Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any other chances to resolve this issue
Admin Login Error : DJANGO I have created a django super user for admin. I have added AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) in settings.py file but when I enter the same credentials it is showing the below erro: ** django admin showing username and password incorrect.both fields are case insensitive ** -
django redirect after form save
I have a detail view with 2 forms and here I provide code for only one of them. The form is located in a modal on user detailed view and I need to redirect the client to that detail view in which the form is. In the post method the request.GET['user'] returns the user id so I have everything needed to achieve this. I have tried the reverse and redirect, nothing worked I guess because of wrong code. Should I provide a get_success_url() to do that? model = TbUser def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['entrance_rights_form'] = TbPeopleEntranceRightForm( user=self.object, initial={'user': self.object}) return context class TbPeopleEntranceRightFormView(FormView): form_class = TbPeopleEntranceRightForm template_name = 'users/create_entrance_permission_modal.html' def post(self, request, *args, **kwargs): print(request.POST['user']) # returns user id entrance_rights_form = self.form_class( user=None, data=request.POST) terminal_permissions_form = TbTerminalPermissionForm(user=None) if entrance_rights_form.is_valid(): entrance_rights_form.save() return redirect('user-detail', args=(request.POST['user'],)) else: return redirect('users-list') urlpatterns = [ path('users-list/', UsersListView.as_view(), name='users-list'), path('user-detail/<str:pk>/', UserDetailView.as_view(), name='user-detail'), path('tb-entrance-right-form/submit', TbPeopleEntranceRightFormView.as_view(), name='tb-entrance-right-form'), ] -
django admin list data using default filter
i have model like this ### models.py class Pizza(models.Model): name = models.CharField() price = models.IntegerField() have_recipe = models.BooleanField() ### admin.py admin.register(Pizza) class PizzaAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'price') exclude = ('have_recipe',) when I enter localhost:8000/admin/pizza i can see all of pizza objects, but, I want to make admin pizza list show only have_recipe=True objects and nobody can't control this filter in admin page is there any solution?? -
AM PM not working in django html template
I am getting Enter a valid date/time. error when trying use AM and PM. Without AM PM I am not getting any error. I am using bootstrap datetimepicker in my html template. here is my code: froms.py class BlogForm(ModelForm): class Meta: model = Blog fields = ['title','body','published'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control','placeholder': 'Title'}), 'published': forms.DateTimeInput(format=['%Y-%m-%d %I:%M %p']) } #html <form method="POST" enctype="multipart/form-data"> {{from}} </form> <script> $(function () { $("#datetimepicker1").datetimepicker({ format: 'YYYY-MM-DD hh:mm:ss a', }); }); </script> -
How to idealy setup Model For default items in Djaago
I have a Django application, where the business can add items in Item Model. Also, some of the common items should be there in the database which is provided by the admins(me) which will be shown to the users and they can add that if they want. If the select that item a new item will be created in the database with values from the selected item and the user field in the item model will point to the user who created it. From that instant, the user has a copy of that item under their control. They can edit values if they want. How to implement this system. I have two options Adding the common items in the item model itself with user field equals to null, and maybe add another field to identify it is added bt admin. Create a separate model for default Items. Which is the ideal method? Or is there an alternate method? -
How to return values without breaking a function [duplicate]
I'm generating an html file to print in a thermal printer. But since I can't use django template tags I'm generating it on the views.py. Since I can't predict the item number, I was using a loop. def total(): for ordered_item in ordered_items: title = ordered_item.food.title['tm'] price = ordered_item.food_size.price quantity = ordered_item.quantity return str(title),str(price),str(quantity) And I'm using that here: html=""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use PyQt5 to print thermal receipts</title> </head> <body> <img src='http://c.biancheng.net/cpp/templets/new/images/logo.jpg?v=3.994' style="align-items: center;" width="130" height="130"/> <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: """ + str(order.code) + """ </span> <br> <br> <span>Order time: """ + str(order.created) + """</span> <br> <br> <span>Cashier: """ + str(order.waiter) + """</span> <br> <span>---------------------------------------</span> <div class="section4"> <div> <table> <thead> <tr> <th width="110">Product name</th> <th width="80">Unit price</th> <th width="30">Quantity</th> </tr> </thead> <tbody> <tr> <td>""" + str(total()) + """</td> </tr> </tbody> </table> </div> <br> <span>---------------------------------------</span> <br> <div class="total"> <span>Total : """ + str(order.total_cost) + """</span> <br><br> <span>Paid : """ + str(order.paid) + """ </span> <br><br> <span>Change : """ + str(change) + """ </span> </div> <br> <span>---------------------------------------</span> </div> <div class="section5"> <span>Thank you for your patronage! </span> </div> </div> </div> </body> </html> """ But my function exits after the first loop. Is … -
Why can't select one object in django
I'm creating a ecommerce store using django And tried s many things to do this.index page is working pretty well but I want select specific product when I click .ex: when I click a shoe I want to enter shoe detail page with shoe image and all the necessary details.Here is my home page.And also I highly recommend to check my all code because you can't get any idea with only this code.github source code here.thanks dinindu {% extends 'store/main.html'%} {% load static %} {% block content %} <style> img:hover{ opacity: 0.5; } </style> <div class="row"> {% for product in products %} <div class="col-lg-4"> <a href="{% url 'productDetail' Product.name %}"><img class="thumbnail" src="{{product.imageURL}}"></a> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <h4 style="display: inline-block; float: right"><strong>Rs {{product.price}}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} -
Error 0 connecting to localhost:6379. Error
Got strange redis error Error 0 connecting to localhost:6379. Error. It comes time to time but it's not permanent or reproduceable. I'm using redis-server v3.0.6 and redis==3.5.3, channels_redis==2.4.2 python packages for client connection alongside with django framework. -
Django login state isn't saving
I'm using Django and React to create a login page. When the user clicks on the submit button, I send an Axios POST request to my Django server to authenticate and login. In the login function, printing request.user works as intended. But as soon as the scope of the function is left, printing request.user prints AnonymousUser. I've talked to some people about it and they seem to think it's because cookies aren't persisting, but we haven't been able to solve the problem. Any guidance would be appreciated. // REACT FORM function submitHandler(event) { event.preventDefault(); const state = login ? "login" : "signup"; axios .post(`http://localhost:8000/auth/${state}`, { username: username, password: password, }) .then((response) => { setRedirectMessage(response.data); axios .post("http://localhost:8000/auth/user") }) .catch((err) => alert(err.response.data)); } # LOGIN REQUEST (/auth/login) @require_POST @csrf_exempt def auth_login(request): if request.user.is_authenticated: return HttpResponseBadRequest("You are already logged in") username, password = get_credentials(request) user = authenticate(username=username, password=password) if user is None: return HttpResponseBadRequest("Those credentials do not exist") login(request, user) print(user) # PRINTS CORRECTLY print(request.user) # PRINTS CORRECTLY return HttpResponse("You have successfully logged in with username " + username) # GET REQUEST TO CHECK LOGIN STATE (auth/user) @csrf_exempt def get_user(request): print(request.user) return HttpResponse("Hey there") -
How to connect to a signal while some method calls?
For example I have the model below. class MyModel(models.Model): ........ def some_method(self): .... At some point I will call this method somewhere in the view. Whenever this method gets called I want to call a django signal. How can I do this ? -
save() prohibited to prevent data loss due to unsaved related object 'student'?
There is m2m relationship models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) students = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py: class CreateStudent(LoginRequiredMixin, CreateView): login_url = '/admin/' redirect_field_name = 'index' template_name = 'app/create_student.html' model = Student fields = ('name',) def form_valid(self, form): self.object = form.save(commit=False) for student in form.cleaned_data['name']: connect = Connect() connect.student = self.object connect.course__name = 'math' connect.save() return super(ModelFormMixin, self).form_valid(form) how to do what when creating a Student instance the default value was automatically added Course instance And how create in view method to define default Group p r -
Accessing a cookie set in template using document.cookie in a django View
I'm trying to use a cookie to store an integer value which will then be used to determine the range of data to be displayed on the next page. I am currently using the function document.cookie="name=tom" I've checked my browser storage and the cookie is stored there. And trying to access the cookie via a django view using request.COOKIES['name'] which is unsuccessful. I'm new to django so any info on why this doesn't work and best practice ways of managing variables between js and Python would be really helpful. Thanks! -
Django - TypeError - quote_from_bytes() expected bytes
I'm getting started with Django. I created a Create View for one of my models and got this Error message. I had the following output on my Django-server-website: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/create/ Django Version: 2.0.7 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'pages', 'blog'] Installed Middleware: ['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'] Traceback: File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in post 172. return super().post(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in post 142. return self.form_valid(form) File "/home/mau/Dev/tryDjango/src/blog/views.py" in form_valid 23. return super().form_valid(form) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in form_valid 126. return super().form_valid(form) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in form_valid 57. return HttpResponseRedirect(self.get_success_url()) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/http/response.py" in init 407. self['Location'] = iri_to_uri(redirect_to) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/utils/encoding.py" in iri_to_uri 151. return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "/usr/lib/python3.8/urllib/parse.py" in quote 839. return quote_from_bytes(string, safe) File "/usr/lib/python3.8/urllib/parse.py" in quote_from_bytes 864. raise TypeError("quote_from_bytes() expected bytes") Exception Type: TypeError at /blog/create/ Exception Value: quote_from_bytes() expected bytes Can anyone tell me what is wrong? -
Check permissions for serialized child objects using Guardian
I have three models where one Document has many Blocks and one Block has many Comments. class Document(models.Model): name = models.Charfield() class Block(models.Model): document = models.ForeignKey(to=Document) class Comment block = models.ForgeinKey(to=Block) Users can have permissions for Document which allows them to see all Blocks in it. Users can also add Comments to any Block which they can share if other users. I use django-guardian to manage object-based permissions. I have created a RetrieveAPIView using Django Rest Framework to make the Document available. class DocumentDetailView(PermissionRequiredMixin, RetrieveAPIView): serializer_class = DocumentSerializer permission_required = "document.view_document" To include all blocks and their comments in that view, I use the following serializers (omitted class Meta for brevity): class DocumentSerializer(serializers.ModelSerializer): blocks = BlockSerializer(many=True, source="block_set") class BlockSerializer(serializers.ModelSerializer): comments = serializers.CommentSerializer(many=True, source="comment_set") class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment I would like to restrict the comments included in DocumentDetailView to those to which a user has permissions. Following the logic of django-guardian I would use get_objects_for_users(), to filter down the QuerySet of Block.comment_set.all(). Yet, I don't know where to do this. I guess to restrict the comments to those available to request.user, the permission-based filtering should be done in the DocumentDetailView, but I don't see how to do this … -
Webkit Scrollbar CSS not Changing
I have this django html file, and when adding inline style I see no changes for the scroll bar. I've also tried creating a separate stylesheet, and that still does not override the scrollbar. {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <link href="{% static 'navbar.css' %}", rel="stylesheet" type="text/css"> <link href="{% static 'style.css' %}", rel="stylesheet" type="text/css"> <title>{% block title %}Base Default Title{% endblock %}</title> </head> <style> body { color: black; background-color: white; margin: 0; padding: 0; } body::-webkit-scrollbar-thumb { background: red; } body::-webkit-scrollbar-track { background: black; } body main { margin-left: 5rem; padding: 1rem; } </style> <body> {% include 'website/includes/navbar.html' %} {% block content %} {% endblock %} </body> </html> Any help and thorough explanation to understand this concept is greatly appreciated. -
How to create m2m dependencies?
How to do when creating a Student instance in the database, a relationship will be created between the Student instance and a number of instances of the Course model: -Every instantiated Student model must have a default relationship to some Course instances -User cannot manually visit other parts of the site to add a new relationship between Student and Course. models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) student = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py: class CreateStudent(LoginRequiredMixin, CreateView): login_url = '/admin/' redirect_field_name = 'index' template_name = 'app/create_student.html' model = Student fields = ('name',) -
HTML not loading CSS in Django
I have a problem that my HTML code does not load my css files. The code works if put into the main.html tag, however as outsourced to the separate css files, not working at all. The overall structure of the folder: The head tag of main.html: <head> <title>ToDoList App</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> --> <link id="sheet-theme" rel="stylesheet" type="text/css" href="light.css"> <!-- Nunito Font --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@200&display=swap" rel="stylesheet"> </head> In my django project, the rest of HTML files extend the main.html file, for example the register view: {% extends 'base/main.html' %} {% block content %} <div class="header-bar"> <h1>Register</h1> </div> <div class="card-body"> <form method="POST"> {% csrf_token %} {{form.as_p}} <input style="margin-top: 16px" class="button" type="submit" value="Register"> </form> <p>Already have an account? <a id="plain" href="{% url 'login' %}">Login</a></p> </div> {% endblock content %} What might be the problem? -
Django SyntaxError
Currently working on an exercise from PythonCrashCourse2ndEd. (Ch.18, Ex.8), and i'm getting a SyntaxError: Invalid syntax on urls.py. (line 13 path('pizza/', views.index, name='pizza), I have tried importing the file directly to shell, and it gave me the same error. urls.py """Defines URL patterns for pizzas""" from django.urls import path from . import views app_name = 'pizzas' urlpatterns = [ #Home page path('', views.index, name='index') #Page that shows all the pizzas. path('pizza/', views.index, name='pizza') views.py from django.shortcuts import render from .models import Pizza def index(request): """The home page for pizzas.""" return render(request, 'pizzas/index.html') def pizza(request): """Show all the pizzas""" pizzas = Pizza.objects.all() context = {'pizzas': pizzas} return render(request, 'pizzas/pizzas.html', context) pizzas.html <!--Inherits from base.html--> {% extends "pizzas/base.html" %} {% block content %} <p>Pizzas</p> <ul> {% for pizza in pizzas %} <li>{{ pizza }}</li> {% empty %} <li>No pizzas have been added yet.</li> {% endfor %} </ul> {% endblock content %} Error >>> import pizzas.urls Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Heyale\OneDrive\Desktop\pizzeria\pizzas\urls.py", line 13 path('pizza/', views.index, name='pizza') -
Is there a way to login in django rest api in browser without UI?
I'm doing backend project in which I need to do an API without any UI. In this API there's no registration (only by admin UI), but I need a way to log in, because I need some "pages" to be only for logged in users. I set up token authentication, each user has their token created. Is there a simple way to make some login "form" with serializer? I mean "page" in which there is only two fields (for username and password) and ability to POST this to get authenticated and then go back to "login only pages"? -
Django Rest Framework - get related FK object for use in template; POST not working now?
I've got a form up and working with a Vue frontend and DRF backend. It's a form for adding (creating) a new model - and has a dropdown of the related models that are FK to the model being created. I need to access attributes of the selected FK item. My serializers look like this: class SubdomainSerializer(serializers.ModelSerializer): class Meta: model = Subdomain fields = [ "id", "domain", "short_description", "long_description", "character_code", ] # def get_absolute_url(self, obj): # return obj.get_absolute_url() class EvidenceSerializer(serializers.ModelSerializer): created_by = serializers.HiddenField( default=serializers.CurrentUserDefault() ) updated_by = serializers.HiddenField( default=serializers.CurrentUserDefault() ) absolute_url = serializers.SerializerMethodField() created_by_name = serializers.SerializerMethodField() updated_by_name = serializers.SerializerMethodField() class Meta: model = Evidence fields = "__all__" The form is to create a new 'Evidence' item, and the 'Subdomain' is a dropdown on the form that contains all related subdomains. The models look like this: class Subdomain(CreateUpdateMixin): domain = models.ForeignKey(Domain, on_delete=models.PROTECT) short_description = models.CharField(max_length=100) long_description = models.CharField(max_length=250) character_code = models.CharField(max_length=5) class Evidence(CreateUpdateMixin, CreateUpdateUserMixin, SoftDeletionModel): subdomain = models.ForeignKey(Subdomain, on_delete=models.PROTECT) evaluation = models.ForeignKey( Evaluation, related_name="evidences", on_delete=models.PROTECT ) published = models.BooleanField(default=False) comments = models.CharField(max_length=500) In my form, I just want to include the short_description of each subdomain when the user chooses it from the dropdown - I may also want to use the … -
bulk_create using ListCreateAPIView and ListSerializer
What is the difference between the above two methods? I don't understand how they work, I did try googling, documentation, StackOverflow, medium articles but I don't understand the working. Does ListCreateAPIView hit the create method as the length of the list? How to override that? ListSerializer, I don't get this at all. So I gotta have a parent list serializer and child model serializer. Where do I add the validations in each of these methods? And what if I want to override the fields or save extra information. Basically, I am trying to create an API endpoint for bulk-creating users. That means apart from just the validations, I need to set the password for each user being created in the backend. How do I save it that way? When I tried using the ListCreateAPIView, it kept throwing me the error ListSerializer is not iterable even after I set many = True. Does ListCreateAPI works with just the model serializer or do I need to set the class to a ListSerializer class? And, when I followed this medium article on bulk creating using ListSerializer, it kept telling me something like "JSON parse error - Expecting ',' delimiter: line 4 column 20 … -
django-tenats for django rest framework. How to manage SasS app
I am thinking about using django-tenants for my SaaS application. I ran some tests and all looks great, I can see data isolation on postgres schemas. The problem now is how to delivery it to customers ? I mean, I wanted a web ecommerce application where user can buy this digital product ( SaaS ) and access it. The problems I am facing are: 1- URL of each tenant is going to be different. And I don't want the user to have to type something like tenant1.example.com / tenant2.example.com . I want the same URL. 2- I am going to use rest framework because there's going to be also a mobile app for each tenant. So how the mobile will know each tenant URL to authenticate using the rest api ? Thank you -
reading params in celery and perform a task on it
hi I am stuck with this situation that: a lot of data in a request params are comming and know that it can not serialize too but also these params data are too much and I need theme directly (it has models filter and order inside) if there is any way to separate params and sending theme as a data it would be grate also can not use pip lib too if you know a way to send request to celery in a way just make me happy thanks -
Could not find a version that satisfies the requirement django-iedge==0.1 (from versions: none)
ERROR: Could not find a version that satisfies the requirement django-iedge==0.1 (from versions: none) ERROR: No matching distribution found for django-iedge==0.1 The command '/bin/sh -c /bin/pip3.6 install -r /web/www/requirements.txt' returned a non-zero code: 1 I changed it to django-edge=0.1 still return error -
django Import "weasyprint" could not be resolvedPylancereportMissingImports
hello everyone i have a concern about importing weasyprint. I would like to understand why and what I have to do to solve it. I installed weasyprint import weasyprint