Django DurationField format options - python

Good evening. I have a question do you have some snippet for DurationField to show it in django admin in format HH:MM? I can't find anything over the internet and 3rd party apps doesn't work in new django. Thank you for help.
Model:
from django.db import models
# Create your models here.
class Aircraft (models.Model):
id = models.AutoField(primary_key=True)
registration = models.CharField(max_length=7)
#hours to maintenance
hours_to_maintenance = models.DateTimeField(help_text = "test", null = True)
#current hours
ch = models.TimeField(help_text = "test", null = True)
#rm = models.IntegerField(help_text = "test", null = True)
added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,)
def __str__(self):
return self.registration

Related

Exception Value: NOT NULL constraint failed: send_appdata.product_id_id

I am using a custom user model and when i am trying to reference it in other model i am getting an error.
Exception Value:
NOT NULL constraint failed: send_appdata.product_id_id
views.py
from django.contrib.auth import get_user_model
AppOnboarding = get_user_model()
# get data from json
#api_view(['POST'])
def index(request):
product_id = AppOnboarding.objects.get(pk=request.data['product_id'])
product_name = request.data['product_name']
product_url = request.data['product_url']
subject = request.data['subject']
body = request.data['body']
recipient_list = request.data['recipient_list']
sender_mail = request.data['sender_mail']
email_type = request.data['email_type']
broadcast_mail = request.data['broadcast_mail']
email_status = status.HTTP_200_OK
location = request.data['location']
# make an object of AppData
app_data = AppData(product_id=product_id, product_name=product_name, product_url=product_url,
subject=subject, body=body, recipient_list=recipient_list, sender_mail=sender_mail, email_type=email_type, broadcast_mail=broadcast_mail, email_status=email_status, location=location)
# save it to DB
app_data.save()
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth import get_user_model
AppOnboarding = get_user_model()
class AppData(models.Model):
# app_data_id = models.IntegerField(primary_key=True)
product_id = models.ForeignKey(AppOnboarding, on_delete=models.PROTECT)
product_name = models.CharField(max_length=100)
product_url = models.URLField()
subject = models.CharField(max_length=100)
body = models.TextField()
recipient_list = models.TextField()
sender_mail = models.EmailField(max_length=254)
email_type = models.CharField(max_length=50)
broadcast_mail = models.BooleanField()
email_status = models.CharField(max_length=50)
date_time = models.DateTimeField(auto_now_add=True)
location = models.CharField(max_length=100)
AppOnboarding is a custom user model in a different app.
I explored the similar questions but could not resolve the issue.
Any help is highly appreciated.
Have added this foreign key product_id recently (after the rest of model fields)?
If yes, you need to make it nullable (null=True) and run makemigrations then migrate
Found the error, when I manually checked using python shell, Apponboarding.objects.get(id=1) was returning Does not exits but Apponboarding.objects.get(id=2) and others it was returning email address instead of id. It is still not clear how the id started from 2 instead of 1 (since it is auto field) and why email is getting returned instead of id.

Rest Framework Seralizer always returns false from is_valid

I am setting up a database of cars inventory and trying to filling it up with json data provided by an api. What is wrong with my seralizer?
This is on Window, Django2 and Sqlite database, and Python3.
Please help me to get the desired output ! Thanks
seralizer.py
from rest_framework import serializers
from .models import SavedInventory
class EmbedSerializer(serializers.ModelSerializer):
class Meta:
model = SavedInventory
fields = '__all__'
views.py
vin = form.cleaned_data['vin']
links={"X-RapidAPI-Host":settings.VINDECODERHOST, "X-RapidAPI-Key": settings.VINDECODERKEY}
r = requests.get("https://vindecoder.p.rapidapi.com/decode_vin?vin="+ vin + "&key=" + settings.VINDECODERKEY)
json = r.json()
serializer = EmbedSerializer(data=json)
if serializer.is_valid():
saved = serializer.save()
return render(request, 'saved.html', {'embed': embed})
else:
return HttpResponse('<h1>ERROR Seralizer</h1>')
Sqlite Based
models.py
from django.db import models
# Create your models here.
class SavedInventory(models.Model):
vin = models.CharField(max_length=15)
year = models.CharField(max_length=4)
make = models.CharField(max_length=20)
model = models.CharField(max_length=20)
trim_level = models.CharField(max_length=20)
engine = models.CharField(max_length=50)
style = models.CharField(max_length=50)
steering_type = models.CharField(max_length=15)
anti_brake_system = models.CharField(max_length=80)
tank_size = models.CharField(max_length=50)
overall_height = models.CharField(max_length=50)
overall_length = models.CharField(max_length=50)
overall_width = models.CharField(max_length=50)
highway_mileage = models.CharField(max_length=30)
city_mileage = models.CharField(max_length=30)
JSON Response from API
"success":true,
"specification":{
"vin":"JNKCA31A61T027494",
"year":"2001",
"make":"Infiniti",
"model":"I30",
"trim_level":"Touring",
"engine":"3.0L V6 DOHC 24V",
"style":"Sedan (4-Door)",
"made_in":"Japan",
"steering_type":"R&P",
"anti_brake_system":"4-Wheel ABS",
"tank_size":null,
"overall_height":"56.50 inches",
"overall_length":"193.70 inches",
"overall_width":"70.20 inches",
"standard_seating":"5",
"optional_seating":null,
"highway_mileage":"28 miles/gallon",
"city_mileage":"20 miles/gallon",
"fuel_type":"Gasoline",
"drive_type":"FWD",
"transmission":"Automatic",
"features":[
"Air Conditioning",
"Cruise Control",
"Power Seat (Driver)",
"Remote Trunk Release",
"Anti-theft System",
"Front Airbags (Driver)",
"Tachometer"
]
},
"vin":"JNKCA31A61T027494"
}

Django model form field to have a user dropdown list based on a condition

In a Django Modelform (Product_definition), i want to have a dropdown(Merchant name) which will show users only if the their designation in User form is "Merchant".
is it possible that I could get the list of users for the dropdown based on this condition .Please note that i don't require it to be a foreign key as connecting the models is not required.
This is the form which contains the Designation :
from django.contrib.auth.models import User
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
#extra UserAttribute
MERCHANT = 'MR'
FABRIC = 'FR'
WASHING = 'WS'
PRINT = 'PR'
PLANNER = 'PL'
DESIGNATION_CHOICES =(
(PLANNER,'Planner'),
(MERCHANT,'Merchant'),
(FABRIC,'Fabric'),
(WASHING,'Washing'),
(PRINT,'Printing'),
)
Designation =models.CharField(
max_length = 20,
choices = DESIGNATION_CHOICES,
default= 'PLANNER'
)
def __str__(self):
return self.user.username
and this is the form with Merchant Name where I want the names of all merchants to appear.
class Product_definition(models.Model):
Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True)
style_name = models.CharField(max_length=15, blank = True, null = True)
color = models.CharField(max_length=15, blank = True, null = True)
Order_qty = models.PositiveIntegerField()
SMV = models.FloatField()
MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select')
def __str__(self):
return self.Order_number
I have created a foreign key for now but I don't require it and it doesn't list the names of only the merchant in the drop down.
I think you can do it like this using ModelChoiceField:
class ProductForm(forms.ModelForm): # please use CamelCase when defining Class Names
MERCHANT = forms.ModelChoiceField(queryset=UserProfileInfo.objects.filter(Designation=UserProfileInfo.MARCHENT)) # Please use sname_case when naming attributes
class Meta:
model = Product_definition # Please use CamelCase when defining model class name
fields = '__all__'

Did not work django-filters in Django app

I am trying to use django filters for my application, but it always returns the same error.
from django.contrib.auth.models import Promoters
ImportError: cannot import name 'Promoters' from 'django.contrib.auth.models' (C:\Users\tymot\Desktop\my_app\env\lib\site-packages\django\contrib\auth\models.py)
Has anyone had a similar problem? How best to solve it? change of django versia?
or maybe there are any alternatives?
My django version (2, 1, 2, 'final', 0), Python 3.6.
EDIT:
I am trying to add a search engine to my site, well i installed 'pip install django-filter' and added this to my settings.py. Next i created filters.py:
from django.contrib.auth.models import Promoters
import django_filters
class PromotersFilter(django_filters.FilterSet):
class Meta:
model = Promoters
fields = ['age', 'profession', 'sex', 'city']
for my models.py
class Promoters(models.Model):
MEAN = 'M'
WOMAN = 'W'
SEX = (
(MEAN, 'Mean'),
(WOMAN, 'Woman'),
)
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
photo = models.FileField(null=True, blank=True)
age = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(99)])
profession = models.CharField(max_length=50)
sex = models.CharField(max_length=1, choices=SEX, default=MEAN)
city = models.CharField(max_length=50)
hobby = models.CharField(max_length=50)
number_friends = models.IntegerField(validators=[MinValueValidator(0)])
related_brands = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(10)])
user_group = models.CharField(max_length=200)
activities_month = models.IntegerField()
fb_links = models.CharField(max_length=200)
and also create a views.py
def Promotors(request):
#promoters
campaignlist = Campaign.objects.filter(customer_name=request.user)
promoters_list = Promoters.objects.all()
#search rama
promoters_filter = PromotersFilter(request.GET, queryser=promoters_list)
#context
context = { 'campaignlist':campaignlist, 'filter':promoters_filter}
return render(request, 'account/costumer_profile.html', context)
Then when I try to start the server, I get an error: 'ImportError:...'
On other forums there is information that this may be due to the mismatch of django-filters to the django version.
But I did not find any information on how to solve this problem to implement the search engine.

Django import export Line number: 1 - u"Column 'id' not found

I am trying to import excel documents into a Django DB. I have added the following code to admin.py and model.py. There seems to be an error in the development of Django. I have read through several different documentations about how to fix this error. But I am still a little lost on how to implement it exactly.
In the Trace it keeps saying that my excel document needs an id field. There is no id field in my excel docs nor did I tell my model to look for an id field.
The documentation that I have found states that I should use get_or_init_instance here:
https://django-import-export.readthedocs.org/en/latest/import_workflow.html
Any help that you guys could give would be great.
admin.py
class VinCasesAndCampaignsResource(resources.ModelResource):
published = fields.Field(column_name='published_date')
def get_instance(self, instance_loaders, row):
return False
class Meta:
model = VinCasesAndCampaigns
widgets = {}
fields = ('VIN','LatestOpenCaseID','LatestClosedCaseID',
'OpenDate', 'CloseDate', 'HasCampaigns',)
import_id_fields = ['VIN']
export_order = ('VIN',)
exclude = ('id')
model.py
class VinCasesAndCampaigns(models.Model):
VIN = models.CharField(max_length=30)
LatestOpenCaseID = models.DateField()
LatestClosedCaseID = models.DateField()
OpenDate = models.DateField()
CloseDate = models.DateField()
HasCampaigns = models.BooleanField(default = False)
HasOpenCampaigns = models.BooleanField(default = False)
HasCases = models.BooleanField(default = False)
HasEstimates = models.BooleanField(default = False)
HasDwell = models.BooleanField(default = False)
HasClaims = models.BooleanField(default = False)
exclude = ('id',)
Trace:
> Line number: 1 - u"Column 'id' not found in dataset. Available columns
> are: [u'VIN', u'LatestOpenCaseID', u'LatestClosedCaseID', u'OpenDate',
> u'CloseDate', u'HasCampaigns', u'HasOpenCampaigns', u'HasCases',
> u'HasEstimates', u'HasDwell', u'HasClaims']" Traceback (most recent
> call last): File
> "/Users/USER/anaconda/lib/python2.7/site-packages/django_import_export-0.2.8.dev0-py2.7.egg/import_export/resources.py",
> line 342, in import_data instance, new =
> self.get_or_init_instance(instance_loader, row)
You can solve this problem by using the following steps:
Step 1 first goto C:/Users/am.sa18/Desktop/myenv/Lib/site-packages/import_export/resources.py
Step 2 open resources.py in the editor.
Step 3 do change in line no 84, its looks like this
Step 4 import_id_fields = ['id'] Where 'id' by-default set by import_export package,
you can change 'id' by your primary key of the model.
After adding primary key : import_id_fields = ['primary_key']
Step 5 Save resources.py file and run the server.
Here is a working example. I also used "exclude" and it works and no need to add exclude = ('id',) in models.py.
My data set does not contain "id" field.
Python 2.7 | Django 1.11 | Django Import export 1.0.0 (2018-02-13)
Models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
# Create your models here.
class CourseList(models.Model):
short_code = models.CharField(max_length=10)
course_id = models.CharField(max_length=50,null=True,blank=True,unique=True)
title = models.CharField(max_length=100)
status = models.CharField(max_length=10)
count_current = models.IntegerField(default=0)
count_cumulative = models.IntegerField(default=0)
start_date = models.CharField(max_length=20)
end_date = models.CharField(max_length=20)
pacing_type = models.CharField(max_length=10)
updated_date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['end_date']
def __unicode__(self):
return self.title
resources.py
from import_export import resources, fields
from .models import CourseList
class CourseListResource(resources.ModelResource):
status = fields.Field(column_name='availability', attribute="status")
short_code = fields.Field(column_name='catalog_course', attribute="short_code")
title = fields.Field(column_name='catalog_course_title', attribute="title")
count_current = fields.Field(column_name='count', attribute="count_current")
count_cumulative = fields.Field(column_name='cumulative_count', attribute="count_cumulative")
class Meta:
model = CourseList
import_id_fields = ('course_id',)
exclude = ('id', 'updated_date',)
skip_unchanged = True
fields = ('status', 'short_code','course_id', 'title', 'count_current', 'count_cumulative', 'end_date', 'pacing_type', 'start_date', )
admin.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
# Register your models here.
from import_export import resources
from courselist.models import CourseList
from courselist.resources import CourseListResource
#admin.register(CourseList)
class CourseListAdmin(ImportExportModelAdmin):
resource_class = CourseListResource
list_display = ('id', 'course_id', 'title', 'start_date', 'end_date')
Just create an empty column namely id before already created columns and then import the same file via Django import_export.
Make sure id column should be of your first column in the CSV or Excel file
include field id in the field of ModelResource
fields = ('id','VIN','LatestOpenCaseID','LatestClosedCaseID',
'OpenDate', 'CloseDate', 'HasCampaigns',)
and in your excel file add a column with filed id with empty values. this add a new field with autoincrement.
file.xls
id VIN OpenDate ...
23 05-10-2018
24 05-11-2018
admin.py should be:
class CourseListAdmin(ImportExportModelAdmin):
resource_class = CourseListResource
list_display = ('id', 'course_id', 'title', 'start_date', 'end_date')
admin.site.register(CourseList, CourseListAdmin)
I had the same issue with the decorator #admin.register. I probably followed the same old tutorial. See Admin Integration in the real docs for django-import-export.

Categories