Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiple annotates are not working properly
Using multiple annotate queries giving unexpected results. When I use annotate separately, it works fine. event_queryset = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter), sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30), rating = Cast(F('sales')/F('days'), FloatField(2))) or event_queryset = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter)).annotate(sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30)).annotate(rating = Cast(F('sales')/F('days'), FloatField(2))) In both queries, days variable is giving wrong values for some items. Sales is fine. And if I do this: event_queryset_days = OrderItemTable.objects.annotate(days=Sum(TIMESTAMPDIFF(f_date_ord, l_date, unit='Day')*F( 'prev_order_items__qty')/30, filter=filter)) event_queryset_sales = OrderItemTable.objects.annotate(sales=Sum(TIMESTAMPDIFF(f_date_sale, l_date, unit='Day')*F( 'sales_order_items__qty')/30) Both give correct values. Can anyone tell what I am doing wrong. Or how can calculate rating if I use separate queries for days and sales. -
Unable to run background tasks with Celery + Django + Gunicorn
Stack: Python v2.7 Django v1.11 Celery v4.3.0 Gunicorn v19.7.1 Nginx When I try to run django server and celery manually the async tasks executes as expected. The problem comes when I am deploying django project using Gunicorn plus Nginx. I tried running Celery using supervisor but it didn't help. views.py def _functionA(): _functionB.delay() #where _functionB is registered async task. settings.py # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' gunicorn.service [Unit] Description=Gunicorn application server.... After=network.target [Service] User=root Group=www-data WorkingDirectory=<myprojectdir> Environment=PYTHONPATH=<ENV> ExecStart=<myprojectdir>/env/bin/gunicorn --workers 3 --access-logfile access_gunicorn.log --error-logfile error_gunicorn.log --capture-output --log-level debug --bind unix:<myprojectdir>/myproject.sock <myproject>.wsgi:application [Install] WantedBy=multi-user.target myproject_nginx.conf server { listen 8001; location / { include proxy_params; proxy_pass http://unix:<myprojectdir>/myproject.sock; } } celery worker celery worker -B -l info -A myproject -Q celery,queue1,queue2,queue3 -n beat.%h -c 1 Can anyone help me with my question(s) below: Why is that when Django is deployed using Gunicorn and nginx the Celery worker doesn't executes tasks whereas when ran manually it is able to execute the tasks i.e. when ran with python manage.py runserver ... . -
Custom validation and saving of django inline forms
I am trying to represent a base model which has some attributes that change over time. I have gotten the model definitions pretty set in stone -- most of this code just enforces that there can be no overlaps between DatedModelState instances on any given BaseModel instance. class DatedModelState(models.Model): id = models.AutoField(primary_key=True) base_model = models.ForeignKey(BaseModel, related_name='dated_states', on_delete=models.CASCADE) begin_date = models.DateField() end_date = models.DateField() def clean(self, *args, **kwargs): super().clean(*args, **kwargs) other_dated_states = self.base_model.dated_states.exclude(id=self.id) # Code omitted, but validate that there are no date overlaps with any other DatedModelStates... To interact with this through the admin console, I am using an admin.TabularInline together with a base ModelAdmin. class DatedResourceStateInline(admin.TabularInline): model = models.DatedResourceState extra = 0 # Do not show extra 'empty' records @admin.register(models.BaseModel) class BaseModelAdmin(admin.ModelAdmin): list_display = (...) fields = (...) inlines = [DatedResourceStateInline] My issue comes when I try to save the ModelAdmin form, including all inline DatedResourceState forms, where I have changed a start/end date in more than one DatedResourceState. A quick and dirty example... Current State id begin_date end_date 1 - 2019-07-05 -> 2019-07-06 2 - 2019-07-06 -> 2019-07-20 If I try to move the boundary one day later, my validations fail Attempted State id begin_date end_date 1 - … -
How can I run functional tests from a django view?
I would like to run the functional tests in the webpage using python,django. Can't I just use management.call_command like this in my views.py ? call_command('test', 'folder.tests.Mytest') Mytest inherits from TestCase of Selenium and contains the classic setUp() and test_() methods. Here the error shown is: "ValueError: signal only works in main thread" Cannot the command be called from the views? Thank you -
Error in Django email validation in model forms(signup)
I am trying to validate the email of the signup form if the user with that email already exists it should show an error like email already exists but I am not able to achieve this with the below code forms.py from django.forms import ModelForm from django import forms from . models import signup class signupForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = signup fields = ['username', 'email' , 'password','confirm_password'] def clean(self): cleaned_data = super(signupForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) email = self.cleaned_data.get('email') try: match = signup.objects.get(email=email) print(match) except signup.DoesNotExist: # Unable to find a user, this is fine return email # A user was found with this as a username, raise an error. raise forms.ValidationError('This email address is already in use.') class loginForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = signup fields = ['email','password'] it is showing AttributeError at /signup 'str' object has no attribute 'get' this error -
django form not submitting due to slug and foreign key
My django cabin form is not submitting. I have applied foreign key and slug in my cabin's model and after that my form stopped getting submitted. whenever I enter all the fields and hit submit button,the form page is getting reloaded and no data is getting submitted.Most Importantly it is not showing any error so that I can fix it.I have tried and searched a lot about it and tried different things but still it didn't work. I am stuck to it. Please help!! class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) class Cabin(models.Model): random_string = str(random.randint(100000, 999999)) centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE,blank=True,null=True) code = models.CharField(max_length=6, blank=False, unique=True, default=random_string) total_seats = models.IntegerField(blank='False') category=models.CharField(max_length=100, default=False) booked_date=models.DateField(blank='False') released_date=models.DateField(blank='False') price=models.IntegerField(blank=False, default=None) slug = models.SlugField(unique=False,default=None) def save(self, *args, **kwargs): self.slug = slugify(self.category) super(Cabin, self).save(*args, **kwargs) In views.py file class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): self.object = form.save(commit=False) self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0] … -
No module found at django deployment (apache,wsgi)
I have deployed a small django application, and I want to display a graph on a page. For the realization of graphs in python I use the plotly library. In production, the import of plotly worked very well, no worries. But when deploying django with apache2 and wsgi, there is an import problem that the plotly module is not found, I don't know how to do that for several hours now. If some have already encountered this kind of problems.... thank you for your feedback -
TypeError: 'NoneType' object is not callable - Beautifulsoup 4
I'm trying to save the scraped data in the Postgres database. I want to use django models for this. I tried to use the Psycopg2 package before, but I found out that it is unnecessary so I decided to use just django models. the data did not go to the database also when I used the Psycopg2 package. I get this error: Traceback (most recent call last): File "/home/xxxx/Desktop/project/django/tnapp/scrap.py", line 61, in <module> scraped_author = author(name='author name') TypeError: 'NoneType' object is not callable Scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome(ChromeDriverManager().install()) contents = [] authors = [] for article in all_links: d.get(article) … -
Overriding Django Save and returning id if exists
I am using Django_rest framework to upload files to my site. However, often I am uploading the same file, so I wish to avoid uploading the same file multiple times. To overcome saving multiple copies of the same file, I have overwritten the save model to upload a file and delete the file if it already exists. This works although I feel it is alot of not needed uploading. However, I can't get the existing id to be returned from my serialiser to not do this. is there a better solution to this? Model.py class IMAGES(models.Model): IMAGE = models.FileField(max_length=150,upload_to='documents/%Y/%m/%d') def __unicode__(self): return str(self.id) def save(self, *args, **kwargs): imstring="documents/" + datetime.now().strftime('%Y') + "/" + datetime.now().strftime('%m') + "/" + datetime.now().strftime('%d') + "/" + str(self.IMAGE) try: this = IMAGES.objects.filter(IMAGE=imstring)[0] # This sees if the filename is already in the database. if this.IMAGE: # if it is, # delete the file and replace it. os.remove(this.IMAGE.path) except IndexError: pass except ObjectDoesNotExist: pass super(IMAGES, self).save(*args, **kwargs) serializer.py class IMAGESEntrySerializer(serializers.ModelSerializer): class Meta: model = IMAGES fields = ( 'id', 'IMAGE') def create(self, validated_data): result, other = IMAGES.objects.get_or_create(**validated_data) return result def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.NAME … -
How to load jquery properties to extended template from base template, jquery included in base template
i want to get jquery propertys from base template to extended template headerfooter.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" href="{% static 'medicure/images/favicon.png' %}" type="image/png" /> <title>Medicure</title> <!-- Bootstrap --> <link href="{% static 'medicure/css/bootstrap.min.css' %}" rel="stylesheet"> {% block headerfooter %} {% endblock %} <script src="{% static 'medicure/js/jquery.min.js' %}"></script> <!-- Bootstrap --> <script src="{% static 'medicure/js/bootstrap.min.js' %}"> </script> <!-- FastClick --> <script src="{% static 'medicure/js/fastclick.js' %}"></script> <!-- NProgress --> <script src="{% static 'medicure/js/nprogress.js' %}"></script> company.html {% extends "headerfooter.html" %} {% load staticfiles %} {% block headerfooter %} <script src="{% static 'masters/js/masters.js' %}"></script> {% endblock %} in the above example i have included jquery in headerfooter.html, and i have included masters.js file in company.html, in master.js javascript is working and jquery is not working, if i include below script on top of masters.js then jquery is working fine, so i need to include jquery on every page even it is extended. <script src="{% static 'medicure/js/jquery.min.js' %}"></script> -
How can i get a object from a other function in django
I have two functions projectTimerStart to start the timer and projectTimerStop i want to use the object which is created in projectTimerStart and i want to end the time when projectTimerStop , and this should be saved in a database ps: Both the functions are not in class they are normal functions enter code here def projectTimerStart(request, slug): project_detail = Project.objects.get(slug=slug) b = ProjectTimer(time_started=datetime.now(), working_project=project_detail, working_freelancer=request.user ) b.save() return HttpResponseRedirect(reverse('project_timer', kwargs= {"slug":slug})) def projectTimerStop(request, slug): project_detail = Project.objects.get(slug=slug) #i want something here super method or something return HttpResponseRedirect(reverse('project_timer', kwargs= {"slug": slug})) -
Need guide lines or hints to use `graphene-python + django_filters` query on `JSONField`?
I am practicing GraphQL because it offs load backend burden a lot comparing to django-restframework in some use cases. Here is my models.py from django.contrib.postgres.fields import JSONField from django.db import models class Fauzan(models.Model): name = JSONField() schemas.py import graphene from graphene_django import DjangoObjectType from fauzans.models import Fauzan class FauzanObjectType(DjangoObjectType): class Meta: model = Fauzan class Query(graphene.ObjectType): fauzans = graphene.List(FauzanObjectType) def resolve_fauzans(self, info): return Fauzan.objects.all() schema = graphene.Schema(query=Query) With limited documents. I can not imagine what is the the implementation of search, filter according to django_filters How do I do search, filter over the JSONField using django_filters? -
How to set up free SSL certificate for my site running on google cloud plateform. (Windows 10)
I have hosted my website on google cloud platform on a windows server(newbie). Buyed domain from godaddy. I have no idea how to put SSL certificate for my site running on 0.0.0.0:80 port. Its simple django webapp. Any one can help? Please. I have tried using but didn't work ''' pip install django-extensions pip install Werkzeug pip install pyOpenSSL ''' -
How to override save method of model to change filefield name?
I have a ModelForm in my django app which allows a user to upload a file and store it to aws storage s3. What I wish to do is rename the file from its original name to the name of the field timestamp. What I have tried so far is overriding the save method of the model. Here is my code: models.py from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone import time class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) timestamp = models.CharField(max_length=1000, default= time.time()) def __str__(self): return self.csv_file def save(self, *args, **kwargs): self.csv_file.name = self.timestamp + ".csv" super(CSVUpload, self).save(*args, **kwargs) forms.py from django import forms from .models import CSVUpload import time class CsvForm(forms.ModelForm): csv_file = forms.FileField(widget=forms.FileInput( attrs= { 'class': 'form-group', } )) timestamp = forms.CharField(initial = time.time()) class Meta: model = CSVUpload fields = ('csv_file', 'timestamp',) def save(self): csvfile = super(CsvForm, self).save() return csvfile my view: def uploadcsv(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): return redirect(about) else: form = CsvForm() return render(request, 'myapp/uploadcsv.html',{'form': form}) Despite that, when I upload the file it doesnt arrive on the bucket. I am not sure what is wrong but I suspect it lies on the save method. Could … -
Ajax function not working properly for deleting without refreshing page
I am working on a problem where I need to delete an entry in database without refreshing the list page. However, with the ajax function and view that I have created, the data is getting deleted but success function is not changing to true.The list page is displayed as it is, and on manually refreshing the deleted data is not displayed. Also, since I am new to ajax I have less idea about what to put in data dictionary in ajax for deleting.What am I doing wrong in the code? Please help me in doing so without page refresh.(I need to stay on the centrelist page).Thanks in advance. <script> $(document).on('click','#delete',function(){ var a ; a=confirm("Do you really want to delete the user?"); if(a==true){ var url = "{% url 'NewApp:centredelete' pk=1%}" var id = $(this).attr('name') $.ajax( { type:"GET", url: url.replace('1',id), data:{ delete:true }, success: function( data ) { if(data.success == true){ $(id).remove(); } } })} }); </script> views.py def CentreDeleteView(request, pk): data = {'success': False} centre = Centre.objects.get(pk=pk) print(centre) if request.method == 'GET': try: if centre: centre.delete() data['success'] = True else: data['success'] = False data['error'] = "unsuccessful!" except Centre.DoesNotExist: return redirect('/NewApp/centrelist') return JsonResponse(json.dumps(data)) -
select columns with group by one column django orm
I trying to get the name, today_date, date_2 from event table with group by name of the event with sql I am able to get the details but while using django orm I am getting duplicate records. select name, today_date, date_2 from event group by name; --> SQL Query Can anyone help me to convert above SQL query to django ORM query? -
ModelMommy makes Django JSONField as a blank
I had tried this snippet By customizing the MySQL line with PostgresQL from model_mommy import mommy def generator_function(): return {} mommy.generators.add('django.contrib.postgres.fields.JSONField', generator_function) It does not work model_mommy fills my JSONField with {}. Question: How can I have a dummy key: value in it? -
How to select objects of a model related to my model
I'm creating a filtering system for my application and I would like to render <select> fields, pre-filled with options possible. Lets assume I have a model called Exam which has relation to Student and this has relation to StudentProfile - I'm filtering Exam objects by field has_passed in student's profile so I'm creating a query such as: student__student_profile_has_passed and passing it to django's filter() function and it works. Now however, I'd like to render html form with and all possible <option>s, to do so I need to find the mentioned possible options. How can I find all objects from such a query string as above to get all the objects of student__student_profile from my Exam model? This also has to work regardless of how long the chain of relations is assuming the relations are all correct. -
object.save() seems to be created but is not registered in db
How is it possible? This is the strangest bug I ever had. I register an object from a form like I ever do. if request.is_ajax() and request.POST: if form.is_valid(): mission = form.save(commit=False) mission.generic_name = p.generic_name mission.created_by = request.user mission.save() At runtime, inspecting this, I can see that mission seems to be created. It has a pk and I can run save() method as well without any errors. Despite all of this, mission is not inserted in the database. If I check in a python console and try to get it using the same pk I got in the ipdb traces, it raises a DoesNotExistsException. Mission.objects.get(pk=4915) (...) rdt.prestations.models.Mission.DoesNotExist: Mission matching query does not exist. Here is the form: class MissionForm(forms.ModelForm): prestaId = forms.CharField(widget=forms.HiddenInput) files = forms.ModelMultipleChoiceField(queryset=None, required=False) class Meta: model = Mission fields = ['name', 'length', 'expected_delivery_date', 'supplier', 'guideline', 'prestation'] widgets = { 'prestation': forms.HiddenInput(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) p = kwargs['initial'].get('prestation') self.fields['supplier'] = forms.ModelChoiceField( queryset=Supplier.objects.available_for_langs( p.price.lang_src, p.price.lang_dest) ) self.fields['files'] = forms.ModelMultipleChoiceField( queryset=p.files.source().exclude( is_duplicate=False, file='', ), required=False ) I precise that form.is_valid() and form.save() doesn't throw any exception at all. It's just that the object is not created despite it has at runtime a pk. save() method is … -
Django formTypeError: signupinfoform.Meta.fields cannot be a string
I created the model with the below fields and it is raising ann error as TypeError: signupinfoform.Meta.fields cannot be a string. Did you mean to type: ('confirm_password',)? from django.db import models from django.contrib.auth.models import User # Create your models here. class signup(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) confirm_password = models.CharField(max_length=200) def __str__(self): return self.user.username forms.py from django import forms from . models import signup from django.contrib.auth.models import User class signupform(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username','password','email') class signupinfoform(forms.ModelForm): confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = signup fields = ('confirm_password') -
Why does python stop when django starts?
After creating a new Django project that is linked to the MySql database, if I try running it with runserver, I get a message that "Python has stopped working" This concerns a new Python 3.5.3, running MySQL 8.0, Django 1.11. There is not a long time any marchair properly. workon my_virt_env python manage.py runserver Python stopped -
annotation for time difference
I have some models and I have to calculate some value like sum of all (difference between date created and today) in days. 1st order - 01/07/2019, diff from now = 4 days * 2(quantity) 2nd order - 03/07/2019, diff from now = 2 days * 3(quantity) Sum = 14 # same foe sales model correct formula is this: Sum(Each Sale.time from now in month)/Sum(Each order.time from now in month) '.' is for multiply First, I am tried this to calculate Sum of time differences. current_date = datetime.date.today() time_diff = OrderItemTable.objects.annotate(days=Sum((F('prev_order_items__order_id__created_at')-current_date))) but output is this 181715600.0. This is not correct if it's in seconds. These are relavent models and fields. class Sales(models.Model): # sales detail of items item_id = models.ForeignKey('Item', models.DO_NOTHING) date = models.DateField() sale_qty = models.IntegerField() item_id = models.ForeignKey('OrderItemTable', models.DO_NOTHING, related_name='sales_order_items') # some more fields class Item(models.Model): # detail of items, around 3000 items item_name = models.CharField(max_length=127) # some more fields class Order(models.Model): # order detail of each order created_at = models.DateField(auto_now_add=True) # some more fields class Ordered_items(models.Model): # item detail for all order order_qty = models.IntegerField() item_id = models.ForeignKey(OrderItemTable, models.DO_NOTHING, blank=True, null=True, related_name='prev_order_items') order_id = models.ForeignKey(OrderOrderTable, models.DO_NOTHING, blank=True, null=True, related_name='prev_order_order') # some more fields -
How can I display the db values of a row in a form before I update the form?
I'm trying to display the employee data after filtering the DB by pk which I passed via the URL. I can update the form, although I don't want the form fields to be empty since I just want to update, which means its not all the fields I'm going to touch forms.py class AddEmployeeForm(forms.Form): genderset = [(0,'--Select an Option--'),('Male','Male'), ('Female', 'Female')] marital_status_set = [(0,'--Select an Option--'),('Married','Married'), ('Single', 'Single')] employment_type_set = [(0,'--Select an Option--'),('Contract','Contract'), ('Full-Time', 'Full-Time'),('Intern', 'Intern')] employment_status_set = [(0,'--Select an Option--'),('Active','Active'), ('Inactive', 'Inactive')] first_name = forms.CharField(label = "First Name ", max_length = 200) last_name = forms.CharField(label = "Last Name ", max_length = 200) employee_id = forms.IntegerField() email = forms.EmailField(label = "Email ", max_length = 200) address = forms.CharField(label = "Address", max_length = 200) role = forms.CharField( max_length = 200) date_of_birth = forms.DateField() join_date = forms.DateField() end_date = forms.DateField() location = forms.CharField( max_length = 200) hod = forms.ModelChoiceField(queryset=Department.objects.only('lead')) phone_number = forms.CharField( max_length = 200) employment_type = forms.ChoiceField( choices = employment_type_set) employment_status = forms.ChoiceField( choices = employment_status_set ) marital_status = forms.ChoiceField( choices = marital_status_set ) gender = forms.ChoiceField( choices = genderset ) department = forms.ModelChoiceField(queryset=Department.objects.only('dept_name')) credentials = forms.FileField() passport = forms.FileField() date_added = forms.DateTimeField( initial = datetime.now, widget=forms.HiddenInput()) views.py @login_required(login_url='/accounts/login') def edit(request, … -
Django GenericForeignKey vs set of ForeignKey
I would like to discuss the case of using GenericRelation and GenericForeignKey. I have the 2 models, Appartement and Mission. And I need to create LockCode model which will be connected to Appartment or Mission. I have added the GenericForeignKey to the LockCode and GenericRelation to the Appartement and Mission: class LockCode(TimeStampedModel): context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) context_id = models.PositiveIntegerField() context = GenericForeignKey('context_type', 'context_id') class Mission(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='mission' ) class Appartment(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='appartment' ) It works ok. But added the complexity level to compare with adding 2 ForeignKeys, for appartement and for mission. class LockCode(TimeStampedModel): appartement = models.ForeignKey(Appartement, null=True, blank=True) mission = models.ForeignKey(Mission, null=True, blank=True) So wdyt should I keep the GFK or use 2 simple FK? -
some fields aren't being saved in django-models
am inserting new records in a model using a function-based view but the problem is some fields aren't being saved. I get all fields through request.POST.get(field_name) and them asssign to a varible before saving them to corresponding field in a particular model. ------- start of View ------- if request.method == "POST": st_exam = exam() topic = request.POST.get("topic") auth = request.POST.get("author") date_now = request.POST.get("date_now") st_exam.topic = request.POST.get("topic") st_exam.auth = request.POST.get("author") st_exam.date = date_now st_exam.total_grade = request.POST.get("total_grade") st_exam.semester_id = request.POST.get("semester") st_exam.exam_id = auth[0:2] + topic[0:2] + date_now # st_exam.course = request.POST.get("course") y = datetime.now() st_exam.semester_id = str(y.year) +'-'+request.POST.get("semester") st_exam.save() return redirect('/teacher/') else: return render(request, '500.html', {"error": "Ooops Illegal access"}) ------end of view---- ------start of model ---- exam_id = models.CharField(max_length=40,null=True) date = models.CharField(max_length=40,null=True) total_grade = models.FloatField(null=True) author= models.CharField(max_length=40,null=True) topic = models.CharField(max_length=40,null=True) course = models.CharField(max_length=40,null=True) semester_id = models.CharField(max_length=40,null=True) -----end of model---- -----start of html---- <form method="post" action="/teacher/create/exam/"> {% csrf_token %} <div class="form-group col-md-8"> <label for="topic">Topic</label> <input type="text" name="topic" class="form-control" id="topic"/> </div> <div class="form-group col-md-8"> <label for="grade">Author</label> <input type="text" name="author" class="form-control" id="author"/> </div> <div class="form-group col-md-8"> <label for="date">Date</label> <input type="date" name="date_now" class="form-control" id="date"/> </div> <div class="form-group col-md-8"> <label for="grade">Course</label> <input type="text" name="course" class="form-control" id="grade"/> </div> <div class="form-group col-md-8"> <label for="grade">grade</label> <input type="number" name="total_grade" class="form-control" id="grade"/> …