Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to use django-hitcount to count hits on my Class based view
I want to use django-hitcount to count the hits to my Class based views. I was following this documentation https://django-hitcount.readthedocs.io/en/latest/ and it's not clear to me how I could achieve that. I have gone as far as using the HitCountMixin like so class HomeView(TemplateView, HitCountMixin): template_name = 'home/index.html' def get(self, request): sections = Section.objects.all() return render(request, self.template_name, {'sections': sections }) I have gone through every installation step, but the hits are not appearing on the admin interface. -
How to pass a model to a base.html that all templates extend from base.html
I have a Django project which I have a base.html that all templates inheritance from that. Then I include a category.html file in base.html which is just my navigation bar. So I have a model named Category and I want to pass this model to category.html to show my categories. I don't know how to do that? base.html: <!DOCTYPE html> {% load static %} <html lang="en" style="height: 100%;"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}{% endblock %}</title> <!-- Google Fonts --> {% comment %} <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Bootstrap core CSS --> {% endcomment %} <link href="{% static 'fontawesome/css/all.css' %}" rel="stylesheet"> <!--load all styles --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Material Design Bootstrap --> <link href="{% static 'css/mdb.min.css' %}" rel="stylesheet"> <!-- Your custom styles (optional) --> <link href="{% static 'css/style.min.css' %}" rel="stylesheet"> <!-- Mega menu style --> <link href="{% static 'css/bs4megamenu.css' %}" rel="stylesheet"> {% block extra_head %} {% endblock %} {% block slideshow %} {% endblock slideshow %} </head> <body> <!-- Category Navbar --> {% include 'category_navbar.html' %} <!-- Category Navbar --> <!-- Body Content --> {% block content %}{% endblock %} <!-- Body Content --> <!-- Footer and scripts--> … -
How to set logout url in django-registration?
Log out works okay, but I can't set redirect logout url using django-registration. In html: <h3> <a style="color:white" href="{%url 'logout' %}">"Logout"</a></h3> In settings.py: LOGOUT_REDIRECT_URL = "accounts/logout" I can access login page using accounts/login in browser, but it doesn't work for accounts/logout(Page not found.,but this page is in registration folder). -
'UserUpdateForm' object has no attribute 'field'
Error during template rendering In template C:\Users\jaimin patel\PycharmProjects\WEBPROJECT\venv\lib\site-packages\crispy_forms\templates\bootstrap4\field.html, error at line 6 'UserUpdateForm' object has no attribute 'field' from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
MultiValueDictKeyError at /admin/criminals 'gender'
I sufering from the problem with my code, whenever i entered my data into the database and then at time when i click submit it will through an error Multyvaluekeyerror. i change my form value so many times but nothing is working. Please help me out this.....it very be thankfull. MultiValueDictKeyError at /admin/criminals 'gender' Request Method: POST Request URL: http://127.0.0.1:8000/admin/criminals Django Version: 2.2.4 Exception Type: MultiValueDictKeyError Exception Value: 'gender' Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['D:\\django project\\gadmin3', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\lenovo\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Mon, 7 Oct 2019 04:35:54 +0000 MAIN FORM CODE:- <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12">Gender</label> <div class="col-md-6 col-sm-6 col-xs-12"> <div name="gender" id="" class="btn-group" data-toggle="buttons"> <label class="btn btn-default" data-toggle-class="btn-primary" data-toggle-passive-class="btn-default"> <input type="radio" name="" value="male" data-parsley- multiple="gender"> &nbsp; Male &nbsp; </label> <label class="btn btn-primary" data-toggle-class="btn-primary" data-toggle-passive-class="btn-default"> <input type="radio" name="" value="female" data-parsley- multiple="gender"> Female </label> </div> </div> </div> VIEW SIDE CODE:- def criminals(request): if request.method=="POST": cn = request.POST['crname'] ccrime = request.POST['crime'] cage = request.POST['age'] cheight=request.POST['height'] cbody = request.POST['bodymark'] crgen = request.POST['gender'] s= Criminals() s.mname=cn s.mcrime=ccrime s.mage=cage s.image = request.FILES['photo'] s.mheight=cheight s.mbody=cbody s.mgender=crgen s.save() messages.success(request,"Criminal Added Successfully.") return render(request,'criminal.html') else: return render(request,'criminal.html') -
How to have custom success url in update view based on different submit buttons in django template?
I have a CustomUser model and a partner model and a student model both having OneToOne relatioship to CustomUser as below: class CustomUser(AbstractUser): username = None email = EmailField(verbose_name='email address', max_length=255, unique=True, ) first_name = CharField(verbose_name='First Name', max_length=30, null=True, ) middle_name = CharField(verbose_name='Middle Name', max_length=30, null=True, blank=True, ) last_name = CharField(verbose_name='Last Name', max_length=30, null=True, ) phone_number = CharField(verbose_name='Phone Number', max_length=30, null=True, ) is_partner = BooleanField(default=False, ) is_student = BooleanField(default=False, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Partner(Model): user = OneToOneField(CustomUser, on_delete=CASCADE, related_name="partner") class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE, related_name='student') I have a view in which I want to update first_name, last_name, middle_name, and phone_number of the user. This is a simple update view. But I want to put two submit buttons, in edge case, both of which might be available in the page: <form method="post" novalidate> {% csrf_token %} {% include 'includes/accounts/user_name_and_phone_update_view_form.html' with form=form %} {% if user.is_student %} <button type="submit" name="student" id="student">Continue to Student Profile</button> {% endif %} {% if user.is_partner %} <button type="submit" name="partner" id="partner">Continue to Partner Profile</button> {% endif %} </form> I need to customize my view as below(this is pseduo code): @method_decorator([login_required, ], name='dispatch') class UserNameAndPhoneUpdateView(UpdateView): model = … -
After apply lestsencrypt , my nginx server is dead
I deployed django project, with nginx, uwsgi. but after apply ssl(letsencrypt), it works and my server is getting slowly and finally have no react. Is it related with applying ssl?? Please comment even if it is little hint. I totally panic now... -
what is the flow of django website.... what views, templates, models and forms does actually
I am new to django web programming and struggling from 1 month to get the hang of view + models + forms + templates... and i just cant get it fully. please can anyone explain it in simple and to the point. thanks for your help. According to me if i need to show a login page I have 2 options. 1 to use build-in UserCreadentialForms way which is in all the youtube tutorials. 2 is to use custom built. i have successfully used 1 way and now tring to use custom built forms. for this, i goes to models and create a model of my choice (given below) then goes to run that migrate commands to actually create them in database... now tell me how to show/ fillout/ render those fields in the templates. (i am currently using admin url to register/fill out the data in fields and display them on template) base template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} <h1>I am base Template</h1> … -
jquery from base.html not working in other templates in django
I am working on a django application. With templates in django I created multiple pages with one base template. pages like index.html, about.html and contact.html inherit the code from base.html. Inside the base.html template is code for a navbar. base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <!-- fonts --> <link href="https://fonts.googleapis.com/css?family=Anton|Open+Sans&display=swap" rel="stylesheet"> <!-- base.css --> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- base.js --> <script src="{% static 'js/base.js' %}"></script> <title>{% block title %}base{% endblock %}</title> {% block header %}{% endblock %} </head> <body> {% block content %} {% endblock content %} <!-- navbar --> <nav class="navbar fixed-top navbar-expand-lg"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'home' %}">Home</a> </li> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'about' %}">About Us</a> </li> <li class="nav-item"> <a class="nav-link hover_effect" href="{% url 'contact_us' %}">Contact Us</a> </li> </ul> </div> </nav> </body> </html> When viewed in a browser the navbar by default has no background color, but when scrolled down, background-color … -
A lot of JS and CSS after collectstatic Django
In my GitHub repo I have created my Django project. To deploy my app to Heroku, I need first run python manage.py collectstatic and push this staticfile folder that collectstatic command has created to heroku git. So, this staticfile folder contain a lot of falsy statistics e.g 48.6% of CSS (what?) that I don't want to show in my GitHub repo. I have thought to hide it in .gitignore file, but, what if I want to push something else? I will have to unignore this folder, and then add my changes. Is there easier or better way to do this? -
A base64 encoding is returning None from the .bash_profile where I save it as an Environment variable
I saved a base64 encoding as as an environment variable in .bash_profile .bash_profile export ENCODED_JSON="b'Aewe323'" doing the following in a python script returns None import os ENCODED_JSON = os.environ.get('ENCODED_JSON') print(ENCODED_JSON) -
What does it mean of '|' in django template?
Currently I am developing website from another old website & I have faced below code which I am not able to understand properly. I am calling javascript from django template with user permission. test.html file <script type="text/javascript"> (function(){ var data = {'type' : '{{type}}','permissions':{{permissions|safe}} }; var testJS =testInit(data); })(); </script> What does it mean of '|' in {{permissions|safe}}. -
How can I use fingerprints collected from a portable fingerprint sensor for development?
For a standalone web-based program, I need to implement biometric verification. Like, I want to store fingerprints in DB and use it at the time of verification. -
Dictionary 0 key value is not picked up when the values enter through the loop
At runtime it does't access value at index[0] and give error of 'avg' not defined How do i fix it. It require two decimal value but it give only one decimal value. CODE BELOW: n = int(input()) student_marks = {} for i in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores print(scores) print(student_marks) query_name = input() if query_name == name: print(query_name) avg=0 avg=sum(scores)/3 print(avg) OUTPUT: 4 dd 3 34 2 2 [3.0, 34.0, 2.0, 2.0] {'dd': [3.0, 34.0, 2.0, 2.0]} g 3 4 5 6 [3.0, 4.0, 5.0, 6.0] {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0]} d 3 4 534 34 [3.0, 4.0, 534.0, 34.0] {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0], 'd': [3.0, 4.0, 534.0, 34.0]} e 3 4 4 4 [3.0, 4.0, 4.0, 4.0] {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0], 'd': [3.0, 4.0, 534.0, 34.0], 'e': [3.0, 4.0, 4.0, 4.0]} dd Traceback (most recent call last): File "C:/Users/Priya/Desktop/1.py", line 15, in <module> print(avg) NameError: name 'avg' is not defined -
how to connect front-end and djangop api with valid token using AzureAD
I have this front-end using react. In this react application, I added Azure Oauth2 ( i used react-adal ) sign-in. I want to pass the token from the front-end to django-api so whenever i call the api, I have this valid token. -
How to save the CSV file in variable
I'm new to Django and Python. I'm trying to compare two CSV files and make a new file as a result (how much both files are different from each other) in my views.py. First, I get those files and set them into a variable, to make sure that the user can select and compare any file with any name. But I got this error. FileNotFoundError at /compare [Errno 2] No such file or directory: 'fine_name.csv' what I'm expecting is, when the user selects two files and hit on the compare button, they got a new updated CSV file 'update.csv'. Here is my code views.py from django.shortcuts import render from django.http import HttpResponse def comp(request): if request.method == 'POST': file1 = request.POST.get('file1', '') file2 = request.POST.get('file2','') with open(file1, 'r') as t1, open(file2, 'r') as t2: fileone = t1.readlines() filetwo = t2.readlines() with open('update.csv', 'w') as outFile: for line in filetwo: if line not in fileone: outFile.write(line) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="update.csv"' return response return render(request,'compare.html') compare.html {% extends 'base.html' %} {% block title %}Comparision{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-md-center"> <div class="col-md-6"> <form method="POST" action="">{% csrf_token %} <h1 class="mb-3 display-4 text-light">Comparision</h1> <input type="file" id="file1" … -
django query: get objects where only 'time' is greater than HH:mm no matter what the date is?
I have a model called, MinutePrice, which has a DateTimeField as one of fields. What I want to do is making query of objects whose time is greater than 15:30, no matter what the date is. What I've tried: MinuetePrice.objects.filter(Q(date_time__lte="15:30")) Errors occured: ValidationError: ["'15:30' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] Any ideas to solve this? -
IntegrityError Primary Key Invalid in django
Something fixed in Order Class of model. and then, I run migrate. But, it is shown an error as django.db.utils.IntegrityError: The row in table 'core_order' with primary >key '4' has an invalid foreign key: core_order.billing_address_id contains a >value '1' that does not have a corresponding value in core_address.id. Models.py from django.conf import settings from django.db import models from django.db.models import Sum from django.shortcuts import reverse from django_countries.fields import CountryField # Create your models here. CATEGORY_CHOICES = ( ('SB', 'Shirts And Blouses'), ('TS', 'T-Shirts'), ('SK', 'Skirts'), ('HS', 'Hoodies&Sweatshirts') ) LABEL_CHOICES = ( ('S', 'sale'), ('N', 'new'), ('P', 'promotion') ) ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return … -
Django rest serializer validation errors during update
I have a separate serializer for updating a user's account, and for some reason whenever I try to use an invalid input its not sending the validation errors as a response, its only sending back the original values that were set. Eg. old username is abc123, if I try to update it to abc123* i want it to throw an error saying its not a proper format but instead it just sends back abc123 as serializer.data. Anybody know why this is happening? serializer class UpdateAccountSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=16) full_name = serializers.CharField(max_length=50) class Meta: model = Account fields = ['username', 'full_name'] def validate_username(self, username): if Account.objects.filter(username=username).exists(): raise serializers.ValidationError(_("This username is taken.")) if not re.fullmatch(r'^[a-zA-Z0-9_]+$', username): raise serializers.ValidationError( _("Usernames must be alphanumeric, and can only include _ as special characters.")) return username def validate_full_name(self, full_name): if not re.fullmatch(r'^[a-zA-Z ]+$', full_name): raise serializers.ValidationError( _("Invalid name.")) return full_name def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.full_name = validated_data.get( 'full_name', instance.full_name) instance.save() return instance view class UpdateAccountView(APIView): def patch(self, request, pk, format=None): account = Account.objects.filter(id=pk) if account.exists(): account = account[0] if request.user == account: serializer = UpdateAccountSerializer( account, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_404_NOT_FOUND) If you're wondering … -
Is there such thing as a VideoField in Django?
So I have been making a site recently, and I want a way for people to upload videos and for me to display them, just like I do with an ImageField. However I have found that VideoField is not a thing. I have used FileField so far, and it is uploading to the right folder, however I don't know how to display that video like an ImageField. I want to use something specifically made for video files, but so far I have't found anything online about VideoFiles. Here is my model. class Post(models.Model): # ... other things here video_file = models.FileField(upload_to='post_files',blank=True,null=True) So my question is: is there a VideoFile in Django? -
If statement throws TemplateSyntaxError Invalid block tag on line 119: 'else', expected 'empty' or 'endfor'
I am trying to make a django app, but I am encountering the following error: Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 119: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have reviewed the code, and can not find any typos in my template file, but the template loads normally without the following lines: {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link">{{ i }}</a> </li> {% else %} <li class="page-item"> <a href="?page={{ i }}" class="page-link">{{ i }}</a> </li> {% endif %} {% endfor %} My entire code for the app is in this github repo in the listings folder: https://github.com/twheelertech/btre_project I have checked models.py and views.py in the listings app, but they seem to be formatted correctly. I am using windows 10, python 3.7.3, django 2.2.6 Thanks for the help. :) -
Take the current value of a variable (for the logged-in user) and save it to database
I would like to take the current value of a variable which is in a javascript in my templates.py, and save it to the database for the current logged-in user. Thanks -
Django slugs not unique wuth unique=True
I created two articles with the title "test" and this is what the second one generates as an error: duplicate key value violates unique constraint "xxx_content_slug_xxxx_uniq" DETAIL: Key (slug)=(test) already exists. Knowing that this is my model: class Content() id = models.AutoField(primary_key=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Content, self).save(*args, **kwargs) and knowing that I made the migration in the DB. I don't know how to solve that. Note: The problem is generated from the class post that inherits the content class and I don't think this information can help. -
Fastest way to implement commenting feature
I am implementing Instagram like commenting feature in my mobile application. The format of each comments at the user end looks like this: Hello @user1 and @user2 How are you today? Now there are 2 very interesting situations here: The server uses some regex pattern and extract the "user1" and "user2". When the user hits an API to view all such comments, the client side logic also parses each comment and extracts each "user1" and "user2" from the comment string. I don't think my solution or approach is scalable and would make the user experience quite laggy as there would be so much computations involved even though I use pagination to bring about 30 comments at once. Can someone give their opinions/knowledge as to what business logic should I use to make it fast and scalable? -
What framework to use for my mobile backend
I am creating a mobile application, similar to the snapchat app, and have already coded my frontend. I am not sure which framework to use for my rest api, which will serve as my backend. The choices are between NodeJs, Django and spring boot Which one would be the most efficient for this task. Thank you.