Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - gitlab-ci - sqlite3 - django.db.utils.OperationalError: unable to open database file
Gitlab CI/CD results in the following Error: django.db.utils.OperationalError: unable to open database file .gitlab-ci.yml: stages: - test pytest: stage: test image: docker/compose:latest tags: - test services: - docker:dind before_script: - docker-compose build - docker-compose run --rm django python manage.py migrate - docker-compose up -d script: - docker-compose run django python manage.py test Django Engine settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I do not push db.sqlite3 to my gitlab project. -
Django: how to give multiple categories to an item
i want to have one Post have multiple Categories kind of like Tags here's what i have already models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default="Non Categorized") Thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") Text = RichTextField(blank=False, null=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) Overview = models.CharField(max_length=400) Date = models.DateTimeField(auto_now_add=True) main_story = models.BooleanField(default=False) def __str__(self): return str(self.title) def get_absolute_url(self): # return reverse('about', args=(str(self.id))) return reverse('home') -
Django Courses Lock and Unlock
I am developing E-Learning Site where I have courses..In the courses I have Sections and within specific section I have video Lectures e.g:if I have django-bootcamp course and within this course I have three sections 1.HTML,2.CSS,3.DjangoBackend ..I want when student click on specific section of course I have created Section in card-component where two buttons already added one for watch and other for Skip..I want when user click on skip button or watch button of specific course section videos next section of Course Lock until user attempt quiz or watch every lectures that are in the selected section of course..For example if user click HTML Section and click watch or takeQuiz next CSS Section lock until anyone of these task perform...I have already add courses,Sections and within sections added video lectures also just Lock next section functionality I want until previous or current Course Section Complete watch or Attempt quiz of this Section and I am developing this site in Django Framework..Plzz help me.Thanks -
How to display legend in toolbox in Google Charts?
I created a scatter chart by using Google Charts in my Django project. It is working clearly but in the toolbox, the legends name does not show just number is displaying. How can I display it? I want to display it as: Argentina(44015314.68,28) my code: var bubbleChart = document.getElementById('mybubbleChart').getContext('2d') var myBubbleChart = new Chart(bubbleChart,{ type: 'scatter', data: { datasets:[{ label: name_1, data:[{x:x_1,y:y_1}], backgroundColor:"#716aca" },{ label: name_2, data:[{x:x_2,y:y_2}], backgroundColor:"#d643ad" },{ label: name_3, data:[{x:x_3,y:y_3}], backgroundColor:"#2ec3be" },{ label: name_4, data:[{x:x_4,y:y_4}], backgroundColor:"#2ec34e" }, { label: name_5, data:[{x:x_5,y:y_5}], backgroundColor:"#decb3e" }, ], }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', }, tooltip: { isHtml: false }, elements: { point: { radius: 10, hoverRadius: 15, } }, scales: { yAxes: [{ ticks: { beginAtZero:true }, }], xAxes: [{ ticks: { beginAtZero:true }, }] }, } }); -
Django: utils.py - name 'short_url' is not defined
I'm seeing the error while querying 'short_url' field from UrlModels NameError at /admin/shortner/urlmodels/5/change/ name 'short_url' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/shortner/urlmodels/5/change/ Django Version: 3.1.6 Exception Type: NameError Exception Value: name 'short_url' is not defined utils.py def code_generator(size=6, chars=string.ascii_lowercase + string.digits ): return ''.join(random.choice(chars) for i in range(size)) def create_shortcut(instance, size=6): new_code = code_generator(size=size) urlmodel = instance.__class__ print(instance) print(instance.__class__) query_exists = urlmodel.objects.filter(short_url==new_code).exists() if query_exists: return create_shortcut(size=size) return new_codefrom models.py class UrlModels(models.Model): url = models.CharField(max_length=1000) short_url = models.CharField(max_length=50, unique=True, blank=True) def save(self, *args, **kwargs): if self.short_url is None or self.short_url == '': self.short_url = create_shortcut(self) super().save(*args, **kwargs) def __str__(self): return self.url -
how to only accept requests with users over the age of a certain age in Django rest framework
the title probably seems very confusing but I will explain it. I am trying to make a feature in my Django rest framework project of which when you sign up it calculates your age then if you are old enough your account is made but if you are not it gives an error of you are not old enough. so my 2 questions are: how would you calculate a users age using their date of birth how would you only create account which have users over the age(in my case I would like to make the threshold 13) I have seen another question on stack overflow here. I added the calculation on the top answer to my models.py but It gives an error in self.birthday(which in the answer would be date_of_birth) saying Unexpected field type(s): (DateField) Possible type(s): (timedelta) (date) -
How to debug Django using daphne
I recently switched from gunicorn to daphne for my Django application, and I am finding it impossible to debug now. When using gunicorn, if I made a mistake the Django debug page would appear, and I could find the issue. With Daphne, I am just getting the nginx error page until I can manually track down the error... Is there a way to make this behave like gunicorn and show the django debug page? -
Django: How do I exclude related fields when using `._meta.get_fields()`?
I'm trying to write a view in Django to export my model data in a csv file. The problem is that I can't figure out how to exclude related fields. Currently, when I run model._meta.get_fields(), the function returns the model's fields and the related model's field, so my view throws an error when I use getattr() using the related field's name. I tried using .is_related() to exclude related fields, but that also excludes the model fields (like ForeignKey). When I call the field name, I can see the class name is ManyToOneRel, but I can't figure out how to access that attribute. Does anyone know how to exclude related fields or figure out if a field is a related model's field? My view is below. Thanks to anyone that can help! class CSVExportView(View): template_name = 'medrec_v2/csv_export.html' def get(self, request, *args, **kwargs): model_list = [m for m in apps.app_configs['medrec_v2'].models if '_' not in m ] # print(model_list) context = {'model_list':model_list} return render(request, self.template_name, context) def post(self, request, *args, ): model_name = request.POST.get("model-sel") model = apps.get_model(app_label='medrec_v2',model_name=model_name) content_type = 'text/csv' datecode = datetime.today().strftime('%y%m%d') file_name = f'{datecode}_medrecv2_{model_name}.csv' response = HttpResponse(content_type = content_type) response['Content-Disposition'] = f'attachment; filename="{file_name}"' header = [f.name.split('.')[-1] for f in model._meta.get_fields() if … -
Django Bootstrap input range slider POST value into db
I have some range slider and I can't figure out why doesn't they post the value into my database. I made this job with select box before and worked fine on the same way. views.py def viselkedestipus_item(request): if request.method == 'POST': vis_01_a = request.POST.get('vis_01_a', "") vis_01_b = request.POST.get('vis_01_b', "") vis_01_c = request.POST.get('vis_01_c', "") vis_01_d = request.POST.get('vis_01_d', "") vis_01_e = request.POST.get('vis_01_e', "") vis_01_f = request.POST.get('vis_01_f', "") vis_01_g = request.POST.get('vis_01_g', "") vis_01_h = request.POST.get('vis_01_h', "") viselkedestipus = Viselkedestipus(vis_01_a=vis_01_a, vis_01_b=vis_01_b, vis_01_c=vis_01_c, vis_01_d=vis_01_d, vis_01_e=vis_01_e, vis_01_f=vis_01_f, vis_01_g=vis_01_g, vis_01_h=vis_01_h) viselkedestipus.save() return render(request, 'stressz/viselkedestipus-form.html') class ViselkedestipusCreateView(CreateView): model = Viselkedestipus form_class = ViselkedestipusForm template_name = 'stressz/viselkedestipus-form.html' def form_valid(self, form): form.instance.user_name = self.request.user return super().form_valid(form) models.py class Viselkedestipus(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vis_01_a = models.IntegerField(null=True) vis_01_b = models.IntegerField(null=True) vis_01_c = models.IntegerField(null=True) vis_01_d = models.IntegerField(null=True) vis_01_e = models.IntegerField(null=True) vis_01_f = models.IntegerField(null=True) vis_01_g = models.IntegerField(null=True) vis_01_h = models.IntegerField(null=True) urls.py urlpatterns = [ path('', views.index, name='index'), path('login/', views.login, name='login'), path('viselkedestipus', views.ViselkedestipusCreateView.as_view(), name='viselkedestipus_item'), ] forms.py class ViselkedestipusForm(forms.ModelForm): class Meta: model = Viselkedestipus fields = ['vis_01_a', 'vis_01_b', 'vis_01_c', 'vis_01_d', 'vis_01_e', 'vis_01_f', 'vis_01_g', 'vis_01_h' ] viselkedestipus-form.html <form method="POST"> {% csrf_token %} <h4>1. question</h4> <br> <div class=""> <label for="slider" class="form-label">A1</label> <input type="range" class="form-range" min="0" max="10" name="vis_01_a" id="vis_01_a" value="0"> </div> 7 more … -
How to store Google credentials in Django model
How I can store Google credentials in Django model without using oaut2client -> DjangoORMStorage? Old version with using oaut2client: storage = Storage(models.GoogleCred, 'act', act, 'credential') storage.put(credentials) But oaut2client does not support Django>=2.0 -
Django - filter a model with multiple parameters passing to function
I have a model as below class Brand(models.Model): name = models.CharField(max_length=32) nationality = models.CharField(max_length=32) class Mobile(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) and I need a query for filtering all Mobiles objects that have the same brand name equal to the input. Input have multiple entry. And it may has no entry, in this situation have to return all the objects. def some_brand_mobiles(*brand_names): query = Mobile.objects.filter(brand__name=Q(brand_names)) return query -
Filtering an user to post something in a group only if he is already a member in that group -> Django Social Media Clone App
I'm new to Django and I've finished a course on Udemy where the project was building a simple social clone. You can look for groups, join or leave them and you can post something in that groups whether you are a member or not. I want a person to post something in a group only if he has already joined the group. In this example, a person can post something whether he is a member of not of that group. I have 2 apps, groups and posts. Here are my models: models.py - groups from django.db import models from django.utils.text import slugify from django.urls import reverse import misaka from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs={'slug':self.slug}) class Meta(): ordering = ['name'] class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta(): unique_together = ('group','user') models.py - posts from django.db import models from django.urls import reverse from django.conf import settings import misaka from groups.models import Group from … -
why am i getting error of AttributeError at /admin/main/consultation/ 'NoneType' object has no attribute 'lastname'
in my admin page when i click on consultation i am getting this error #model.py class doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=True) firstname = models.CharField(max_length = 50) lastname = models.CharField(max_length = 50,default='') dob = models.DateField() address = models.CharField(max_length = 100) countrycode=models.CharField(max_length=5) mobile_no = models.CharField(max_length = 15) gender = models.CharField(max_length = 10) registration_no = models.CharField(max_length = 20) specialization = models.CharField(max_length = 30) rating = models.IntegerField(default=0) qualification = models.CharField(max_length=100,default='') year_of_registration = models.CharField(max_length=50,default='') medical_experience = models.CharField(max_length=50,default='') medical_council=models.CharField(max_length=80,default='') charges = models.IntegerField(default=0) profilephoto = models.ImageField(null=True,blank=True,upload_to="dprofile/") def __str__(self): return "Dr. " + self.firstname +" "+ self.lastname class consultation(models.Model): patient = models.ForeignKey(patient ,null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey(doctor ,null=True, on_delete=models.SET_NULL) diseaseinfo = models.OneToOneField(diseaseinfo, null=True, on_delete=models.SET_NULL) consultation_date = models.DateField() status = models.CharField(max_length = 20) def __str__(self): return self.patient.firstname + " "+self.doctor.lastname + '- Dr.' +self.doctor.firstname + ' ' +self.doctor.lastname -
Django DRF filter and update only runs on server reboot
I have this model: class Applicant(models.Model): first_name = encrypt(models.CharField(max_length=35, blank=False)) last_name = encrypt(models.CharField(max_length=35, blank=False)) email = encrypt(models.CharField(max_length=255, null=True, blank=True)) ... application_status = models.ForeignKey( ApplicationStatus, on_delete=models.CASCADE, related_name="applicant_application_status", null=False, blank=False, ) objects = models.Manager() mask = MaskApplicantManager() With this custom manager: class MaskedQuerySet(models.QuerySet): def mask_applicants(self): return self.exclude(application_status__status="Hired").update( first_name="Masked", last_name="Masked", email="masked@mail.com" ) class MaskApplicantManager(models.Manager): def get_queryset(self): return MaskedQuerySet(self.model, using=self._db) def mask_applicants(self): return self.get_queryset().mask_applicants() What is the best approach for adding this to a generic view? Currently tried this: class AppliedListView(generics.ListAPIView): serializer_class = ApplicantSerializer permission_classes = (IsAuthenticated,) pagination_class = Set10Pagination lookup_url_kwarg = "job_vacancy" def get_queryset(self): vacancy = self.kwargs.get(self.lookup_url_kwarg) applicant = Applicant.mask.filter(job_vacancy=vacancy).order_by("-id") return applicant Although the masked details never run, if I change applicant to: applicant = Applicant.mask.mask_applicants().filter(job_vacancy=vacancy).order_by("-id") Then the error below is returned but on dev server reboot the masked details are applied: 'int' object has no attribute 'filter' Any tips most helpful. -
Django 'QuerySet' object has no attribute 'title'
I am creating E-Learning website and I want to show course content like playlist. For that I use foreign key in models. Here is the code of models.py class Subject(models.Model): subject_id = models.AutoField(primary_key=True) title = models.CharField(max_length=500) desc = models.CharField(max_length=800) slug = models.CharField(max_length=130) image = models.ImageField() timeStamp = models.DateTimeField(default=now) def __str__(self): return self.title class Videos(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=500) cont = models.TextField() vurl = models.URLField(max_length=200) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='videos') position = models.PositiveSmallIntegerField(verbose_name="videono.") slug = models.CharField(max_length=130) timeStamp = models.DateTimeField(default=now) def __str__(self): return self.title Code of Views.py def allsubject(request): subj = Subject.objects.all() # print(videos) context = {'subj': subj} return render(request, 'allsubject.html', context) def pvideo(request, slug): vds = Videos.objects.filter(slug=slug).values() cont = Videos.objects.get(title=vds.title) context = {'vds':vds, 'cont':cont} return render(request, 'pvideo.html', context) I think I made a mistake here cont = Videos.objects.get(title=vds.title) . If anyone has any other idea besides this, so please help me Here is the code of templates to let you know what I really want to do. {% extends 'base.html' %} {% block title %}Free Video Course{% endblock title %} {% block body %} {% for v in vds %} <div class="container"> <div class="embed-responsive embed-responsive-21by9"> <iframe class="embed-responsive-item" src="{{v.vurl}}" allowfullscreen></iframe> </div> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link … -
Django app not recognized when inside another module
I have a project with a structure like this: my-django-project/ venv/ .gitignore README.md my_django_project/ db.sqlite3 manage.py my_django_project/ settings.py my_first_app/ __init__.py inside_app/ __init__.py apps.py serializers.py models.py views.py ... In settings.py i loaded the app like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_first_app.inside_app', ] Running py manage.py runserver gives the following error: File "C:\Users\\Documents\GitHub\tin_api_v2_test\venv\lib\site-packages\django\apps\config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'inside_app'. Check that 'my_first_app.inside_app.apps.InsideAppConfig.name' is correct. However, it works fine when I don't use the Virtualenv. I've also tried putting the venv inside the django project folder to see if that would change anything but it didn't work. -
Could not parse some characters: video.viewers.all.count| ans video.viewers_by_ip.all.count||intcomma
How I can parse or sum two ManyToMany field in the template <div class=""> <h6 class="card-text ml-2 p-2 bd-highlight" style="text-align: left; height: 1px; "><small class="text-muted ">{{ video.viewers.all.count + video.viewers_by_ip.all.count|intcomma }} views . </small></h6></div> -
filtering by one-digit number in MultiSelectField
I have MyModel: class MyModel(models.Model): ELEMENTS_CHOICES = Choices( (1, 'element1'), (2, 'element2'), (3, 'element3'), (4, 'element4'), (10, 'element10'), (12, 'element12'), ) elements = MultiSelectField( _('elements'), choices=ELEMENTS_CHOICES, blank=True, ) I have also some MyModel objects with elements values like below: obj1.elements = ['1', '2', '3', '10', '12'] obj2.elements = ['1', '3', '10', '12'] obj3.elements = ['1', '3', '10'] obj4.elements = ['2'] How do I filter through this field values? The filter I tried to use is: search_id = 2 MyModel.objects.filter(elements_icontains=search_id) It was ok before the two-digit numbers appeared in the MyModel field choices. Now it returns obj1, obj2 (because 12 is on the list, and it contains 2 as the part of it) and obj4. I would like to search just for values with 2 number and get just obj1 and obj4 as results. Currently, the results are objects that contains 2 and 12. What is the right way to filter this field? -
Django save signup form sent via Ajax with fetch() API
I am trying to send a signup form using Ajax and the fetch() API. The Ajax call works and I am able to send data to Django's backend: Ajax call: const sendForm = function(endpoint, formData) { const request = fetch(endpoint, { method: 'post', body: formData, credentials: 'same-origin', // pass CSRF token to the backend headers: { "X-CSRFToken": getCookie("csrftoken"), 'X-Requested-With': 'XMLHttpRequest' } }).then(console.log(formData)) } const getForm = function(endpoint) { const request = fetch(endpoint) .then(response => response.text()) .then(data => modal.innerHTML = data) .then(() => { const signupForm = document.getElementById('signup-form') // prevent default submit behaviour signupForm.addEventListener('submit', function(e){ e.preventDefault() // store form data to send to the backend const formData = new FormData(signupForm) sendForm(endpoint, formData) }) } ) } btnSignup.addEventListener('click', function(){getForm('/accounts/signup')}) If I check the request I get on the backend, I can see that form data is passed correctly and I can access it from the server: views.py if request.method == 'POST': for value in request.POST.values(): print(value) Output: giulio giulio@g.com Password123 Password123 So data is correctly sent to the server. Now, if I try to instantiate the signup form to later save it, it does not work. This is what I'm doing: views.py def SignUpView(request): # if this is a POST request we … -
Passing two Models in update view to a same template
I want to render two models User (built in model) and Profile model to the same template profile_form.html so that the user can update the data of both User model as well as Profile model This is my Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') description = models.TextField() def __str__(self): return self.user.username + "'s Profile" This is my profile_form.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %} Make your Profile {% endblock title %} {% block content %} <div class="container mb-6"> <form action="" method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Submit</button> </form> </div> {% endblock content %} This is my UserUpdateView class UserUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model=User fields=['username', 'first_name', 'last_name'] success_url='/' def test_func(self): x = self.request.user.id y = self.kwargs['pk'] if x == y: return True else: if self.request.user.is_authenticated: raise Http404("You are not authenticated to edit this profile") I want my Profile model's to be below User model's form Please help me with this -
Calling a Python C extension blocks all Django processes/users
Problem I have written a Python C extension (ftaCalculate) in order to improve the performance of a given function that was previously written in pure Python. I have been able to increase the execution speed by a factor of x10, so no problem on this site. import ftaCalculate cs_min = ftaCalculate.mcs(N, tree) However, I am executing this function in a Django framework. The problem is that, until the function ftaCalculate.mcs does not finish, I cannot do anything on my website. When the function was in Python, I could press other buttons and access other URLs. This is specially a problem when several users are working at the same time in the website, because the other users cannot do anything while this function is being executed. Actually, you can see in the following image that one core is at 100% when running the function: Question Do you know any way I could call my Python C extension without "freezing" the Django framework? Possible workaround In the worst case, I could try calling this part of the code with Celery. However, I would prefer another solution, since I do not need Celery when running in pure Python. -
Template inheritance doesn't inherit encoding?
I have managed to deploy my first django app to heroku. After some struggle I got it to work and the main site is loading well however other views result in Server Error 500. Firefox console spits out this: '''The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.''' Now I'm the base.html template I am using on the main page which is loading fine has a charset="UTF-8" metatag defined. I'm extending that template for every other view in my app so I assume this tag should be also included. When I was running that locally then the templates were working fine. Any ideas on how to solve this? -
Django Admin - How to exclude an item for user permissions?
I have an app where it is not inside the permissions that I want the user to access to, but there is one item inside of it that I would like the user to change it content! Is there any solution to do that by using Groups? -
Gunicorn error 203 while setting up django project
I try setting up a django project with nginx and gunicorn but get a gunicorn error 203: My installation is located at path /webapps/sarlex and all project files are owned by user "sarlex" and group "webapps". The virtualenv is located at /webapps/sarlex/environment. Gunicorn is located at /webapps/sarlex/environment/bin/ and owned by user sarlex. Gunicorn confirmation is set in /webapps/sarlex/gunicorn_start.sh: NAME="sarlex" # Name of the application DJANGODIR=/webapps/sarlex/ # Django project directory SOCKFILE=/webapps/sarlex/run/gunicorn.sock # we will communicte using this unix socket USER=sarlex # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=9 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=sarlex.settings # which settings file should Django use DJANGO_WSGI_MODULE=sarlex.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /webapps/sarlex/environment/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Executing gunicorn_start.sh works with environment activated and deactivated. /etc/systemd/system/gunicorn.service is owned by root and has this content: [Unit] Description=gunicorn daemon After=network.target [Service] User=sarlex Group=webapps WorkingDirectory=/webapps/sarlex ExecStart=/webapps/sarlex/gunicorn_start.sh [Install] … -
Contacts matching query does not exist in django rest framework
I am trying to update Contact model fields while creating the new fields of UpdateInfo model and add them to the existing model. But I am getting this error contacts.models.Contacts.DoesNotExist: Contacts matching query does not exist. I know the contact object with the id 19 exists because I can see it when I try the get contacts API. I am sending data like this. My models: class Contacts(models.Model): full_name = models.CharField(max_length=100, blank=True) ......... def __str__(self): return self.full_name class Meta: verbose_name_plural = 'Potential Clients' class UpdateInfo(models.Model): contacts = models.ForeignKey(Contacts,on_delete=models.CASCADE, related_name='update_info') updated_at = models.DateTimeField(auto_now=True) modified_by = models.CharField(max_length=100, blank=True) def __str__(self): return f"Last modified by {self.modified_by} at {self.updated_at}" My views: class EditContactView(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Contacts.objects.all() serializer_class = ContactsUpdateSeializer My serializers: class UpdateInfoSerializer(serializers.ModelSerializer): contacts= serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = UpdateInfo fields = ['id','contacts','updated_at','modified_by'] class ContactsUpdateSeializer(serializers.ModelSerializer): update_info = UpdateInfoSerializer(many=True) id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Contacts fields = ['id', 'full_name', 'lead_source', 'email', 'phone', 'contact_owner', 'contact_status', 'company_name', 'job_position', 'tasks', 'notes', 'email_list', 'created_by', 'created_at', 'update_info'] def update(self, instance, validated_data): update_data = validated_data.pop('update_info') id = validated_data.get('id') contacts = Contacts.objects.get(id=id) #contacts.save() #contact_only_update_logic instance.full_name = validated_data.get('full_name') instance.lead_source = validated_data.get('lead_source') instance.email = validated_data.get('email') instance.phone = validated_data.get('phone') instance.contact_owner = validated_data.get('contact_owner') instance.contact_status = validated_data.get('contact_status') instance.company_name = validated_data.get('company_name') instance.job_position = …