Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (403) CSRF verification failed
When I click on ok button in add_tech.html then it will redirect me on upload_type.html. But it show error while clicking on ok button. ERROR - Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. My template(add_tech.html) - <form action="/uploads/type/" method="post"> <label for="your_name">New Tech: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"> </form> My Template(upload_type.html)- <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} </form> My View.py - def upload_type(request): if request.method =='POST': details = NameForm(request.POST) if details.is_valid(): return render(request, "core/upload_type.html", {'form':details}) else: details = NameForm() return render(request, 'core/upload_type.html', {'form': details}) My Url.py - urlpatterns = [ url(r'^uploads/type/$', views.upload_type, name='upload_type'),] My form.py - from uploads.core.models import Name class NameForm(forms.ModelForm): class Meta: model = Name fields = ('your_name', ) My Models.py- class Name(models.Model): your_name = models.CharField(max_length=100) -
Django unique ManyToMany field
I have a PlaceType model related to the Place model via a M2M field. It functions as necessary where I do place.type.create(name='foo') but it ends up having duplicate values for name=foo. That leads to a large amount of duplicate data. I would like the PlaceType table to be unique in the name field. I tried to add unique=True but it throws an error when inserting. I would essentially want to do a get_or_create on the type but in an elegant way. class Place ... class PlaceType name = models.CharField(unique=True) place = models.ManyToManyField(Place) Thank you! -
Treebeard - No module found
I installed Treebeard using pip install django-adminlte-ui But still it shows ModuleNotFoundError: No module named 'django.contrib.treebeard' This is my installed app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.treebeard', 'crud.apps.CrudConfig', 'crispy_forms', 'django_select2', 'django_ajax', 'treebeard', ] Can anyone help me solve this? -
Is it good to put django code in databsse
I am planning to build a generic system for sending notifications to users from my system. Currently, whenever I need to send any new notifications to users, I add a new periodic_tasks/tasks in Django code and schedule it and deploy the Django application. I put the logic for notifications in code and whenever my periodic tasks run it check which all users are eligible to get this notification. Then I send it to them. Now, I am planning to build a notification manager So that I can add logic from the user interface for notification alert and it will store in DB so whenever I need a new notification alert it will require database lookup rather than Django deployment. -
User information not being saved
I created a field in my signup form asking users for a link to their linkedin profile. I created a page that returns a list of all the users (mentor users) and noticed that I cannot access the linkedin link. I am not sure if its because I have not saved the link or I am not accessing it correctly. This is what I have in models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) def __str__(self): return "Profile of user {}".format(self.user.username) @receiver(post_save,sender=User) def create_or_update(sender, instance, created, **kwargs): if created: post_save.connect(create_or_update, sender=User) forms.py class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) linkedin = forms.URLField(max_length=200) class Meta(UserCreationForm.Meta): model = User fields = ('email', 'username', 'first_name', 'last_name') def save(self, commit=True): self.instance.is_teacher = True user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() mentor = Mentor.objects.get_or_create( user=user, linkedin=self.cleaned_data['linkedin'] ) return user #basic form class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') views.py (teachers.py) class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('teachers:app-instructor-dashboard') … -
Django is_valid() always returns false error
I am beginner of Django. When i submit in the html page, is_valid funtion in my views.py always returns false. users.html is my template. I obviously filled things correctly but it still returns false. Any help would be welcome. this is my models.py file from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length=264, ) last_name = models.CharField(max_length=264, ) email = models.EmailField(max_length=255,) def __str__(self): return self.first_name + self.last_name this is my forms.py file from django import forms from first_app.models import User from django.forms import ModelForm class User_form(ModelForm): class Meta: model = User fields = ['first_name','last_name','email'] this is my views.py file from django.shortcuts import render from django.http import HttpResponse from . import forms from first_app.models import User # Create your views here. def index(request): return render(request,'index.html') def user_form_view(request): form = forms.User_form() if request.method == 'POST': if form.is_valid(): form = forms.User_form(request.post) form.save() return index(request) else: print(form) return user_show(request) return render(request,'first_app/users.html',{'form':form}) and this is my users.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Users</title> </head> <body> <h1>Hello! please type in your information</h1> <div class="container"> <form class="" method="POST"> {{form.as_p}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="submit"> </form> </div> </body> </html> -
Django: Best practice for showing list of Models (as a text) based on group permissions given to specific user
My main concern is to show a list of Models that user can interact with based on given permissions. I am thinking of doing this by way of user's group permissions. I wanna mimic how the Django admin is able to list the models when you give any permissions to the user related to that model like this: For example I have model called Posts with permissions can_add_post and can_delete_post. I am assigned to a Group called Writer that has been assigned with both permissions. In my view, I want to be able to retrieve the name of 'Posts' model as a text so I can do something with it like set an onClick function to call a respective React component like this: I have no clear business logic in mind to do this though. -
Many to Many relation' list display with checkbox in Django
I want a checkbox with the M2M list of Clinic/Hospital with an individual row. here are my forms class ClinicHospitalForm(forms.ModelForm): class Meta(): model = ClinicHospital fields = ('name','address','contact','lat','lon') class DoctorForm(forms.ModelForm): class Meta(): model = Doctor fields = ('name','speciality','contact','clinic_hospital') -
How can I compare TimeField model with current time?
I want to compare TimeField with current time and call certain function at that time, how is it possible? or is there any way to do this process? -
About WSGI header spoofing via underscore/dash conflation
I have a Django project deployed via apache/uwsgi. But things do not work as described in https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest.META. I would expect all request headers to be converted to "META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name", but instead they are not! Does anyone know why? Is it possible the conversion is performed on http protcol only (not on https which I am using)? Is there any switch/configuration parameter that enable/disable this conversion? Any hint explaining the behavior will be really appreciated! Thanks in advance for your kind advice Dario P.S.: The following is the content of requirements.txt certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 django-cors-headers==2.2.0 django-simple-history==2.0 djangorestframework==3.7.7 docker==3.5.1 docker-pycreds>=0.3.0 idna==2.6 mysqlclient>=1.3,<1.4 pycparser==2.18 pytz==2018.3 requests>=2.20,<2.21 six==1.11.0 urllib3>=1.23,<1.24 websocket-client==0.47.0 Django==2.1.2 gunicorn>=19.5.0,<19.6 django-filter==2.0.0 mozilla-django-oidc==1.2.1 python-dateutil==2.8.0 -
Django - Converting a Binary stream to an Image
I am trying to obtain an image from a url and return it to the ModelAdmin to display it in a new column of the table. I tried the following code in admin.py file: def new_field(self, obj): r = requests.get('https://abcd.com/image') return r.content The code is not giving me any error but it's returning a long binary string instead of the image itself. How can I pass the image itself, or convert the binary content to an image? -
For Android & iOS application, what backend technology should we use among NodeJS or Laravel/PHP or Django/Python?
I am working on backend of flutter app. I can implement backend in Laravel-PHP or Node-JS or Django-Python. I have suggested by the people politically so confused with which framework should I move on. My app should get the data & load immediately is the requirement. Then I will be using Payment Gateways etc. -
How can i remove collections after embedded them to another collection in mongodb with djongo?
I am new with Django . I'm trying to connect django to mongodb with djongo .But when i use embedded models ,mongodb create 2 collections for me . How can i remove the embedded collections. This is my models.py code class CallHistory(models.Model): Time = models.DateField(default=datetime.date.today) Count = models.IntegerField(default=0) class History(models.Model): SeriNo = models.CharField(max_length=100) Call = models.EmbeddedModelField( model_container = CallHistory ) I don't want to create CallHistory collection in mongodb. -
Not Found: /newsletter.send.php Error in Django
Is there anybody know what is going on with this problem?! I almost finished my programming in Django and at the end i faced with this error: Not Found: /contact/email/newsletter.send.php [17/Jan/2020 12:07:28] "POST /contact/email/newsletter.send.php HTTP/1.1" 404 4643 Not Found: /accounts/signup/newsletter.send.php [17/Jan/2020 12:07:13] "POST /accounts/signup/newsletter.send.php HTTP/1.1" 404 7740 Not Found: /9/signature-s-bentley/newsletter.send.php [17/Jan/2020 11:56:01] "POST /9/signature-s-bentley/newsletter.send.php HTTP/1.1" 404 4421 actually it had occurred when i wanted to use "Add to Card" or "Sign-in" or even at "Mail-Approval"!! Thank Y'all! -
Django run function on logging out of admin page
I'm trying to find a way to handle on admin logout (django admin page), files in a certain folder will get deleted. Because i have a function on certain admin interactions, files will get saved to a folder and i would like these files to get deleted when the admin logging out of the admin page. I only know about Django detect user logout on browser close like so: if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: What i would like to do is to override the logout function of admin site to execute a function and delete files in a folder. I can see that the logout function exists in https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L349 but how do i override it and add my delete files function into it ? -
How to handle posting payload in POST method even if one field is missing in Django Rest Framework
I have implemented a post method with Django rest framework, the problem with the post method is that when posting one is required to include all the required fields of the payload so as the request to be successful. How do I make it possible to allow one to post successfully if anyone field is missing from the payload? -
Debugging Django/Docker environment with VS Code
Im tryiong to setup VSCode Debugger for a docker/django environment but struggling im busy following this guide https://gist.github.com/veuncent/1e7fcfe891883dfc52516443a008cfcb which worked on a different project, but i can't seem to find out why it isn't connecting to my breakpoints in this project. I have opened the ports in docker-compose and everything :/ django: build: . command: /start-dev.sh environment: - DJANGO_SETTINGS_MODULE=project.settings_docker volumes: - ./src:/code ports: - 8000:8000 - 3000:3000 depends_on: - mysql Dockerfile looks something like this RUN mkdir /code WORKDIR /code RUN pip install --upgrade pip COPY ./requirements /requirements RUN pip install --no-cache-dir -r /requirements/base.txt \ && rm -rf /requirements ADD ./src /code/ in VS my launch file looks as follows { "version": "0.2.0", "configurations": [ { "name": "Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/{THEAPP}", "remoteRoot": "/code/" } ], "port": 3000, "host": "localhost" } ] } The Start-dev.sh that runs the server #!/bin/sh python3 manage.py migrate --noinput python3 manage.py runserver 0.0.0.0:8000 If i run this ever now and then i do receive an error message in my console saying. pydev debugger: unable to find translation for: "/Users/{USER}/workspace/{THEAPP}/src/app/models.py" in ["workspace/{THEAPP}"] (please revise your path mappings). i replaced the sensitive information with {} tags for the question -
Attribute Error 'WebElement' object has no attribute 'copy' when Select element to new function common file
I have a HTML element like this <select class="form-control mt-1 set-miw-100" name="status" id="my_id"> <option value="">ALL</option> <option value="1.0">ALL</option> <option value="2.0">A</option> <option value="3.0">B</option> <option value="4.0">C</option> </select> I want to select and choose an value of that, when I use define a function in test file It will working OK def _find_and_select(self, elm_id, value): select_item = Select(self.browser.find_element_by_id(elm_id)) select_item.select_by_value(value) self._find_and_select("my_id", "1.0") But when I move to a common test file, It will get error class Common: @staticmethod def _find_and_select(browser, elm_id, value): select_item = Select(browser.find_element_by_id(elm_id)) select_item.select_by_value(value) Common._find_and_select(self.browser, "my_id", "1.0") It's will get error : Traceback (most recent call last): File "D:\iBNet-Prj\ibnet\apps\autotest\contract\tests.py", line 251, in test_search CommonTest._find_and_select(self.browser, "contractLoanStatus", loanStatus[0]) File "D:\iBNet-Prj\ibnet\apps\common_test.py", line 467, in _find_and_select select_item = Select(browser.find_element_by_id(elm_id)) File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 558, in __init__ super().__init__(attrs) File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 201, in __init__ self.attrs = {} if attrs is None else attrs.copy() AttributeError: 'WebElement' object has no attribute 'copy' -
Django models defined in tests.py are not created in database
I am trying to run test suits given by Django "https://github.com/django/django/tree/master/tests" on default database sqlite. For one of the apps "custom_lookups" I get an error saying "Exception: Statement Execute Failed: [IBM][CLI Driver][DB2/NT64] SQL0204N "DB2ADMIN.CUSTOM_LOOKUPS_CUSTOMMODEL" is an undefined name. SQLSTATE=42704" I am using this command "./runtests.py --settings=settings custom_lookups" I also included this app name in INSTALLED_APPS under settings file. This model (i.e custommodel) for which I am getting error is defined in tests.py as below, class CustomField(models.TextField): def get_lookup(self, lookup_name): if lookup_name.startswith('lookupfunc_'): key, name = lookup_name.split('_', 1) return SQLFuncFactory(key, name) return super().get_lookup(lookup_name) def get_transform(self, lookup_name): if lookup_name.startswith('transformfunc_'): key, name = lookup_name.split('_', 1) return SQLFuncFactory(key, name) return super().get_transform(lookup_name) class CustomModel(models.Model): field = CustomField() You can find whole code in github for this Django test suite https://github.com/django/django/tree/master/tests/custom_lookups What I found is models defined in models.py file is been migrated but any models defined in tests.py is not migrated but would got created during running test case and get deleted at same time once test case is run. My question is why models defined in tests.py are not picked for migration but after running complete test suite its trying to flush this ? hence I get above said error. whats fix for this ? … -
How get instance id after save_m2m in admin django
I've method in admin.py def save_model(self, request, instance, form, change): user = request.user instance = form.save(commit=False) if not change or not instance.created_by: instance.created_by = user instance.save() form.save_m2m() if instance.send_to_killer: serializer = OrderSerializer( instance) emailClass = Email() emailClass.sendemail(serializer, 1, instance) return instance and other one is class Email(object): def sendemail(self, data, sendfrom, instance): print(instance.id) orders_item = order_item.objects.filter(order_id=instance.id) print(orders_item) for item in orders_item: print(item.qty) I received instance.id but not getting orders_item as items are saved after order. so how i can get order items data while saving m2m ?? -
`wagtailimages` not found in reverse data migration for custom image field
TLDR: Getting error: LookupError: No installed app with label 'wagtailimages'. once the custom data migration is executed in wagtail which causes all tests to fail, as Django can't find the app after running the latest migration. I needed to add a few custom fields to my image model in my wagtail installation that supports a Vue SPA. I followed the guidelines in the docs here: http://docs.wagtail.io/en/v2.0/advanced_topics/images/custom_image_model.html So, I created a custom image model along with custom rendition like this: class CustomImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) caption = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ( "alt_text", "caption", ) class CustomRendition(AbstractRendition): image = models.ForeignKey( CustomImage, on_delete=models.CASCADE, related_name="renditions" ) class Meta: unique_together = ( ("image", "filter_spec", "focal_point_key"), ) I also changed the WAGTAILIMAGES_IMAGE_MODEL setting to point to my new model: WAGTAILIMAGES_IMAGE_MODEL = "pages.CustomImage" I wrote a data migration with the help of this blog post which refers to this StackOverflow discussion: # Generated by Django 2.1.10 on 2020-01-15 09:03 from django.db import migrations, models def forwards_func(apps, schema_editor): wagtail_image_model = apps.get_model("wagtailimages", "Image") custom_image_model = apps.get_model("pages", "CustomImage") tagged_item_model = apps.get_model("taggit", "TaggedItem") django_content_type = apps.get_model("contenttypes", "contenttype") db_alias = schema_editor.connection.alias # Get images stored in default wagtail image model images = wagtail_image_model.objects.using(db_alias).all() new_images = [] for image … -
Django import order causing error with default user model on class imports from another app
When referencing models from my core app 'core_hr' in my custom user model app where I overrode AbstractBaseUser to define a new user model I received an error Until I tried to import models from another django app into my overridden custom user model app I had never seen this error. All my apps are in installed apps. "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.Employee' that has not been installed models.py from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone # ---->from core_hr.models import Passport, RegistryOfStay <----- from .managers import CustomUserManager from ####.storage_backends import PublicMediaStorage, PrivateMediaStorage from django.core.validators import RegexValidator name_validator = RegexValidator(r'^[a-z A-Z]*$', 'Only Alphabetic characters allowed') class Employee(AbstractBaseUser, PermissionsMixin): employment_statuses = ( ('ap','Applicant'), ('trial', 'Initial Training'), ('em', 'Employed'), ('ps','Pause') ) genders = (('M', 'male'),('F', 'female')) # core information full_name = models.CharField(_('Surname, Given Names as on passport'), validators=[name_validator], max_length=25, blank=False, null=True) #employment data gender = models.CharField(max_length=10, choices=genders) employee_id_number = models.CharField(_('employee id number'), max_length=20, null=True) # activity Status employment_status = models.CharField(choices=employment_statuses, max_length=30) employment_status_note = models.TextField(max_length=500) # contact information phone_number = models.CharField(max_length=14, unique=True) email = models.EmailField(_('APAX … -
Save blob as a file in Django Rest Framework
I am sending a blob using Ajax. I need to save it as a file in a model. views.py class JobPostModelViewSet(ModelViewSet): serializer_class = JobPostModelSerializer parser_class = (FileUploadParser, ) def create(self, request): data = dict() data['user'] = request.user data.update(request.data) serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response({'success': 'Job Posted Successfully'}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class JobPostModelSerializer(ModelSerializer): class Meta: model = JobPost fields = ("job_title", "job_description", "job_video") Ajax.js _postJob(e){ var blob = this.video_blob; var job_title = $("#job_title").val(); var job_description = $("#job_description").val(); var cookie = getCookie('csrftoken'); var formdata = new FormData(); formdata.append('job_title', String(job_title)); formdata.append('job_description', String(job_description)); formdata.append('job_video', blob); console.log(formdata.get('job_title')); console.log(formdata.get('job_description')); console.log(formdata.get('job_video')); $.ajax({ url: '/api/v1/job-post/', type: 'post', enctype: 'multipart/form-data', headers: {'X-CSRFToken': cookie}, data: formdata, contentType: false, processData: false, success: function (e){ console.log(e); }, error: function(e){ console.log(e); }, }); } } The error I get is. {"job_title":["Not a valid string."],"job_description":["Not a valid string."],"job_video":["The submitted data was not a file. Check the encoding type on the form."]} -
How to run OpenCV face detector in Django web app?
Basically, I want to use the feature, of OpenCV to detect face using webcam, in my Django Web app. I tried it using web api but couldn't succeed. Following is my code for create_data.py which scans the face and stores the results in the datasets. create_data.py (open cv code) import cv2, sys, numpy, os, random import uuid haar_file = 'haarcascade_frontalface_default.xml' datasets = 'datasets' sub_data = "person" myid = random.randint(1111, 9999) path = os.path.join(datasets, sub_data + '-' + str(myid)) if not os.path.isdir(path): os.mkdir(path) # defining the size of images (width, height) = (130, 100) # '0' is used for my webcam, # if you've any other camera # attached use '1' like this face_cascade = cv2.CascadeClassifier(haar_file) webcam = cv2.VideoCapture(0) count = 1 while count < 30: (_, im) = webcam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 4) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 4) face = gray[y:y + h, x:x + w] face_resize = cv2.resize(face, (width, height)) cv2.imwrite('% s/% s.png' % (path, count), face_resize) count += 1 cv2.imshow('OpenCV', im) key = cv2.waitKey(10) if count > 29: print('Dataset Created!') if key == 27: break I want to … -
Django Privacy / Cookie Policy With Logging And Versioning
I am trying to make a GDPR compliant privacy policy / cookie policy consent agreement popup / banner on my website to protect from EU laws. I currently am using this github project for my ToC https://github.com/cyface/django-termsandconditions and I love it so much I want to do something just like that for the privacy policy / cookie policy. Basically the website owner can edit the policy, save the policy to the database under various version numbers, and track logged in user's data (IP, username, date, version) if they consent or decline to each and every policy version and policy updates. The user cannot access much of the site unless they accept. I think a popup will be better because it takes up more screen real estate and "blocks" users from viewing / doing anything on the page. Otherwise, I really don't care what it looks like (whatever is easier) as long as it functions well, stores data about the user showing they "signed the contract" for X version number of the editable policy and once the user agrees, they can now view the rest of the website contents. (I am not sure what to do if they decline). I don't …