Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Address Django translation messages using variables
Is there a way to set translation messages parametrically in Django? For example, when I need to traslate a message in a template, I always need to write the whole text: <h1>{% trans "Hello World" %}</h1> Instead, I'm wondering if there is something that allows to use variables, something similar to Ruby on Rails: <h1><%= t :hello_world %></h1> -
django messages syntaxerror useing f string
i am trying to send a message to the user of my site when they register i used django message import but i did not work here is my views.py code # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render, redirect from .models import cooking from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages # Create your views here. def homepage(request): return render(request=request,template_name='main/home.html',context={"cooking": cooking.objects.all}) def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.succees(request, f"new account created: {username}")#error on this line login(request, user) return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, form.error_messages[msg]) form = UserCreationForm return render(request,"main/register.html",context={"form":form }) -
Make_password and user.set_password before user saving get different value from after saving
when I create new user, I set pass by user.set_password, after saving make_password make different value from user.set_password, and when I trying to check password by check_password(password,user.password) I get False. But if I call make_password before saving I get same. Sorry for my english ^_^ class MyUserManager(BaseUserManager): def create_user(self, email, password, first_name, sername, sex, date_of_birth, **extra_fields): if not email: raise ValueError('Email must be.') user = self.model( email = self.normalize_email(email), first_name = first_name, sername = sername, sex = sex, date_of_birth = date_of_birth, ) user.set_password(password) user.save() print(f'email {user.email} pass {password} passhash {user.password} hasher {make_password(password)}') return user def create_superuser(self, email, password, first_name, sername, sex, date_of_birth, **extra_fields): if not email: raise ValueError('Email must be.') extra_fields.setdefault('is_staff', True) return self.create_user(email, password, first_name, sername, sex, date_of_birth, **extra_fields) In models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.hashers import check_password, make_password from .managers import MyUserManager # Create your models here. class MyUser(AbstractBaseUser): first_name = models.CharField(max_length = 80) sername = models.CharField(max_length = 80) email = models.EmailField(unique = True) password = models.CharField(max_length = 80) date_joined = models.DateField(auto_now_add = True) date_of_birth = models.DateField() sex = models.BooleanField() balance = models.FloatField(null=True) ticket = models.PositiveSmallIntegerField(null=True) ticket_date_end = models.DateField(null=True) ticket_next = models.PositiveSmallIntegerField(null=True) ticket_next_date_end = models.DateField(null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) REQUIRED_FIELDS = … -
Is there any way to identify the source of a serialization dependency error in django?
I've got a fairly complicated django project with 4 apps and (unfortunately) a bunch of many-to-many relationships. Sometime recently, dumpdata and tests stopped working, throwing the following error: Can't resolve dependencies for app1.ActionItem, app1.ActivityLog, app2.AnnualEvaluation, app1.Citation, app2.Commitment, app1.Complaint, app1.ComplaintStage, app1.ComplaintSubscription, app1.Contact, app1.Document, app2.Feedback, app1.Goal, app2.Goal, app1.GoalUpdate, app1.Investment, app1.KeyDate, app1.Note, app2.ProfessionalDevelopmentGoal, app1.Project, app2.QuarterlyUpdate, app1.ResearchRequest, app1.Source, app1.SubGoal, accounts.Subscription, app1.SupportItem, app2.Tactic, app1.UserProfile, app1.Workplan in serialized app list. This happens whether or not I use natural key handling. Specifying the natural key dependencies explicitly in the model also doesn't seem to have any effect. I know it's a bit of a tangled web, but is there any way to figure out which specific model relationships are causing this error? -
Django project css and js not loading
Had a similar question with an older version of Django... trying to get my site to load with its css and js This is the structure of my project gradMVPV1 --> .idea --> catalog views models apps .... --> gradMVPV1 settings urls wsgi .... --> templates ---->static css js ... ---->index.html db.sqlite3 manage.py this is what I have on settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/templates/static') -
Pointing to index.html in Django
I just updated to a newer version of django and now having difficulties pointing to my index.html file This is the structure of my project gradMVPV1 --> .idea --> catalog views models apps .... --> gradMVPV1 settings urls wsgi .... --> templates ---->index.html db.sqlite3 manage.py This is my settings.py file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, '/templates') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, "index"), ] and views def index(request): return render(request, "index.html") this is my error message ValueError at / dictionary update sequence element #0 has length 1; 2 is required -
Django signals "object has no attribute"
I have problem with show count -=1 with the signals. Pesquisei aqui mas não achei nada parecido, apesar da mensagem de error ser comum: "AttributeError at /admin/statements/statement/ 'Watched_lessons' object has no attribute 'purchased_lessons'" I tried it: watched_lessons/models.py from lessons.models import lesson from django.conf import settings from purchased_lessons.models import Purchased_lessons from datetime import datetime from django.dispatch import receiver from django.db.models.signals import post_delete class Watched_lessons(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) lesson = models.ForeignKey(Statement, on_delete=models.CASCADE) watched_date = models.DateTimeField(default=datetime.now) @receiver(post_delete, sender=Watched_lessons) def rem_watched_lessons_count(instance, **kwargs): instance.purchased_lessons.count -= 1 instance.purchased_lessons.save() The other codes: lesson/models.py from courses.models import Course class Lesson(models.Model): course = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) lesson = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.lesson courses/models.py from django.db import models class Course(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title purchased_lessons/models.py from django.db import models from django.conf import settings from courses.models import Course class Purchased_lessons(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) count = models.IntegerField(default=0) def __str__(self): return self.course When I delete a Lesson, I automatically delete Watched_lessons, because I put the `lesson = models.ForeignKey (Statement, on_delete = models.CASCADE) function` So, I need to automatically, when a "Watched_lessons" is deleted, register a signal "- = 1" in the "count" attribute of purchased_lessons / models.py. How can I … -
Cannot catch an exception in a try/catch block
I have a typical drf view which get some data, serialize it, process it in a separate service. I validate input data with python-trafaret inside my service. def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) # one field serializer; data = JsonField() serializer.is_valid(raise_exception=True) upload_obj = serializer.save() try: self.uploader_class(upload_obj).execute() except UploaderValidateError as e: raise UploadFailed(detail=str(e)) # drf exception with 400 status return Response(status=status.HTTP_204_NO_CONTENT) If trafaret cannot parse input data it raises a DataError. I catch it inside my execute method like this: try: validated_data = self.validate_data(data) except t.DataError as e: raise UploaderValidateError(e.as_dict()) Traceback says that there was an unhandled UploaderValidateError with the text: ...exceptions.UploaderValidateError: {0: {'value': "value can't be converted to float"} I tried to change this line of code: except UploaderValidateError as e: to except Exception as e: but I still can't catch an error -
Django registration template doesn't load form when entered
I have a problem with my Django registration template. To register I'm using a Django-auth system. Theoretically it works, because whenever I enter my registration site, it loads the template, but it only shows my registration button. When I click it, the page reload and the form shows up. I assume it's something about POST method but I can't figure it out to load form right away, after redirect. This is my views.py: class RegisterView(TemplateView): template_name = 'register/register.html' def post(self, request, *args, **kwargs): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() return render(request, self.template_name, {'form': form, }) forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] Here is picture of my register.html template, somehow I couldn't paste it as a code -
Django model's clean method and foreign key validation in FormView
In my django app I have simple Category and Offer models: class Category(BaseModel): title = models.CharField(_('Category title'), max_length=256) available = models.BooleanField(_('Is available'), default=True) slug = models.SlugField(max_length=256, null=True, blank=True, unique=True, verbose_name=_(Slug')) requires_item_price = models.BooleanField(default=False, verbose_name=_('Requires item price to be provided')) class Offer(BaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, verbose_name=_('Category')) item_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, verbose_name=_('Item price'), blank=True) def clean(self): if self.category.requires_item_price and not self.item_price: raise ValidationError({'item_price': _('If category requires item price - you have to provide it')}) My form class: class NewPaginatedOfferForm(forms.ModelForm): class Meta: model = Offer fields = ('item_price',) def __init__(self, category, *args, **kwargs): super().__init__(*args, **kwargs) self.category = category self.helper = FormHelper() self.helper.form_id = self.__class__.__name__.lower() self.initial['category'] = category self.helper.layout = Layout( Field('page_price'), Field('page_per_day'), Div( Submit('submit', _(Save &rarr;'), css_class="btn btn-lg bold btn-block btn-success", ), ) ) and my view class, based on generic CreateView class: class NewOfferForCategoryView(CreateView): model = Offer category = None template_name = 'web/new_offer_for_category.html' def get_form_class(self): print('get_form_class') if self.category.requires_item_price: return NewPaginatedOfferForm def get_form_kwargs(self): print('get_form_kwargs') kwargs = super().get_form_kwargs() kwargs['category'] = self.category print('kwargs:', kwargs) return kwargs def dispatch(self, request, *args, **kwargs): print('dispatch, ', request.method) try: self.category = Category.objects.get(slug=self.kwargs.get('cat_slug'), available=True) except: print('wrong category') return redirect(reverse('web:new_offer')) print('self category is', self.category) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): print('form_valid') form.instance.category = self.category return super().form_valid(form) … -
get objects from db django
How can I get the objects from the db when I press an a tag? View def product(request): template_name = 'u/product.html' search = {"name":["Mais","Perzik","Brocolli"]} context = {"info":search['name']} return render(request, template_name, context) Template {% for x in info %} <a href="{% url 'product' %}">{{x}}</a> {% endfor %} What I want is how can I, if I press Mais, get the products from the db that has the title Mais? Product.objects.filter(product_name=search??) But where and how do I implement this filter? -
How do I avoid `obj.save()` not to update `updated_at` field?
The title alone seems to be vague. Here is the detail. I have the following Model: class Post(models.Model): title = models.CharField(max_length=100) # deleted for brevity created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) count_visits = models.PositiveIntegerField(default=1) # counts visit time of posts and added the following code in blogs.html: {% if post.created_at == post.updated_at %} Posted {{ post.created_at|naturaltime }} {% else %} Updated {{ post.updated_at|naturaltime }} {% endif %} then I made a simple if statement in DetailView to keep track of number of visitors of a certain post: def post_detail(request, title_slug): obj = get_object_or_404(Post, slug=title_slug) session_key = f'key_{title_slug}' if not request.session.get(session_key, False): obj.count_visits += 1 obj.save() request.session[session_key] = True return render(request, 'blogApp/detail.html', {'post': obj}) Here is the problem, When I create a post, in list view it shows Posted now. but as I click the post to view its detail. It shows Updated now and I think I know what is the problem, when I go to detail view. it creates a session_key, increments obj.count_visits += 1 and save the object obj.save(). When obj.save() is called it updates the database including updated_at field and that is why I get Updated now. How do I solve this? I want to … -
java script loop copmare string JSON
I'm having trouble with comparing a simple loop and if condition here , trying to compare a string from a return Jzon file and compare it . here is my json file "interface": [["enp1s0", "e4:3a:6e:09:bb:d3", "10.0.0.250/24", "fe80::e63a:6eff:fe09:bbd3/64"], ["enp2s0", "e4:3a:6e:09:bb:d4", "192.168.0.250/24", "fe80::e63a:6eff:fe09:bbd4/64"], ["enp3s0", "e4:3a:6e:09:bb:d5", "unavailable", "unavailable"], ["enp4s0", "e4:3a:6e:09:bb:d6", "unavailable", "unavailable"]]} and this is my js code that tries to compare if the the ip address is defined to fill mt table function getinterfaces() { $.getJSON('/getips/', function(data) { // document.getElementById("enp1s0").setAttribute("data-value", data.interface) for (i = 1; i < 3; i++) { if (data.interface[i][2]==='unavailable') { document.getElementById('enp'+ i +'s0').textContent= data.interface[i][2]; } else { document.getElementById('enp'+ i +'s0').textContent= 'NOT ASSIGNED'; } } }); } I have a table to fill from the json file ...... <td><span id="en1ps0"></span></td> ..... <td><span id="en2ps0"></span></td> ..... <td><span id="en3ps0"></span></td> ..... <td><span id="en4ps0"></span></td>...... Thanks in advance -
What is the primary key in user creation django
After the user completes the reCaptcha I have this: if result['success']: user = form.save() firstName = form.cleaned_data.get('first_name') messages.success(request, f"New Account Created: {firstName}") login(request, user) messages.info(request, f"You are now logged in as {firstName}") and django says login(request, user) is an error "Cannot force an update in save() with no primary key." -
django dynamic add extra field in same model
i am trying to build a model where one of the fields is dynamic add extra and i am not sure how to go about it when am writing the view. i will be using Jquery to populate the extra fields but how to capture them as only one field is added to the db. Model: class Holding_Company (models.Model): main = models.CharField (max_length = 32 , null = False , blank = False ) sub = models.CharField (max_length = 32 , null = False , blank = False ) -
Django Custom Template Tag Arguments not Passed Through
I have a custom template tag which accesses a model's method to get items. However, when I pass through the correct amount of arguments, it says I am missing one- get_reminder_items() missing 1 required positional argument: 'remind_list' HTML: {% for list in remind_lists %} <h3>{{ list.title }}</h3> {% get_list_items user.username list as list_items %} {% for item in list_items %} <p>{{ item.title }}</p> {% endfor %} {% endfor %} Custom tag: register = template.Library() @register.simple_tag def get_list_items(authenticated_user, remind_list): return RemindList.get_reminder_items(authenticated_user, remind_list) I have no idea why its doing that, as I have the correct amount of arguments passed through. -
Django not loading css and JS
As the question implies, my django doesn't seem to be loading the js and css for my theme. This is the structure of my project: -->mysiteX ---->.idea ---->mysite ------->migrations __init__ admin.py apps.py models.py test.py views.py ---->mysiteX __init__ settings urls wsgi ----->venv -------->Lib ---------->site-packages ----------->django ------------>contrib ------------->auth -------------->templates index.html --------------->static ---------------->js ---------------->css db.sqlite3 manage This is what I have in my settings.py file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'gradientboostMVP/templates') TATIC_URL = 'gradientboostMVP/templates/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
DRF: Many-to-many or Foreign Key please help to create models
I have two models, Item and Content. So what I want is Item to have many Content. class Item(models.Model): title = CharField(max_length=255) content = models.ManyToManyField('Content', blank=True) class Content(models.Model): title = CharField(max_length=255) class ItemSerializer(serializers.ModelSerializer): content = ContentSerializer(many=True) class Meta: model = Item fields = ('id', 'title', 'content',) class ContentSerializer(serializers.ModelSerializer): item_id = serializer.RelatedField(read_only=True) class Meta: model = Content fields = ('id', 'title', 'item_id',) In content serializer, note that i have given extra field item_id. Because i want to return the item Id the content is related to. But I'm not getting item_id in Content List. How do I achieve this? Am I doing something wrong? -
Third party model not shown in Django custom admin site (MaterialAdmin)
Problem: I am using django-material-admin in my Django Application. I am also using another third-party package django-eventlog. The problem is I can see the models in my application. But I can't see third party models that are defined in django-eventlog. When I try to use the plain Django Admin without django-material-admin I can see third-party models defined in django-eventlog. Possible Cause: I believe this is happening because django-material-admin uses its own implementation of AdminSite. Even if it inherits from AdminSite, the package only uses material.admin.sites.site to register admin models. And the recommendation for custom admin views is to use material.admin.decorators.register, which also uses material.admin.sites.site. The problem is that third-party packages will always use django.contrib.admin.site to register their admin models. As django-material-admin is not using this main site, it does not display all their admin views. Help Needed: What could be the potential solution for the same? I don't really want to remove django-material-admin as I am already using it intensively in my application. -
how to display specific results from the dropdown in models.py in django
I want to display only employees which emp_type is 'Doctor'? ** Here is Models.py ** class Employee(models.Model): name = models.CharField(max_length=50) emp_type_choices = [ ('Nurse', 'Nurse'), ('Doctor', 'Doctor'), ('Other', 'Other'), ] emp_type = models.CharField( max_length=6, choices=emp_type_choices, default='Nurse') def __str__(self): return self.name class Ticket(models.Model): patient = models.CharField(max_length=50) doctor = models.ForeignKey(Employee, on_delete=models.CASCADE) def __str__(self): return self.patient.name -
How to add posted time and updated time feature in Django blog post?
I am using the following approach to show when I posted a post and when I updated a post in my blog, but it is not working as expected. I added created_at and updated_at fields as below which keep tracks of when a post was posted and when it was updated. class Post(models.Model): title = models.CharField(max_length=100) # deleted for brevity created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and then in blogs.html {% if post.created_at == post.updated_at %} Posted {{ post.created_at|naturaltime }} {% else %} Updated {{ post.updated_at|naturaltime }} {% endif %} After I create a post, it shows Posted now, but as I refresh the page then after some seconds it shows updated x seconds ago. Why is this happening and how do I solve it? Thank You -
why I have to import manually in django project?
from . import views #working urlpatterns = [ path('', views.index, name='home'), ] Above code is working but it does not work when I import like: from #project_name.#app_name.views ( import by clicking Alt + Enter ) I have created views.py inside app and app is inside project. why this is happening? I'm a beginner and i like to import by clicking Alt + Enter. How can i fix this problem? -
how to use django achieve auto login in a website
I'm doing a website to collect my partners' request.And i want the web can identify who login the web once he/she open my website. For example,you open an website,and you can see the greeting'Welcome,XXX(your name)'.What I want is this,to identify automatically a username or a hostname not manual input username/pwd.Could I get these in the http request headers?or other header info send to server?My friend say to get environment variable can do this,but i don't know how to.I tried request.user or request['username'],but i can't get username.It return nothing. Purpose of the auto function isn't to get user info from a existed user DB,and also i don't have one.But hope to get client username or his/her PC's hostname. By now I don't know how to do this.Possible solution I think can work are: 1.Use cookie.I had try this but not success.I find no info in the cookie my brower send to server,i only can find is a crsftoken code and i don't know how to go on with this situation.I try to go through request.META['somefield'] to get some info,I can find many info only escape username,hostname,remote_name.Result also returns nothing. 2.Use session.I think there may have username/hostname in session.But i don't know … -
Django DateTimeField and datetime.datetime.now() giving different times
I have a model where I want the name field to be a string representation of the timestamp, and another field to be the actual time stamp. Here is my model code: from django.db import models from datetime import datetime class Image(models.Model): name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S")) create_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to="images/") Then I go in the django shell and enter this: >>> import models >>> models.Image(image='images/rock.png').save() This works but the only problem is the two times do not align. For example, I get name = 20191201-143119 and create_date = 2019-12-01 14:32:11.445474. How can I get these two datetimes to be the same? -
is it dangerous to use django 3 for production
you know Django is pre-release of Django and in Django's website wrote This release is only for users who want to try the new version and help identify remaining bugs before the 3.0 release. I want to create my new shopping website with Django 3 how much dangerous is that?