Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show messages using django messages framework from one particular view
I'm using Django messages framework to show a success message in my contact page template when contact form submission is succeed. since installed app, middlewares and context processor for messages are set in settings.py all the messages that are being generated showing in my contact template, for instance, Login success, logout success, and so on. I just want to show the message.success in the contact templete that I defined in contact view: def contact(request): if request.method == 'POST': Contact.objects.create( first_name=request.POST.get('first_name', ''), last_name=request.POST.get('last_name', ''), email=request.POST.get('email', ''), subject=request.POST.get('subject', ''), message=request.POST.get('message', ''), ) # I want to show only this message on 'POST' success of this view messages.success(request, "Your message has been submitted.") return render(request, 'contact/contact.html') my template: <div class="success-message"> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> <h4 class="alert-success text-center" style="padding-top: 5px; padding-bottom: 5px;"> {{ message }} </h4> </li> {% endfor %} </ul> {% endif %} </div> my template is showing all the messages that are being generated throughout the website along with the one that I want. how to prevent other messages except the one that I want? What is the workaround for this problem, Can somebody help me through this? -
Django | Ordering - How to implement "ordering" when you use @property
please help me to make the correct "ordering" for a "custom" property some_property_field. I write such an URL and it doesn't work. I understand the reason is a "custom" property. How to work it out? /api/articles/?ordering=-some_property_field models.py class Article(models.Model): title = models.CharField(max_length=20) description = models.TextField() def __str__(self): return self.title @property def some_property_field(self): return f'{self.title} property func' views.py class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) ordering_fields = ('id', 'title',) ordering = ('id',) # default ordering serializers.py class ArticleSerializer(serializers.ModelSerializer): some_property_field = serializers.CharField(read_only=True) class Meta: model = Article fields = '__all__' -
Django Crispy Forms: Apply a custom title attribute to each error
Situation To inject errors into my registration form, I do some checks in my form class's clean methods (e.g. clean_email(), etc.) and call form.add_error('attribute', 'error message'). I render my forms with django-crispy-forms by using the {% crisy form %} template tag. What I want to do is to set custom title attributes for the error messages which get rendered in span tags. I would prefer to be able to do that within the Django form itself, if possible, but if there is another way, I am open to that as well. Example For example, instead of... <span id="error_1_id_password" class="invalid-feedback"><strong>Password must have an uppercase and a lowercase letter</strong></span> <span title="Password 1 error" id="error_1_id_password" class="invalid-feedback"><strong>Password must have an uppercase and a lowercase letter</strong></span> I have looked at some of the documentation for FormHelper but I don't see any mechanism that will let me apply specific title attributes to each error message. The Current HTML Form The HTML that gets rendered for the form is (notice in particular, the span tags with the errors): <form action="/users/register/" method='post'> <input type="hidden" name="csrfmiddlewaretoken" value="dU7WZ5jCZExYw10TZs6xke4cSj6jFpXZq285IJM3KILHKeGlilkNkAdozSrzAMno"> <div class="form-row"> <div class="col-md"> <div id="div_id_first_name" class="form-group row"> <label for="id_first_name" class="col-form-label col-25 fs-400 ff-sans-normal requiredField">First name<span class="asteriskField">*</span></label> <div class="col-75"> <input type="text" name="first_name" … -
How can I install new product logic in Django?
In Django, when the product is newly added, I want the new product to be named for about 1 week and appear on the new products page. How can I build the logic of this? model.py class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) main_image = models.ImageField(upload_to='static/product_images/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=1000) price = models.FloatField() brand = models.CharField(max_length=50, default='Markon', verbose_name='Brand (Default: Markon)') sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)") bestseller = models.BooleanField(default=False) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) stock = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @property def discount(self): dis = float(self.price - (self.price * self.sale) / 100) ln = '' if len(str(dis)) > 3: for i in str(dis): ln += i dis = float(ln) if len(ln) > 3: break return dis -
How to get the value of a radio button in django
I am learning django. I am stuck with this problem. I want to create an upload form which has a field for gender. SO basically, it has radio buttons for male and female. Please note that I have not created forms.py file I just created a template in HTML and the rest of the processing happens in the views.py file. So, I want to know how can I pass the value of the radio button to the views.py file. I have seen some tutorials and articles but they seem to be too complicated and also use forms.py file. Is there anything simpler. I am a newbie and any help will be appreciated. -
Django primary key url issues
I am makeing a simple blog project. In my project, there is one page where there is a list of all the blog posts. If you click on the title of the post you are taken to the post. I used (?P\d+) I the URL path so the user would be directed to the correct post. However, this did not work. Any help would be much appreciated. all_posts.html {% extends "base.html" %} {% block content %} <div class="container"> <h1>Blog Posts</h1> </div> <div class="container"> {% for blog_post in object_list %} <table class="table table-striped"> <ul class="list-group"> <li><a class="btn btn-primary" href="{% url 'blog_app:view' pk=blog_post.pk %}">{{ blog_post.post_title }}</a></li> </ul> </table> {% endfor %} </div> {% endblock %} modles.py from django.db import models # Create your models here. class Blog_Post(models.Model): slug = models.SlugField(max_length=1000, editable=False, null=True) post_title = models.CharField(max_length=100, editable=True, blank=False, null=True) blog_content = models.TextField(max_length=10000, blank=False, editable=True, null=True) files = models.FileField(blank=True, null=True, upload_to=True) date = models.DateTimeField(blank=False, null=True, auto_now=True, editable=False) likes = models.IntegerField(blank=True, null=True, editable=False) urls.py from django.urls import path from . import views app_name = "blog_app" urlpatterns = [ path('create/', views.create_blog_post.as_view(), name='create'), path('view/(?P<pk>\d+)/', views.view_blog_post.as_view(), name='view'), path('all_posts/', views.all_blog_posts.as_view(), name='all'), path('delete/<slug:slug>', views.delet_blog_post.as_view(), name='delete') ] -
Django AllAuth resent password even if the password is not in the database
How do I prevent django-allauth from sending password recovery emails to emails not registered in the database? -
django convert function view to class view
I have a problem converting from a function-based view to a class-based view, function VIEWS.PY @ login_required def favourite_add(request, id): post = get_object_or_404(Perfumes, id=id) if post.favourites.filter(id=request.user.id).exists(): post.favourites.remove(request.user) else: post.favourites.add(request.user) return HttpResponseRedirect(request.META['HTTP_REFERER']) URLS.PY urlpatterns = [ path('fav/<int:id>/', views.favourite_add, name='favourite_add'), ] TEMPLATE.HTML <div> <a href="{% url 'favourite_add' perfume.id %}" class="btn btn-outline-primary">Add</a> </div> In general, the goal is to get the id of a certain perfume on the page, and using the get_object_or_404 function, I'm pulling its object from the Perfumes database - the post variable. Next, I want to retrieve the id of the logged-in user and check if the id of the above user is in the favourites section of the post variable. If not then add, otherwise remove the user id to the favourites section of the post variable. -
Django URL errors
I'm learning Django and I encountered some URL issues that I can't solve. I think it's a URL problem so I'm not sure if the views are needed, but I post them anyway(I'm kind of desperate) The first problem is that when I try to log in with wrong credentials, I get an error. TemplateDoesNotExist at /home/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/home/login/ Django Version: 3.2.12 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\dell\ofaw\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Users\dell\ofaw\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\dell\\Desktop\\OneForAll\\Django website\\ofaw', 'C:\\Users\\dell\\ofaw\\Scripts\\python37.zip', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\dell\\ofaw', 'C:\\Users\\dell\\ofaw\\lib\\site-packages'] Server time: Sat, 09 Apr 2022 18:43:41 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\dell\ofaw\lib\site- packages\django\contrib\admin\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\ofaw\lib\site- packages\django\contrib\auth\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\ofaw\lib\site- packages\crispy_forms\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\Desktop\OneForAll\Django website\ofaw\register\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\dell\Desktop\OneForAll\Django website\ofaw\profiles\templates\registration\login.html (Source does not exist) In terminal. django.template.exceptions.TemplateDoesNotExist: registration/login.html [09/Apr/2022 19:43:41] "GET /home/login/ HTTP/1.1" 500 79486 The thing is registration folder was in my first app Templates but I delete it, I don't even know why is still showing it. I use to have an HTML form with action="register" that directed me to … -
Django, request.user prints AnonymousUser, even if i logged in
views.py class StorageView(viewsets.ModelViewSet): serializer_class = StorageSerializer def get_queryset(self): if self.request.user.is_authenticated: user = self.request.user queryset = Storage.objects.filter(username=user.username) return queryset else: print(self.request.user) return [] urls.py from django.urls import path, include from django.urls import re_path as url urlpatterns = [ path('auth/', include('rest_auth.urls')), path('auth/register/', include('rest_auth.registration.urls')) ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # CORS 'corsheaders', # REST 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'django.contrib.sites', # App 'backend' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P", 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } I logging in via form or api, but is_authenticated method don't see me Login via api postman screenshot Condition in get_queryset() function in views.py always evaluates to false, even if i logged in it keeps printing "AnonymousUser", why? How to check if user is logged in, in my case? -
Django migration error in heroku postgres
I've just deployed my Django website on Heroku and while running the command to make migrations it shows a lot of migrations to apply but when I try to migrate it, it says no migrations to apply. Here's a photo of it. -
Django 3 claims column does not exist after fixing database manually with pqsl
Something went wrong with the migrations and now, even when I run makemigrations I get: django.core.exceptions.FieldDoesNotExist: mq.pipeline has no field named 'mq_pipepline_id' I used psql to change this particular column name from mq_pipeplineid to mq_pipepline_id. To fix what seemingly went wrong, running: psql \c myapp ALTER TABLE mq_pipeline RENAME COLUMN mq_pipeplineid TO mq_pipepline_id; And I can see the changes. I quit qsql and entered it again to make sure the changes are persistent. Now, the table definitely has that column, but strangely I still get the same error. Is the error not referring to the database itself, but to the migration files? -
Django date field derived from timestamp field
I have a created_date field: class Comment(models.Model): created_date = models.DateTimeField(auto_now_add=True) I want a field derived from created_date that ideally exists in the model. I know in SQL I can do: SELECT created_date::date FROM Comment How would I define that in the Django model? -
What's wrong with GraphQL theme?
I'm learning GraphQL now on my test project with Django, and can't understand where the problem is. Here is my models.py class Teacher(models.Model): full_name = models.CharField(max_length=70, verbose_name="Full name") subject = models.ManyToManyField( "Subject", related_name="teacher_subject", verbose_name="Subject" ) def __str__(self): return self.full_name class Subject(models.Model): name = models.CharField(max_length=100, verbose_name="Subject name") def __str__(self): return self.name class Meta: verbose_name = "Subject" verbose_name_plural = "Subjects" ordering = ["name"] class Student(models.Model): full_name = models.CharField(max_length=70, verbose_name="Full name") subject = models.ManyToManyField( "Subject", related_name="student_subject", verbose_name="Subject" ) avg_grade = models.FloatField(verbose_name="Average grade") def __str__(self): return self.full_name Here is schema.py import graphene from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from graphql_app.models import Student, Subject, Teacher class TeacherType(DjangoObjectType): class Meta: model = Teacher # fields = ("id", "full_name", "subject") filter_fields = { 'id': ['exact'], 'full_name': ['exact', 'icontains', 'istartswith'], } interfaces = (graphene.relay.Node,) class SubjectType(DjangoObjectType): class Meta: model = Subject # fields = ("id", "name") filter_fields = {'name': ['exact', 'icontains', 'istartswith']} interfaces = (graphene.relay.Node,) class StudentType(DjangoObjectType): class Meta: model = Student # fields = ("id", "full_name", "subject") filter_fields = { 'id': ['exact'], 'full_name': ['exact', 'icontains', 'istartswith'], } interfaces = (graphene.relay.Node,) class Query(graphene.ObjectType): teacher = graphene.relay.Node.Field(TeacherType) subject = graphene.relay.Node.Field(SubjectType) student = graphene.relay.Node.Field(StudentType) teachers = DjangoFilterConnectionField(TeacherType) subjects = DjangoFilterConnectionField(SubjectType) students = DjangoFilterConnectionField(StudentType) def resolve_teacher(self, info, **kwargs): num … -
Why leads deletion of UUIDField to Django SystemCheckError
I've been building a Django website and included a UUID field "customer_id" in my initial "Customer" model. Finally, I decided to drop it. But when I try to delete it from my models.py, Django throws SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomerAdmin'>: (admin.E035) The value of 'readonly_fields[1]' is not a callable, an attribute of 'CustomerAdmin', or an attribute of 'accounts.Customer'. Here is the code of models.py from django.db import models import uuid # Create a base model to make sure we keep track of creation and edits class ModelBaseClass(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) date_modified = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True # Create your models here. class Customer(ModelBaseClass): customer_id = models.UUIDField(default=uuid.uuid4, #this is the field i try to drop editable=False, unique=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name What I tried so far: I suspect that this could be related to existing data or some other dependencies. So... I deleted the sqlite database, deleted all migration files and ran "python manage.py makemigrations" and "python manage.py migrate". I ran python manage.py flush. I also tried to change the editable=False to editable=True and migrate before dropping, but it didn't change anything. It's perhaps also … -
django query set how to get last n records
class Message(models.Model): host = models.ForeignKey(NewUser, on_delete=models.CASCADE) body = models.TextField(max_length=1000) created = models.DateTimeField(auto_now_add=True) class Comments(models.Model): message = models.ForeignKey(Message, on_delete=models.CASCADE) publisher = models.ForeignKey(NewUser, on_delete=models.CASCADE) body = models.TextField(max_length=300) created = models.DateTimeField(auto_now_add=True) I have this app where i want to display in template last 5 comments for every message. How can i get last n comments that matches to specific message? I've tried: comments_all = Comments.objects.all().order_by('-id')[:5] but it just returns 5 last comments regardless of message. -
How can I undo this (accidental) table inheritance in Django?
I've got a django app library in production, and have found a major flaw. The library declares AbstractMyModel from which a concrete MyModel inherits. Users of the library can choose to install the app and use MyModel directly, or just import the abstract models to do their own thing with. The problem is that AbstractMyModel isn't abstract. I forgot to include a class Meta() declaring abstract=True. So I basically have a table inheritance in production: class AbstractMyModel(models.Model): """Abstract model... EXCEPT IT'S NOT!!!""" name = models.SlugField( help_text="name", unique=True, ) class MyModel(AbstractMyModel): """ARGH - the abstract one isn't actually abstract But I've got this in production - there are two actual tables from AbstractMyModel and MyModel. How can I sort this mess out?""" QUESTION: How would I migrate my way out of this, to collapse the inheritance and end up with the MyModel table as concrete and AbstractMyModel as truly abstract? TIA! -
Django - Register m2m in admin
Facing some troubles with m2m in inline. class Task(models.Model): title = models.CharField(...) performer = models.ForeignKey(User, ...) for_control = models.ManyToMany('self', ...) class TasksForControlInline(admin.TabularInline): model = Task.for_control.through fk_name = 'from_task' show_change_link = True # not displayed because m2m is not registered in admin I cannot add task for control in inline. Is it possible to register m2m in admin? -
How to pass parameters delete method? (django)
I have model Like and want to delete this object with parameters. it's code -> Like.objects.filter(user=self.request.user, question=self.get_object()).delete() and also I have signal @receiver(post_delete, sender=Like) def delete_like(sender, instance, using, **kwargs): instance.question.point -= 1 instance.question.save() I want something like that Like.objects.filter(user=self.request.user, question=self.get_object()).delete(status="Testing") and after using this status while deleting -
Password reset django-allauth and django-rest-auth
I cannot wrap my head around this problem. Read a lot of solutions but cannot seem to find the correct combination that works for me. I want to initiate a users password reset flow from within my (android/iOS) app. I think I need django-rest-auth for this to expose an API endpoint something like this: from rest_auth.views import PasswordResetView urlpatterns = [ path('password/reset/', PasswordResetView.as_view(), name='rest_password_reset'), ] Now posting to http://127.0.0.1:8000/password/reset/ with a JSON payload of { "email": "test1@test.com" } gives an error: django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. Now, I'm strugeling with the next part. I found that password_reset_confirm is defined in django.contrib.auth but I do not want to expose the admin-like interface to the user. I'd like to use the allauth PasswordResetFromKeyView. So, defining password_reset_confirm as: path('password/reset/<uidb64>/<token>/', PasswordResetFromKeyView.as_view(), name='password_reset_confirm' ), Works. An email is send containing a reset URL. But now, following that URL I'm getting another error: PasswordResetFromKeyView.dispatch() missing 2 required positional arguments: 'uidb36' and 'key' Ok, obvious, changed the password_reset_confirm path arguments from <uidb64> and <token> to <uidb36> and <key>. Than the error moves to password_reset_email.html because of the arguments in {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Ok, also changed that to uidb32=uid and … -
Django - Update database value on drag and drop
I am creating TODO app, and I am trying to implemnt drag and drop using JavaScript. I managed to create drag and drop feature but I don't know how to change and save tasks "category" (for example backlog to done) on drop. Do I need to use JavaScript or is there some Django library that can help me? If JS is necessary, what should I do? -
how to give parameters when connecting to different webpages in django framework
I'm trying to link two webpages in django framework, using anchor tags in template. One of my view takes an argument and I can't figure out how to pass a parameter in template. This is a url pattern that takes argument. path("<str:entry>",views.display_entry,name="entry") corresponding view is: def display_entry(request,entry): text = str(util.get_entry(entry)) markdown = Markdown() html = markdown.convert(text) html_file = open(f"encyclopedia/templates/encyclopedia/{entry}.html",'w') html_file.write(html) html_file.close() return render(request, f"encyclopedia/{entry}.html") and template where I'm trying to access this view is - <ul> {% for entry in entries %} <li><a href="{% url 'encyclopedia/entry' %}">{{ entry }}</a></li> {% endfor %} </ul> -
js spread operator syntax error django compressor
Im trying to configure the ifs.js library in my project, it uses rollups, and I found django compressor to bundle files, but I got an error of syntax, not really sure whats wrong, everything is configured ok, and I got this error CommandError: An error occurred during rendering b_proy/prueba_ifc.html: SyntaxError: /home/fcr/anaconda3/envs/gda/a_viurb/a_viurb/static/ifc/bundle.js: Unexpected token (87230:6) 87228 | throw new Error(nullIfcManagerErrorMessage); 87229 | const modelConfig = { > 87230 | ...config, | ^ 87231 | modelID: this.modelID 87232 | }; 87233 | return this.ifcManager.createSubset(modelConfig); it is the spread operator, it seems the compressor doesnt recognize it, I saw other similar questions and the answer was to not minify the js code, but in my case is a 2mb js file, so I really hope there's another way to solve this, thanks -
django_tables2 mixins, display non-joinable models with concatenated rows
For some contrived reason I have two QuerySets which match up in row-order, but don't have a shared foreign key, so a join is not possible. I don't have the ability to add a key here, so I'd like to do a "hstack" of the two results and display as a table. This is easy with jinja templating, but I'd like to use the convenience functions of tables2 (e.g. sorting, etc) and I would like to still retain the ability to do foreign key traversal on each queryset. Equivalently, consider providing a QuerySet and a list of external data that is the result of an operation on that QuerySet. qs = ModelA.objects.filter( ... ) # queryset ext_data = get_metadata_from_elsewhere(qs) # returns a list of dict # len(qs) == len(ext_data) For example, with two models I can create a Mixin: class ModelATable(tables.Table): class Meta: model = ModelA class ModelBTable(ModelATable, tables.Table): class Meta: model = ModelB Which produces a rendered table with the fields from both models. If I supply ModelBTable(query_model_b) then only those fields are displayed as expected, and similarly for ModelBTable(query_model_a). How do I provide both query_model_a and query_model_b? Also if there's an easy way to do hstack(query_a, query_b) then … -
Conflict on Python Django API Deployment
Please, i'm very new to Python and Django, a friend (non developer) reached out to me on deploying django on digitalocean. I've tried troubleshooting some of my issues but dont understand how to solve the latest one: The conflict is caused by: The user requested Django==2.2.16 django-cors-headers 3.2.1 depends on Django>=1.11 django-filter 2.0.0 depends on Django>=1.11 django-phonenumber-field 4.0.0 depends on Django>=1.11.3 django-rest-knox 3.0.3 depends on django django-rq 2.3.2 depends on django>=2.0 djangorestframework 3.11.1 depends on django>=1.11 drf-yasg 1.20.0 depends on Django>=2.2.16 django-rest-logger 1.0.4 depends on Django<=2.2 and >=1.11 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies ERROR: failed to build: exit status 1 I've tried visiting the address but dont know what to do with the information given. Please, help me out