Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'SET_NULL' is not defined [closed]
So I want to set on_delete=SET_NULL but it gives me an error "NameError: name 'SET_NULL' is not defined", documentations say this should work but it's not. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Book(models.Model): name = models.CharField(max_length=200) description = models.TextField() image = models.ImageField() price = models.IntegerField() class Category(models.Model): name = models.CharField(max_length=100) book = models.ForeignKey(Book, on_delete=SET_NULL, null=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Order(models.Model): order_id = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=SET_NULL, null=True) -
Apache mod_wsgi not using venv file for django
I'm trying to run my django project with apach2, here is my /etc/apache2/sites-availabe/myproject.conf file VirtualHost *:80> . . . Alias /static /myproject/static <Directory /myproject/static> Require all granted </Directory> <Directory /myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/myproject/venv python-path=/myproject WSGIProcessGroup myproject WSGIScriptAlias / /myproject/myproject/wsgi.py I have two versions of python on my machine, v3.6 and v3.9. I used python 3.9 for my venv but when I run the project I get the following error in the apache2 error.log file 16:22:51.522214 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] mod_wsgi (pid=17379): Target WSGI script '/myproject/src/myproject/wsgi.py' cannot be loaded as Python mod$[Tue Jan 26 16:22:51.522294 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] mod_wsgi (pid=17379): Exception occurred processing WSGI script '/myproject/src/myproject/wsgi.py'. [Tue Jan 26 16:22:51.522533 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] Traceback (most recent call last): [Tue Jan 26 16:22:51.522566 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] File "/myproject/src/myproject/wsgi.py", line 12, in [Tue Jan 26 16:22:51.522585 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] from django.core.wsgi import get_wsgi_application [Tue Jan 26 16:22:51.522606 2021] [wsgi:error] [pid 17379] [remote 156.215.213.11:38592] ModuleNotFoundError: No module named 'django' [Tue Jan 26 16:22:51.857115 2021] [wsgi:error] [pid 17379] [remote 156.215.129.117:38596] mod_wsgi (pid=17379): Target WSGI script '/myproject/src/myproject/wsgi.py' cannot be loaded as Python mo$[Tue Jan 26 … -
Django- create_user() function not saving data to database
I have custom User model. I tried to create new user using create_user(), by calling it from view, but data is not getting saved to database. models.py class UserManager(BaseUserManager): def create_user(self, email, username, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user views.py user = { 'username': generate_username(name), 'email': email, 'password': password} user = User.objects.create_user(**user) user.is_verified = True user.save() -
Couldn't Install django-rest-framwork
I am getting these two errors while installing Django_rest_framwork using pip. ERROR: Could not find a version that satisfies the requirement djangorestframwork ERROR: No matching distribution found for djangorestframwork although i have following versions of all requirments: python = 3.9.1 django = 3.1.5 pip = 21.0 screenshot -
django's form is not saved in store
I have a quiz form and when I want to save the answer the model does not store its question. I want to validate the form and save it when if form.is_valid (): I remove it and instead of AnswerForm I use the direct Answer model then it saves but not so. How to change it so that I can validate it and save it with the help of the form? my code -> models.py from django.db import models # Create your models here. from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": if form.is_valid(): qu=request.POST["i_id"] question_id=int(qu) answ=AnswerForm(questin=question_id,answer=request.POST["answer"]) answ.save() return render(request, "question/ans.html", … -
Django - Save Form Value in Different Views
I'm trying to create a small app in which a user can view an event, submit a form indicating the quantity of tickets they would like, view their basket and finally go to a checkout page. My problem is that after I submit a form for event1, the value that is posted is lost when I try to view another event or refresh the basket. How can I prevent this from happening? I need to use Django to make use of a python module during the checkout process so I need to be able to retrieve the quantities submitted for any event in the final checkout view. My views.py file: def basket(request): context = {'Event 1 Tickets': event1_tickets, 'Event 2 Tickets': event2_tickets} return render(request, 'first_app/basket.html', context) def event2(request): form = forms.TicketForm() form = forms.TicketForm(request.POST) if request.POST: if form.is_valid(): # form.save(commit=True) quantity = form.cleaned_data['quantity'] return render(request,'first_app/basket.html',{'event2_tickets': form.cleaned_data}) else: form = TicketForm() return render(request, 'first_app/event2.html', {'form': form}) def event1(request): form = forms.TicketForm() form = forms.TicketForm(request.POST) if request.POST: if form.is_valid(): # form.save(commit=True) quantity = form.cleaned_data['quantity'] return render(request,'first_app/basket.html',{'event1_tickets': form.cleaned_data}) else: form = TicketForm() return render(request, 'first_app/event1.html', {'form': form}) My forms.py: from django import forms class TicketForm(forms.Form): quantity = forms.IntegerField(label="Ticket Quantity",min_value=1,max_value=9,required=True, widget=forms.NumberInput) My event1/event2.html: <!DOCTYPE … -
How can I get self.fields element value in forms file?
In my forms.py file I have method called r_valid and it is used in views.py file. from django.shortcuts import render, redirect from .forms import UserRegisterForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.r_valid() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Created Account for {username}!') return redirect('main') else: form = UserRegisterForm() context = { 'form': form, } return render(request, 'register.html', context) The meaning of it is to ad few more barriers for user which is creating an account. The problem is that in browser it returns an error => TypeError at /register/ 'CharField' object is not subscriptable Here you can see that problem is that I can't get self.fields['username']. So please explain how can I get the username value. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def r_valid(self): j = self.fields['username'] if j[0] in '0123456789': raise ValidationError('The username can\'t start with number') if len(j) < 6: raise ValidationError('That username is too short') for c in j: if c in '@+-/': raise ValidationError('Your username can\'t contain @, +, - or /') … -
Django : Page not found (404)
Whenever I try to log in with username and password this happens: my project name is:corey_schafer app name for user stuff is: users projects urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('register/', include('users.urls')) ] users urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.register, name='register'), path('signup', views.signup, name='signup'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), ] users views.py: [![enter image description here][2]][2] if views.py image not showing please go here:https://i.stack.imgur.com/auZxo.png if any other file is needed to solve this problem please me -
How to keep the data when pushing code changes to heroku [duplicate]
I deployed a django application for the first time using heroku, and of course i had some bugs in my code that needed some changes , so i had to change the code base , push to github repository and finally pushed the project to heroku so i ran these commands in order : git add . git commit -m "message" git push git push heroku main But i lost the data of the database .. So the main question here is how to keep the data after changing to the code base and deploying again .. -
how to set WSGI of appache2 to work with python 3.7?
i am using ubuntu 16.05, i have installed python3.7 and set it to default using this instructions: Unable to set default python version to python3 in ubuntu when i type python in the console i get python3.7 , i tried to set appache2 to work with python3.7 using : sudo apt-get --yes install python3-pip apache2 libapache2-mod-wsgi-py3 sudo a2enmod wsgi sudo apt install --yes python-django-common sudo apt-get install --yes python-django but still i get exceptions of import packages that are already installed in /var/log/apache2/error.log when try to reach out to the server that i don't get at the terminal like this : Traceback (most recent call last): File "/home/ubuntu/mu_code_path/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' mod_wsgi (pid=75005): Target WSGI script '/home/ubuntu/mu_code_path/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=75005): Exception occurred processing WSGI script '/home/ubuntu/mu_code_pathwsgi.py'. Traceback (most recent call last): File "/home/ubuntu/mu_code_path1/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application and mod_wsgi (pid=75005): Target WSGI script '/home/ubuntu/mu_code_path/ut_pr_01/wsgi.py' cannot be loaded as Python module. even though i have django installed in python 3.7 another error i get is after service restart : mod_wsgi (pid=89300): Call to 'site.addsitedir()' failed for '(null)', stopping. -
Django redirect to login url with next ,without using method decorator
I have multiple links on my page which redirects user to take quiz. Some quiz requires user to login or create an account and some does not. def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: if self.logged_in_user: return render(request, self.single_complete_template_name) else: return redirect(settings.LOGIN_URL) return super(QuizTake, self).dispatch(request, *args, **kwargs) I would like user to redirect like how method decorator does login/?next=/quiz/f506cb92-ccca-49ff-b2e5-730bbfea6a5a/take/ but instead I get /login/ I would like my user to come back to the page instead of going to "/dashboard" In my settings I have LOGIN_REDIRECT_URL ="/dashboard" -
api = get_api(request) NameError: name 'request' is not defined - Celery/Django/Twitter API
I have the following function for my Django app using the Twitter API. It all works well but when trying to make it a background task with Celery I get the following error "api = get_api(request) NameError: name 'request' is not defined" I've tried splitting the function differently. Getting the API within the function itself. I just seem to get different errors with everything I try. Can anyone help? I just would like the authorised user to be able to run the function and carry on browsing whilst it works away. views.py from django.shortcuts import render from .models import * from django.http import * from django.urls import reverse from django.contrib import messages from auto_tweet_liker.utils import * from AutoTweetLiker.settings import DEFAULT_FROM_EMAIL from AutoTweetLiker.celery import liking # from profanityfilter import ProfanityFilter import tweepy import time import os def like(request): liking.delay() return render(request, "home.html") def auth(request): # start the OAuth process, set up a handler with our details oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # direct the user to the authentication url # if user is logged-in and authorized then transparently goto the callback URL auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) # store the request token request.session['request_token'] = oauth.request_token return response def callback(request): verifier = … -
coverage.py not reporting error from run command
I have a bash script that runs my tests: #!/bin/bash coverage run --source='directory_for_coverage' manage.py test coverage report --fail-under=87 but when I run the script it only returns an error code if the coverage fails, not if one of the tests fails. I would think that because I am not using the --ignore-errors switch that coverage run should return the error code from the failing test. What am I missing? -
How to setup Celery on Django start in a docker-compose environment?
I have a working Django Docker Project with a celery setup with redis as backend. Actually I have to start my container e.g. docker-compose up and after that I run in a other terminal docker compose exec [containername] celery -A [projektname] worker -l INFO So far everything is fine, but for debugging reasons I don't want to restart celery after every docker restart and I want to integrate the command after the docker containers are successfully started. So how do I start celery after project startup automatically in a docker environment? -
javasvript is not printing to console after click
Hello i'm new in django and js. Problem: I'm trying to pass from html <button> - (line 26) through javascript to my view in django but data parameters are not printed in console the error i get in console the button i'm getting class from is in line 26 in right view js function and html -
Django initialising AppConfig multiple times
I wanted to use the ready() hook in my AppConfig to start django-rq scheduler job. However it does so multiple times, every times I start the server. I imagine that's due to threading however I can't seem to find a suitable workaround. This is my AppConfig: class AnalyticsConfig(AppConfig): name = 'analytics' def ready(self): print("Init scheduler") from analytics.services import save_hits scheduler = django_rq.get_scheduler('analytics') scheduler.schedule(datetime.utcnow(), save_hits, interval=5) Now when I do runserver, Init scheduler is displayed 3 times. I've done some digging and according to this question I started the server with --noreload which didn't help (I still got Init scheduler x3). I also tried putting import os if os.environ.get('RUN_MAIN', None) != 'true': default_app_config = 'analytics.apps.AnalyticsConfig' in my __init__.py however RUN_MAIN appears to be None every time. Afterwards I created a FileLock class, to skip configuration after the first initialization, which looks like this: class FileLock: def __get__(self, instance, owner): return os.access(f"{instance.__class__.__name__}.lock", os.F_OK) def __set__(self, instance, value): if not isinstance(value, bool): raise AttributeError if value: f = open(f"{instance.__class__.__name__}.lock", 'w+') f.close() else: os.remove(f"{instance.__class__.__name__}.lock") def __delete__(self, obj): raise AttributeError class AnalyticsConfig(AppConfig): name = 'analytics' locked = FileLock() def ready(self): from analytics.services import save_hits if not self.locked: print("Init scheduler") scheduler = django_rq.get_scheduler('analytics') scheduler.schedule(datetime.utcnow(), save_hits, interval=5) … -
Django: How to annotate query with Count of distinct occurrences of field combination?
Ideally I would like to use the Count aggregator to count distinct appearances of two fields, instead of just one: q = Tag.objects.annotate(success=Count(['artifact__event__session', 'artifact'], distinct=True)) but this does not seem to be allowed. I came up with the hacky solution of concatenating the fields I want to count the distinct combinations of: q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), distinct=True)) But this does not seem like the right thing to do. Is there a better way? More background information: The actual query is more like: q = Tag.objects.annotate(success=Count(Concat('artifact__event__session', 'artifact'), filter=Q(artifact__event__success=True, artifact__event__user=user), distinct=True)) which has the meaning: "For each tag, give me the number of distinct session-artifact combinations of artifacts that are tagged with that tag and sessions that included that artifact, where an event that belongs to this user was successful" with the models being: class Artifact(models.Model): tags = models.ManyToManyField(Tag) ... class Event(models.Model): artifact = ForeignKey(Artifact) session = ForeignKey(Session) success = BooleanField() user = ForeignKey(User) ... class Session(models.Model): ... -
Представление поля в админке Django
В модели есть функция def variant(self, *args, **kwargs): queryset = list(Supplier_items.objects.filter(si_ean__contains = self.order_ean).all()) return queryset Работает правильно, но я хочу выводить данные из этого поля в админке как select/options. Помогите куда копать. Спасибо -
Django save method doesn't work despite successful POST request
I'm using jquery to send request to a Django form. I have this function in views.py: @csrf_exempt def update_ops(request): print('something something') ops_id = request.POST['id'] instance = Ops.objects.all().filter(id=ops_id) form_qdict = QueryDict(request.POST['form_data']) form = OpsForm(form_qdict or None, instance=instance) if form.is_valid(): form.save() print('saved bro!') # return HttpResponseRedirect('/ops/') else: print('form is not valid') return render(request, 'ops_form.html', {'form': form}) urls.py: urlpatterns = [ url('^update_ops_form/', views.update_ops, name='update_ops_form') ] the html form in form.html: <form action="{% url 'update_ops_form' %}" id="post-form" method="post"> {% csrf_token %} <!--some html form--> </form> and the script in form.html: <script> var ops_id = $('#ops_id').text() console.log(ops_id) $("#post-form").submit(function (event) { event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); console.log(post_url)//get form action url var request_method = $(this).attr("method"); //get form GET/POST method var form_data = $(this).serialize(); //Encode form elements for submission console.log(form_data) $.ajax({ url: post_url, type: request_method, data: {'id':ops_id,'form_data':form_data} }) }); </script> What I want to do is to update an instance of the Ops Model with form using jquery. The POST request is successful, but it doesn't update the instance that I changed. The only possible reason for the error that I know of is because the url in action parameter of the html form doesn't match the url that maps to the update_ops() function in … -
Search in several models
I have two model classes as follows that are not related to each other. class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... first_name = models.CharField(max_length=30, null=False, blank=False) last_name = models.CharField(max_length=30, null=False, blank=False) father_name = models.CharField(max_length=30, null=False, blank=False) class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... code = models.CharField(max_length=15, null=True, blank=True) And now a request comes as follows: http://localhost:8000/api/v1/search/users/?first_name=john&&last_name=dev&&code=25 How can I search if one of the input parameters is in one of the tables (person or company)? The effort I have made but no result found: class SearchUserAPI(APIView): def get(self, request, format=None): try: from django.db.models import Q q = request.query_params search_models = [Person, Company] search_results = [] for model in search_models: fields = [x for x in model._meta.fields if isinstance(x, django.db.models.CharField)] search_queries = [Q({x.name + "__icontains": q.get(x.name)}) for x in fields] print(search_queries) q_object = Q() for query in search_queries: q_object = q_object | query results = model.objects.filter(q_object) search_results.append(results) data = [search_results] return Response(data, status=status.HTTP_200_OK) except Exception as e: return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
wagtail WagtailFormBlock localization
I have a WagtailFormBlock streamfield in my project. When I tried to translate my pages with that streamfield, I can only translate block's form_action and form_reference but can't change form as it is. Is it any way, to change form, when translate some page? img reference -
Django model importing issue
I'm new to Django. I've been trying to import my model.py into a custom management command file, but it tells me: Unable to import 'Educationa_Organization_Management_System.Subjects.models and when I tried to remove the folder name from the import, I still got this error message: Unable to import 'Subjects.models Here's my code in the custom command file : from django.core.management.base import BaseCommand from Educationa_Organization_Management_System.Subjects.models import Subject class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("Subject_name") parser.add_argument("Instructor_name") parser.add_argument("prerequisites", action="store_true") parser.add_argument("Assistant_name") parser.add_argument("Course_description") parser.add_argument("Validation_date") parser.add_argument("SubjectNumberOfChapters") parser.add_argument("numberOfLecturesPerWeek") parser.add_argument("numberOfSectionsPerWeek") parser.add_argument("Subject_FullGrade") def handle(self, *args, **options): subject = Subject( name=options['name'], Instructor_name=options['Instructor_name'], prerequisites=options['prerequisites'], Assistant_name=options['Assistant_name'], Course_description=options['Course_description'], Validation_date=options['Validation_date'], SubjectNumberOfChapters=options['SubjectNumberOfChapters'], numberOfLecturesPerWeek=options['numberOfLecturesPerWeek'], numberOfSectionsPerWeek=options['numberOfSectionsPerWeek'], Subject_FullGrade=options['Subject_FullGrade'], ) subject.save() self.stdout.write(self.style.SUCCESS( "Subject has been successfully added to the database")) and here's my model.py file content: from django.db import models class Subject(models.Model): Subject_name = models.CharField(max_length=50, blank=False) Instructor_name = models.CharField(max_length=50, blank=False) prerequisites = models.BooleanField() Assistant_name = models.CharField(max_length=50, blank=False) Course_description = models.TextField() Validation_date = models.DateTimeField() SubjectNumberOfChapters = models.IntegerField(blank=False, null=False) numberOfLecturesPerWeek = models.IntegerField() numberOfSectionsPerWeek = models.IntegerField() Subject_FullGrade = models.IntegerField() And finally, Here're my folders: Yeah, also, the app is in the setting.py file in the INSTALLED_APPS part. -
Django update form doesn't keep the files?
i want to update the note which is also in database, The code below is only update note instance accept the files. when i submit the form the form is create new files it's not changing the old files. i want to update the files data too. I would be grateful for any help. def PostUpdate(request, id): post = Note.objects.get(id=id) form = NoteFullForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): title = form.cleaned_data['title'] text = form.cleaned_data['text'] note_obj = Note.objects.create(title=title, text=text) for f in request.FILES.getlist('images'): Images.objects.create(note=note_obj, image=f) form.save() return redirect('/up/update/27/') else: form = NoteFullForm(instance=post) return render(request, 'uploading.html', {'form': form}) -
why django model methods is not applicable in queryset methods like values and annotate
I want to know, why Django custom methods in model does not apply in Django queryset methods? Is there any problems if we make custom manager to deal with it. -
how sum ForeignKey to ManyToManyField django queryset
i have this model class PortfolioExchangeTransaction(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now, verbose_name=_('Create Time')) portfolio = models.ForeignKey(Portfolio, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Portfolio'), related_name='exchange_transaction') type = models.CharField(max_length=40, choices=Transaction_TYPE, blank=True, null=True, verbose_name=_('Type')) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Exchange')) count = models.IntegerField(default=0, verbose_name=_('Count')) and want to sum count and portfolio of this model based on exchange so i use below code : transes.annotate(exc_count=Case( When(type='negative', then=F('count') * -1), When(type='positive', then=F('count')), ) ).values('exchange').annotate( sum_count=Sum('exc_count') ).values('exchange', 'sum_count').annotate( portfolios=Value(None, output_field=ManyToManyField(Portfolio)) ) the result is : <QuerySet [{'exchange': 248, 'sum_count': 4000, 'portfolios': None}, {'exchange': 512, 'sum_count': 10000, 'portfolios': None}, {'exchange': 591, 'sum_count': 0, 'portfolios': None}, {'exchange': 940, 'sum_count': 10000, 'portfolios': None}]> as can see i create portfolio field and want to sum foreignkeys to manytomanyfield ( now is None value ) how can do that?