Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python function import not working in Django
My Django project has the following folder structure where controllers is where I keep all custom .py files: C:. │ db.sqlite3 │ manage.py │ ├───myApp │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ widgets.py │ │ __init__.py │ │ │ ├───controllers │ │ │ helpers.py │ │ │ function.py │ │ │ __init__.py │ │ │ Inside controllers/function.py I want to import the file helpers.py. Scenario 1: If I type from .helpers import foo and run this in Django, then I am able to import helpers.py, but if I run this same import in Spyder then I get: ImportError: attempted relative import with no known parent package Scenario 2: If I type from helpers import foo (without the "dot") and run this in Django, then I get: ModuleNotFoundError: No module named 'helpers' but it works in Spyder! What am I missing here with the paths (or relative paths). I need to be able to have one python script that works in Django and Spyder without having to remove the . everywhere. -
Django, connect one field with multiple models
I guess it is a "normal" problem. I want to connect model C with different Models A,B,.. Model A "buildings" - time_built - description - adress - architects - places Model B "photos": - time_taken - title - architects - places Model C "architects" - title - time_born - website - items so items should be connected m:n to Model A or B . Model A and B can have multiple architects. Is it possible to realize something like this in Django? I thought to use a Intermediate Model, but as I understood it does not help me too. -
Django dynamic table using AJAX
I want to dynamically load the table to my html page after ajax form submit. Below is my view definition def patients_create(request): data = dict() if request.method == 'POST': form = PatientForm(request.POST or None) if form.is_valid(): form.save() data['form_is_valid'] = True patient_list = Patients.objects.all() data['html_patient_list'] = render_to_string('dental/patients_list.html', {'patients': patient_list}) else: data['form_is_valid'] = False else: form = PatientForm() context = {'form': form} return render(request, 'dental/partial_patient_create.html', context) and ajax js script $(function () { $("#modal-book").on("submit", ".js-book-create-form", function () { var form = $(this); $.ajax({ url: '/partial_patient_create', data: form.serialize(), type: form.attr("method"), dataType: 'html', success: function (data) { alert("Book created!"); // <-- This is just a placeholder for now for testing $("#patients tbody").html(data.html_patient_list); $("#modal-book").modal("hide"); } }); return false; }); }); the problem is with this part of code $("#patients tbody").html(data.html_patient_list);. In java script file it is marked as unresolved variable. How can I pass the variable from views.py file to JavaScript file? Thanks in advance -
What are non-scriptable objects in Django?
I have the following model: class Performance(Event): date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) class PerformanceWork(models.Model): perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE) work = models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE) class WorkMusic(MPTTModel, Work): ... In my view.py: class PerformanceView(TemplateView): template_name = 'performances/performance.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'perf': Performance.objects.get(pk=self.kwargs['pk']) }) return context In my template, I am trying to render a recursive tree with this in my template: {% for work in perf.perf_work.all %} {% recursetree work.work %} <li> {% if node.is_leaf_node %} {{ node.name_original }} {% endif %} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} {% endfor %} When run my app, I get the following error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/performance/2/ Django Version: 3.0 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'opus', 'generic', 'art_perf', 'art_visual', 'debug_toolbar', 'mptt', 'import_export', 'googlemaps'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Template error: In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0 'WorkMusic' object is not subscriptable 1 : {% load static i18n %} 2 : 3 : <!DOCTYPE html> 4 : <html lang="en" class="{% block html_class %}{% endblock %}"> … -
django-menu-generator in rest api
Is that possible to send django-menu-generator in a Rest Api? I need to send a menu like this in a rest api to use it in Angular: NAV_MENU_RIGHT = [ { "name": "Account", "url": "/acount", "validators": ["menu_generator.validators.is_authenticated"], "submenu": [ { "name": "Profile", "url": "/account/profile", } ], }, ] ``` -
Django does not store password in database
When i print my password from view it shows non in my command prompt i am using only password1 in forms.py i put pass2=none Models.py:- class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname Forms.py:- class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2=None class Meta: model=User fields=['username','password1','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] views.py:- def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user=form.save() profile=profile_form.save(commit=False) profile.user=user profile.save() username= form.cleaned_data.get('username') password= form.cleaned_data.get('password') print(username) print(password) messages.success(request,f'account created for {{ username }}') return redirect('home') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) **When i print my password in viws it shows None.also i am using only password1 ** -
Migrate From An IntegerField With Choices To A CharField
In Django I have a model with the following IntegerField. GENDER_CHOICES = ( (0, 'Male'), (1, 'Female'), ) gender = models.IntegerField(choices=GENDER_CHOICES) I would like to altar this model to become a CharField using the choices. GENDER_CHOICES = ( ("MALE", 'Male'), ("FEMALE", 'Female'), ("NA", 'Id Rather Not Say'), ) gender = models.CharField(choices=GENDER_CHOICES, max_length=10) If I were to do this by running makemigrations and migrate I would lose the existing data in the database. How would I make this (and similar) migrations without losing the existing data in the database? Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate command. -
How can i create both the child and parent object in one request Django rest framework
I have a company object that has a OneToOneField(Profile), and Profile has OneToOneField(User) My question is: is it possible to create all three in one request and if so, how can i do it? Structure of my company object "company":{ "profile" :{ "user" : { "first_name" : "", "last_name" : "", "username" : "", "email" : "" }, "phone" : "", "registered_date" : "" }, "name": "", "address": "", "currency": "", "id_number": "", "vat_number": "", "vat_company_name": "", "company_email": "", "fixed_phone": "" } I tried sending this into the POST request to the Company serializer and this is what i get: { "profile": [ "Incorrect type. Expected pk value, received dict." ] } Can i do this without overriding .create() in the serializer? -
New User Role model in Django
I want to create a new System User model. I have already created a Role for it. I have added a factory for the new role and edited my django UserManager like this: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_systemuser', False) return self._create_user(username, email, password, **extra_fields) def create_systemuser(self, username, email, password, **extra_fields): extra_fields.setdefault('is_systemuser', True) if extra_fields.get('is_systemuser') is not True: raise ValueError('System-user must have is_systemuser=True.') return self._create_user(username, email, password, **extra_fields) this is the factory: class SystemUserFactory(UserFactory): class Meta: model = User # Type hinting def __new__(cls, *args, **kwargs) -> "SystemUserFactory.Meta.model": return super().__new__(*args, **kwargs) # pragma: no cover is_systemuser = True Still I get this error by Django: AttributeError: 'UserManager' object has no attribute 'create_systemuser' -
Use cookiecutter django with poetry
i am trying to use Cookiecutter with django template by pydanny. Im using poetry to manage my python project and i don't know how to use cookiecutter with poetry. Normally using pip and a virtual environment, all packages from requrements are installed with: pip install -r requirements/local.txt But in poetry i can't install dependencies from '.txt' file. What i have to do? -
how to verify user on sign up using mobile otp in django?
my urls.py ''' from django.urls import path, include from . import views urlpatterns = [ path('enter_otp',views.otp_call,name='otp_confirmed') ]''' my views.py ''' def signup(request): if request.method == 'POST': username = request.POST["username"] last_name = request.POST["last_name"] first_name = request.POST["first_name"] date_of_birth = request.POST["birthday"] email = request.POST["email"] password = request.POST["password"] Phone = request.POST["phone"] gender = request.POST["gender"] if User.objects.filter(username=username).exists(): messages.info(request,'username already taken') return render(request,"signup.html") if User.objects.filter(phone_no=Phone).exists(): messages.error(request,'Phone number already in use') return render(request,"signup.html") else: sent = otp() print(sent) return otp_call(un=username,pswrd= password,mail = email, fn=first_name,ln=last_name,pn=Phone,dob=date_of_birth,gen=gender,otp=sent) else: return render(request,"signup.html") def otp_call(request,**kwargs): if request.method == 'POST': trials = 0 while trials<3: input_otp= request.POST["six_digit"] if input_otp == otp: signedup_user = User.objects.create_user( username=un, password=pswrd, email=mail, first_name=fn, last_name =ln, phone_no=pn, date_of_birth=dob, gender= gen ) signedup_user.save() break return redirect('login') if input_otp != otp: trials+=1 messages.error(request,"wrong otp") return render(request,'otp_recieve.html') else: return render(request,'otp_recieve.html') ''' I have html to confirm the otp with post request and csrf_token but I its not a right way I know because Urls.py will be needing parameeters too how do I verify users using otp through there mobile and the otp() in signup() is just a random 6 digit key generator please help me -
How do i write redis channel layer in django and windows
I have this code in my settings.py, but it seems not working in django and windows, any ideas on how to correct this code? CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG':{ "hosts": [('127.0.0.1', 6379)], }, }, } -
Django validate answer for specific question
Overview: I want to build a Question-Answer website, where the user has to enter the correct answer for each question. I have made 3 models for this: class ProblemSet(models.Model): id = models.IntegerField(primary_key=True) class Problem(models.Model): id = models.IntegerField(primary_key=True) problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE) question = models.TextField() solution = models.TextField() class Solve(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) problem_set = models.ForeignKey(ProblemSet, on_delete=models.CASCADE) problem_id = models.ForeignKey(Problem, on_delete= models.CASCADE) In solve model, if there is any entry that means that particular user has solved that problem_id. So, I have utilized the generic Form View: class IndexView(FormView): form_class = ProblemForm template_name = 'home/index.html' success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: inner_qs = "fetch ids that are solved from Solve model" problem_obj = Problem.objects\ .exclude(id__in=inner_qs)\ .order_by('id').first() else: #do something context['question'] = problem_obj.question return context The problem form is: from django import forms class ProblemForm(forms.Form): solution = forms.CharField(widget=forms.TextInput()) How do I validate that the user is inputting the correct answer? I do get the value of solution field in def form_valid(self, form) function but how should I deal with it? Should i pass question_id in context and query the database in form_valid, or should i pass solution itself to context and access context data in … -
how to save image in django media root storage from python
hi anyone to help me out with this please i'm trying to save my images to the media root folder which i named pictures in the media folder..this is my code and i want whenever my function is making the screenshot it should save the screenshots in my media root folder from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404,render,redirect import time import random from django.db import models import pyautogui import sys from shots.models import pictures from .models import pictures from shots.forms.forms import DocumentForm def button(request): import pyautogui myScreenshot = pyautogui.screenshot() storage=pictures.pictures2 myScreenshot.save(storage) return render(request,'index.html') def output(request): return HttpResponse("""Hello, world. You're at the polls index. your Screenshot should start now""")``` this is my models.py from django.db import models import random class pictures(models.Model): pub_date = models.DateTimeField('date published') pictures2 = models.ImageField(upload_to='pictures')``` -
How to filter a query on the results of another one in django?
Lets say that i have 2 models : Class OrderEvent(models.Model): isPaid = models.Booleanfield() Class Participant(models.Model): orderEvent = models.ForeignKey(OrderEvent) participantFirstName = models.CharField() participantLastName = models.CharField() #etc... And i want to get all the participants where Orderevent.isPaid = True. I think that i struggle to do something very simple... -
How to create model instances from csv file
There is a task to parse the csv file and create instances in the database based on the received data. On the backend - DRF and at the front - React. The specific feature is that the file processing is not quite hidden. The logic is as follows: There is a button to load the file. The file is loaded and validated, but nothing is created in the database at once. A window appears with a list of saved data (like a table) and in this window there is a new button to confirm by clicking on which the database is already requested. What I just did: 1. Created a class to download the file (Upload button) class FileUploadView(APIView): parser_classes = ( MultiPartParser, FormParser) renderer_classes = [JSONRenderer] def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 else: status = 406 r = "File format error" return Response(r, status=status) In the class, the csv_file_parser function is called, the result of which is json containing all the saved data like this: { "1": { "Vendor": "Firstvendortestname", "Country": "USA", ... ... "Modules": … -
How can I log user authentication using django?
I am working on a project using Django (Version 3.0) and I would like to log any login and logout attempt (whether successful or not) for security reasons. Unfortunately, I did not find a way to do it yet. The solutions suggested here here did both not work -
How create a user and a profile with a single form in Django?
I have created a Clients model in models.py that is intended to be a Client (user) Profile. class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome") last_name = models.CharField(max_length=30, verbose_name="Apelido") address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) email = models.CharField(max_length=200, null=True, verbose_name="Email") avatar = models.ImageField(null=True) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() This model is connected to the Django Users through a OneToOneField called user. I created a form that is capable of adding data to the Clients model in forms.py: class NewClient(forms.Form): first_name = forms.CharField(max_length=30, label="Primeiro Nome") last_name = forms.CharField(max_length=30, label="Apelido") address = forms.CharField(max_length=200, label="Morada") nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')]) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) email = forms.CharField(max_length=200, label="Email") def clean(self): cleaned_data = super(NewClient, self).clean() first_name = cleaned_data.get('first_name') last_name = cleaned_data.get('last_name') address = cleaned_data.get('address') nif = cleaned_data.get('nif') mobile = cleaned_data.get('mobile') email = cleaned_data.get('email') if not first_name and not last_name and not nif: raise forms.ValidationError('You have to write something!') How can I, through this single form, add a username and password field so that, through the OneToOneField, … -
How to ensure celery executes tasks consisting of chains in the order they were submitted?
I'm working on a django project where users can submit long-running, computationally intensive jobs that will run asynchronously using celery. What I want to achieve is actually quite simple: Say user A submits a job. This job (consisting of multiple subtasks with different runtime, some taking multiple hours) gets executed in the background with celery and after a while you get a result. Meanwhile, other users can also queue their jobs, which SHOULD get executed AFTER user A's job has finished, in the order they were submitted. This is where the problem lies. Suppose the pipeline consists of arbitrary tasks 1,2,3. My code looks something like this: @shared_task(bind=True, name="execute_pipeline") def execute_pipeline(self, job_id, *args, **kwargs): result = chain(task1.s(), task2.s(), task3.s()) return result.apply_async() Every time a user submits a job, I call this task with: execute_pipeline.delay() while having started my worker with celery -A project worker --concurrency=1 -l info to ensure only one worker is executing one task at a time. This works fine in that the tasks are executed sequentially; the result is also correct. The problem comes in when another user submits their job while this task is still running. As soon as user B submits their job, it gets … -
I want to use MongoDB with Latest Django
But i am getting this error, some people are suggesting to downgrade django but it does not work Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named ``` -
Django socket connection timout
I am trying to check if a certain device (Lauterbach PowerDebug Pro) is connected to the network. I have the following code that I am using in Django view. def checkConnection(hostname, port, timeout=5): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(timeout) s.sendto(message,(hostname,port)) message = bytes.fromhex('{1024 bytes here}') try: if s.recv(1024): return True except ConnectionResetError: return False except socket.timeout: return False If I run this function from the Django View (called through AJAX), it will return False. If I run this code in a Python console, it will return True. If I run manage.py shell and manually write this code, it will return True. However, if I run manage.py shell, import and call this function, it will return False, due to a timeout error. How come? I can't figure out why it will not work. I have captured the messages using Wireshark and they are all the same. Below is the output. Code written manually in Django shell (returned True): No. Time Source Destination Protocol Length Info 233 17.202222 10.171.90.59 10.171.94.100 UDP 1066 59221 → 60010 Len=1024 Frame 233: 1066 bytes on wire (8528 bits), 1066 bytes captured (8528 bits) on interface 0 Ethernet II, Src: IntelCor_c1:d7:3e (b4:6b:fc:c1:d7:3e), Dst: All-HSRP-routers_5a (00:00:0c:07:ac:5a) Internet Protocol Version … -
Django DateTimeField auto_now_add attribute is not working
I have a model Alerte (below) that is updated in a function like this Alerte.objects.create( asp_ale_loc = site, asp_ale_typ = 1, # activation de l'alerte # asp_ale_dat = timezone.now() -> replaced by auto_now_add ) I have modify asp_ale_dat format from DateField to DateTimeField and add auto_now_add as attribute I have run makemigrations and migrate but when I create an Alerte object, asp_ale_dat is empty and if I use timezone.now(), only date is registered, not time... class Alerte(models.Model): asp_ale_cle = models.AutoField(primary_key=True) asp_ale_loc = models.CharField("Site concerned by alert", max_length=10, null=True, blank=True) asp_ale_typ = models.IntegerField("Operation type on alert", null=True, blank=True,) asp_ale_dat = models.DateTimeField("Operation date on alert", null=True, blank=True,auto_now_add=True) -
How to search using regex fast in mongodb using djongo in django
I have a table in DB with almost 20 million records. I want to search through regex. It was all good when the number of records were about 100 thousand. But now it takes like quite a lot time even sometime it results in timeout. Does i need to migrate to SQL database may be postgresql or something like elastic search. As the records in this table is expected to increase more than 20 billion. Can there is a way to make it efficient by keeping the same settings as i'm using djongo to connect django to mongodb or i have to use anyother database for fast searching. My model schema is from djongo import models as model class User(model.Model): email = model.CharField(max_length=50, default='') source = model.CharField(default='unknown',max_length=150) username = model.CharField(max_length=150, default='') hash = model.CharField(max_length=255, default='') salt = model.CharField(max_length=255, default='') ipaddress = model.CharField(max_length=50,default='') lastipaddress = model.CharField(max_length=50,default='') name = model.CharField(max_length=150, default='') dateofbirth = model.CharField(max_length=100, default='') phonenumber = model.CharField(max_length=100, default='') firstname = model.CharField(max_length=150, default='') lastname = model.CharField(max_length=150, default='') address = model.CharField(max_length=255, default='') objects = model.DjongoManager() This method is called when an post request is send to django @api_view(['POST']) @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAdminUser]) def search(request): if 'username' in request.data: username = request.data['username'] if 'email' in request.data: … -
How do I fetch data from a csv file and display it using django
I want to fetch data from a csv file and display it using django. can anyone help me on this. -
How to communicate with Docker Postgres DB when I already have a local DB running?
I just inherited a codebase that spins a new Postgres DB instance but has DB settings in it's local.py module. Now when I run a migration command, it throws an authentication error meaning, it is communicating with my local Postgres installation. How do I different it. I have checked services but Postgres isn't running. Should I delete my local installation of Postgres?