Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing context in django auth views
I have this in my django project: path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='password_change.html'), name='password_change'), in these html pages for the above urls I have to pass some information too as context. So how do I pass context in such type of urls which have no custom view -
Making Django messages appear in a specific place on the page
I have a registration form, and I want my errors to appear under my submit button. How could I make that work? +i'd like to add custom classes to my messages. My forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] #override def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) #Custom classok self.fields['username'].widget.attrs['class'] = 'input' self.fields['email'].widget.attrs['class'] = 'input' self.fields['password1'].widget.attrs['class'] = 'input' self.fields['password2'].widget.attrs['class'] = 'input' #Custom label self.fields['username'].label = "" self.fields['email'].label = "" self.fields['password1'].label = "" self.fields['password2'].label = "" #Custom placeholder self.fields['username'].widget.attrs['placeholder'] = 'Username' self.fields['email'].widget.attrs['placeholder'] = 'Email address' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' #Help text off for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None My views.py file: from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('landing-home') else: form = UserRegisterForm() return render(request, 'users/register.html',{'form':form}) I … -
Can a empty string be passed in the url in django?
I am working on a django project which have a posts page. I have its url as follows: path('posts/<str:sort>', views.posts, name='posts'), and this is what its view looks like: def posts(request,sort) b="" if b=="time": posts=Post.objects.all().order_by(b) else: posts=Post.objects.all() return render(request,posts.html,{'posts':posts}) Now what I want is that if there is nothing passed as sort in the url or the url is like : /posts/ I want to display all posts but if the parameter is 'time' then I want to order_by as in my view. But currently if nothing is passed in url for sort then I get the error that no path found the url. -
Want the Fill the Django ForeignKey in another Html page with different forms contain that key
I am making the CV page, I want to link my Skill, language etc class(table) to Main person table/class, But for that i need to submit skill table first because my person table contain foreign key for skills But as per CV form name & personal info comes first. Also i can put it in one page but i want to go to next page for each subinformation, so is it possible i can commit= false person.save, But python do not let me to pass variable from one class to another. models.py ''' from django.db import models from django.core.validators import MinLengthValidator from django.conf import settings import datetime class Workexperience(models.Model): work = models.TextField(null=True, blank=True, max_length=256, help_text='eg: Juniorengineer: at L&T ') def __str__(self): return self.work class Education(models.Model): school = models.TextField(max_length=200) college = models.TextField(null=True, blank=True,max_length=200) def __str__(self): return self.school class Skills(models.Model): skill = models.CharField( max_length=256, help_text='Add skills sperated by commas eg: programming, Matlab') def __str__(self): return self.skill class Languages(models.Model): language = models.CharField( max_length=256, help_text='Add language sperated by commas eg: English, Gujarati') enter code here def __str__(self): return self.language class Person(models.Model): name = models.CharField( max_length=100, help_text='Enter a name (e.g. Harry Virani)', validators=[MinLengthValidator(2, "It must be greater than 1 character")] ) picture = models.BinaryField(null=True, blank=True, … -
how to make a like wise button django
I have an Article model which has a votes IntegerField, now I want to make it so that when the user clicks it the votes go up by one and that I managed to make, however, how can I make so next time he clicks it goes down by one. views.py: @login_required def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) vote, created = Vote.objects.get_or_create(article=article, user=request.user) if created: article.votes += 1 article.save() return JsonResponse(data = {"vote": "Voted! Thank you for the vote."}) return JsonResponse(data = {"vote": "You already voted for this article."}) I have a Vote model which has a user and article foreignkey. The button which "likes" article with ajax: <button id="vote" class="button">vote</button> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> var voted = false; $("#vote").click(function (e) { if (!voted) { e.preventDefault() var upvotes = $("#total_votes").html() voted = true; var updatedUpVotes = parseInt(upvotes) + 1 $("#total_votes").html(updatedUpVotes) $.ajax({ url: 'vote/', method: "GET", data: {}, success: function (data) { console.log(data) }, }) } }) </script> Now the other problem is that when the user refreshes the page when he clicks the like button it goes by 1 just in the UI and not in the database, How can I save it so when he comes to an article … -
Allow post request in Apache deployed Django 3.1
I need for my Django app to be able to receive unsolicited POST requests, without the CSRF token. This question has been asked before here, but the answer given, implementing a class based view with functions get and post has not helped me. This is my view class: class WebHooks(TemplateView): def get(self, request): return HttpResponse("get") def post(self, request): return HttpResponse("post") I also added the directive <Location "/"> AllowMethods GET POST OPTIONS </Location> to my httpd.conf for Apache and set the CSRF_USE_SESSION constant in Django's settings.py to False. Testing this with Postman keeps returning "get". The server access log reads POST /url HTTP/1.1" 403 3366. How do I enable POST requests? -
Cannot resolve keyword 'like_count' into field
I'm trying to get data from the model preoperty but i get this error: "Cannot resolve keyword 'like_count' into field. Choices are: comments, created_at, id, likes, text, title, updated_at, user, user_id" My Post model is: class Post(AutoTimeStamped): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=260) text = models.TextField() def __str__(self): return f"Post {self.id}: {self.title}: created {self.created_at}" @property def comment_count(self): return self.comments.count() @property def like_count(self): return self.likes.count() My Post node is: class PostNode(DjangoObjectType): id = graphene.ID(source='pk', required=True) like_count = graphene.Int(source="like_count") comment_count = graphene.Int(source="comment_count") class Meta: model = Post interfaces = (graphene.relay.Node,) It works for my user model, but I'm getting this error when querying posts -
How to create a ModelForm field based on a RelatedManager?
I'm creating a multiple choice quiz with the following models.py: class Question(models.Model): question = models.CharField(max_length=200) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) correct = models.BooleanField(default=False) choice_text = models.CharField(max_length=200) This way, a question's choices can be accessed through its RelatedManager choice_set e.g. q.choice_set.all(). I don't know how to then create a Radio Input Form for each Question? I created the following forms.py: class QuestionForm(ModelForm): class Meta: model = Question fields = ['choices'] However, I'm not sure how I can create a field based on each question's choice_set and then have a radio input for each choice in each question's choice_set? I want the end result to be urls that end up like this: question/1, question/2, etc. with the Question title, radio inputs for the choices and next and previous buttons (where applicable). I have the following FormView and template: views.py class QuestionFormView(generic.FormView): form_class = QuestionForm model = Question template_name = 'quiz/question-form.html' question-form.html <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> -
How open uploaded file in django rest framework?
I try to write a library application on django rest framework. I have two models: File and Book: class File(models.Model): file = models.FileField(upload_to="books//%Y/%m/") class Book(models.Model): filename = models.CharField(max_length=100) title = models.CharField(max_length=200) author = models.CharField(max_length=100) year = models.IntegerField() path = models.TextField() isbn = models.CharField(max_length=100) tags = models.TextField(max_length=200) last_access = models.BinaryField() cover_image = models.BinaryField() upload_date = models.DateTimeField(auto_now=True, db_index=True) owner = models.ForeignKey('auth.User', related_name='uploaded_files', on_delete=models.CASCADE) size = models.IntegerField(default=0) def __str__(self): return self.author + ' - ' + self.title Serializator and view class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" class FileViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = [permissions.IsAuthenticated] How can i open uploaded file in ModelViewSet? Or i must use a generic APIView to override put/post operation for my needs? -
Django Reversion - How to set_comment with Django Rest
I'm trying to save comment in table reversion_revision. However i still got empty value comment What i tried In ModelViewset class ReversionViewMixin(object): def dispatch(self, *args, **kwargs): with transaction.atomic(), reversion.create_revision(): response = super(ReversionViewMixin, self).dispatch(*args, **kwargs) reversion.set_user(self.request.user) reversion.set_comment('Hello') return response @permission_classes([CustomUserPermission]) @parser_classes([MultiPartParser, JSONParser]) class HistoryViewset(ReversionViewMixin, viewsets.ModelViewSet): queryset = Version.objects.all() serializer_class = VersionSerializer filter_backends = (filters.DjangoFilterBackend,) # if pagination page = none, it will return all page def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Any Help, Pls :( Thanks in advance... -
Django Master/Detail
I am designing a master/detail solution for my app. I have searched for ever in the django docs, also here and elsewhere I could, so I guess the answer is not that obvious, despite being an answer many people look for - not only in django, but in every language, I think. Generally, in most cases, the master already exists: for example, the Django Docs illustrate the Book example, where we already have an Author and we want to add several Books for that Author. In my case, the parent is not yet present on the database think of a purchase order, for instance. I have thought to divide the process in two steps: the user would start to fill in the info for the master model (regular form) and then proceed to another view to add the lines (inline formset). But I don't think this is the best process at all - there are a lot of possible flaws in it. I also thought about creating a temporary parent object in a different table and only having a definitive master when the children are finally created. But it still doesn't look clean. Because of that, for my app it … -
CreateView with OneToOneField relation in one View
I'm a Django beginner and try to implement a class based CreateView with two forms and an OneToOne relation but have no glue how to do this in one view. For example: the following is given: #models.py # some imports.. class RedItem(models.Model): name = models.Charfield(max_length=255) storage = models.OneToOneField("Storage", on_delete=models.CASCADE) class BlueItem(models.Model): name = models.Charfield(max_length=255) storage = models.OneToOneField("Storage", on_delete=models.CASCADE) class Storage(models.Model): shelf = models.Charfield(max_length=255) room = models.Charfield(max_length=255) ...the View: #views.py from django.views.generic.edit import CreateView from .models import RedItem, BlueItem, Storage # some other imports.. class RedItemCreate(CreateView): model = RedItem fields = ['name'] template_name_suffix = "_form" and a Form: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The question is now how can a user fill in both (e.g. RedItem + Storage) in one batch? Thanks in advance for any direction. -
Django Rest framework Model serialiser omit null from response
This question is based off another question I have a similar though somewhat different problem: in the original question the user wants to omit a null field from his json response: [ "meta": { "title": null, "name": "XYZ" } ] The one of the answers uses .to_representation() to filter out the title: from operator import itemgetter class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_representation(self, instance): ret = super().to_representation(instance) ret = OrderedDict(filter(itemgetter(1), ret.items())) return ret This works beautifully. The issue I am running into using this method is that I have cases where all my fields get filtered out, leaving me with an empty dictionary: [ {}, { "name":"XYZ" } ] I have tried modifying the method: from operator import itemgetter class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_representation(self, instance): ret = super().to_representation(instance) ret = OrderedDict(filter(itemgetter(1), ret.items())) if not bool(ret): return None return ret But that is also not what I'm looking for, since I get this: [ null, { "name":"XYZ" } ] So my question is: is there a way to filter out the empty dictionary/null completely? I tried passing allow_null=False to the ModelSerialiser but that also doesn't work. -
Django using Ajax for get data without refreshing page
n the last 48 hours. I create a view it works and it displays name correctly but I want to show that How long has it been since the data was sent. I want to do this with Ajax and table will be update without refreshing. I wrote something for that but I get an error. TypeError at / int() argument must be a string, a bytes-like object or a number, not 'NoneType' How can I use Ajax correctly, please help me views.py def get_48_hours(request): increment = int(request.GET.get('append_increment')) increment_to = increment + 10 time_48 = timezone.now() - timedelta(hours=48) results = NavigationRecord.objects.filter(datetime__gte=time_48).order_by('-datetime')[increment:increment_to] paginator = Paginator(results, 10) # Show 50 data per page page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. results = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. patients = paginator.page(paginator.num_pages) context = { 'results': results, } return render(request, 'navigation.html', context) models.py class Vehicle(models.Model): id = models.IntegerField(primary_key=True) plate = models.CharField(max_length=30) def __str__(self): return str(self.plate) class NavigationRecord(models.Model): id = models.IntegerField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) datetime = models.DateField(default=timezone.now) latitude = models.FloatField() longitude = models.FloatField() def __str__(self): return str(self.vehicle) class meta: abstract … -
How to send notifications to gmail from contact form using Django and pushbullet
I'm helping someone update a website that was built a few years ago using Django. On the site there is a contact form that a user fills out and the request is sent to the site admin. My friend wants to get notifications to their gmail account also when the contact form is submitted. The previous developer wrote a code that seems to attempt to do this with Pushbullet API. I'm not familiar with using Pushbullet so I'm trying to find out how this is supposed to work. If anyone is familiar with this way of sending notifications to gmail via the Pushbullet API please enlighten me a bit. I've included the code that is supposed to accomplish the goal. import logging import os from typing import List from django.core.mail import EmailMessage from pushbullet import PushBullet # todo Add mr tires api to .env pb = PushBullet(os.getenv("PUSHBULLET_API")) # Get an instance of a logger logger = logging.getLogger('mail_admins') class Notify: subject: str message: str from_: str = "none.anyname@gmail.com" to: List[str] = [ 'contactemail@gmail.com' 'example@tmomail.net', # 'example@txt.att.net', ] bcc: List[str] = [ # 'example@txt.att.net', 'contact@gmail.com' ] reply_to: List[str] = ['contactemail@gmail.com'] @staticmethod def send(subject: str, message=''): try: logger.info(f"Sending email:\nSubject: {subject}\nMessage:{message}...") email = EmailMessage(subject, … -
Write a view model in Django
How to write a view model in Django which is similar to database view? PS: A view can combine data from two or more table. In my case, i want to combine 5 table in this view. -
Django Template loader searching template in another app
The template loader is searching template file in another app instead of current app. Tn this case, template loader should search in home/templates directory instead its searching template in polls/template directory . Please help my code template loader post-mortem -
Which is the best protocol for video streaming ,websockets or https? [duplicate]
I had created a music website (Django+React) with https protocol and when users play music in frontend they were not able to seek or jumb to middle track of playing music. If I use websockets, can I overcome this ? I have seen many videos in internet which are capable to seek/backward/speed the tracks, do they use websockets ? -
Django Model Form: Foreign Keys: Override Dropdown Menu and Allow For New Entries
I am developing a dictionary application using Django. I am having trouble successfully creating a form using Django's ModelForm class that allows users to submit new definitions to BOTH existing AND new dictionary headwords. Here is my models.py: class Headword(models.Model): headword = models.CharField(max_length=64, unique=True) class Definition(models.Model): definition = models.CharField(max_length=64) headword = models.ForeignKey(Headword, related_name="definitions_headword") Here is my forms.py: class DefinitionForm(forms.ModelForm): class Meta: model = Definition fields = ["headword", "definition"] Here is my HTML form: <form action="{% url 'dictionary:define' %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Define</button> </form> The result of all this is a form with 1) a dropdown menu containing all the headwords already in the database, 2) a text input field for the definition, and 3) a submission button. With the above code, therefore, the user is ONLY allowed to add definitions to headwords that already exist. As I said, I would like to change that and have this form such that users are able to submit definitions to BOTH existing headwords (the ones in the dropdown menu), AND new ones (ones that the user can just type in). This means I wouldn't want a dropdown menu at all in the form, but just two unconstrained text … -
SystemError: Parent module 'setuptools' not loaded, cannot perform relative import
I'm currently using google cloud platform ubuntu vminstance to run vscode. Whenver I run python3 __init__.py, it will return this error: Traceback (most recent call last): File "__init__.py", line 4, in <module> from BatteryModel.batterymodel.conn.sqlDatabase import sqlDatabase File "/home/phuongdoanmr/sensa/SENSA_2020v1/BatteryModel/batterymodel/conn/sqlDatabase.py", line 3, in <module> import django.db as db File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/phuongdoanmr/.local/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 981, in _gcd_import File "<frozen importlib._bootstrap>", line 931, in _sanity_check SystemError: Parent module 'setuptools' not loaded, cannot perform relative import Could anyone please suggest a way to solve this problem. Thanks a lot. -
(Django) How to assign unique values to each user for something linked by ForeignKey?
My group project for school has us building a school management system. I have the following models: Student: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) User.is_student = True enrolled_courses = models.ManyToManyField(Session, blank=True) def __str__(self): return f'{self.user.last_name}, {self.user.first_name}' Session: class Session(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_date_start = models.DateTimeField() course_date_end = models.DateTimeField() def session_id(self): new_session_date = self.course_date_start.strftime('%Y') return f'{new_session_date}{self.course.number}{self.pk}' def __str__(self): return f'{self.course.number} - {self.course.title} - {self.session_id()}' Assignment: class Assignment(models.Model): session_link = models.ForeignKey(Session, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) due_date = models.DateField() title = models.CharField(max_length=50) total_points = models.IntegerField() points_earned = models.IntegerField(blank=True, null=True) objective = models.TextField() def __str__(self): return self.title The problem right now is if I save one value of points_earned to a user, it saves that value to all, since they're linked by the FK. What's the best way to handle it so each Student can have their own score for each assignment? -
Django bicrypt password different from ruby
I have ruby app with mysql database which has password stored.I don't know ruby but from internet what i found is that ruby stores password in bicrypt format. I created one user with password : Password123. What i printed in console was its encrypted password. Tasks: Now i am creating a django app which needs to be connected to same database.I need to verify password from same database.That is i used bicrypt algorithm in django dummy app and created user with same password : Password123. But encrypted text from ruby app and django app are different.It needs to be same for verification from django app. How to do this? Why bicrypt output of both language different. -
Failure to run Django app with Docker compose on the browser
I am working on a Django project, & I am using Docker Compose to set up and run a simple Django/PostgreSQL app. The problem is when I try to run the command "docker-compose up" the terminal gives me the URL to run on the browser but nothing happening in the browser. Can you help me if you have any idea, I will be so thankful. Dockerfile: FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ Docker-compose.yml: version: '3' services: web: build: . command: python src/products_projects/manage.py runserver 192.168.99.100:8000 volumes: - .:/code ports: - "8000:8000" redis: image: "redis:alpine" The Docker Terminal: ## . ## ## ## == ## ## ## ## ## === /"""""""""""""""""\___/ === ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ / ===- ~~~ \______ o __/ \ \ __/ \____\_______/ docker is configured to use the default machine with IP 192.168.99.100 For help getting started, check out the docs at https://docs.docker.com $ docker-machine ip 192.168.99.100 The results in the terminal: web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | August 31, … -
filter queryset based on django countries field
this is my viewset: class PollViewSet(viewsets.ReadOnlyModelViewSet): queryset = Poll.objects.all() serializer_class = PollSerializer() def get_queryset(self): country = self.kwargs.get('pk', None) if country is not None: django_countries.Countries.name(country) return self.queryset.filter(personality__country__name=country) else: country = self.request.user.preferred_country return self.queryset.filter(personality__country=country) model.py : class Poll(RulesModel): personality = models.OneToOneField(Personality, related_name='polls', on_delete=models.CASCADE) start_date = models.DateTimeField(null=True) end_date = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return 'poll#' + str(self.id) + ' ' + self.personality.name here it raises exception that "Unsupported lookup 'name' for CountryField or join on the field not permitted." this is raised in the if condition (else condition works perfectly fine). is there any other way of filtering the query set based on the country's name i actually want to view only the polls related to country passed as a param in the get url -
why am I not able to execute SQL query on my existing postgres database table?
for learning purpose I have migrated my database from SQLite to postgres recently with in my Django project, and it was successful. I am able to connect to the DB through below command sudo -u <username> psql -d <DB_name>; I am able to list the tables including the schema: \d But when I tried to query simple select query it give below error: select * from public.AUTHENTICATION_userprofile; ERROR: relation "public.authentication_userprofile" does not exist LINE 1: select * from public.AUTHENTICATION_userprofile; Table details: Schema | Name | Type | Owner --------+-----------------------------------+----------+---------- public | AUTHENTICATION_userprofile | table | postgres public | AUTHENTICATION_userprofile_id_seq | sequence | postgres Any suggestions please. Thank you