Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apply django authentication for all views
I am trying to implement Django basic authentication for all of the views in my views.py file. Although I can add the authentication code snippet in every view, but it will not be easy to apply this to upcoming views. Is there any way that every view in my views.py will automatically check for the authentication? views.py def mgmt_home(request): ############################################################## # This code is repetitive ############################################################## if request.user.is_anonymous: return redirect("/login") ############################################################## test_name = Test.objects.all()[0].test_name metadata = { "test_name": test_name, } return render(request, "mgmt_home.html", metadata) Is there any way where I can avoid this repetitive code in all of my views? -
I need a text when your login "Your password incorrect"
Can you help me to understand logic : I need when I enter have a message near login form "Your password incorrect" "Your login incorrect. I have a base registration form with this messages: class RegistrationForm(auth_forms.UserCreationForm): """ A form that creates a user """ error_messages = { 'password_mismatch': 'Password mismatch.', } password1 = forms.CharField( label='Password', strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}) ) password2 = forms.CharField( label='Access password', widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False ) I think to write the same for login : Class AuthForm(AuthenticationForm): error_messages = { 'password_mismatch': ("Password mismatch" ), 'invalid_login': ("Invalid login"), } But I think it is not correct. my views.py this: class BaseRegistrationView(ActivationEmailMixin, generic.FormView): form_class = RegistrationForm @transaction.atomic def form_valid(self, form): self.new_user = form.save(commit=True) self.new_user = authenticate( username=form.cleaned_data['email'], password=form.cleaned_data['password1'], ) login(self.request, self.new_user) self.send_activation_email() return super().form_valid(form) # new class BaseLoginView(LoginView): authentication_form = AuthForm And html in templates: {% if field.is_hidden %} {% render_field field %} {% else %} <div class="form-group"> <label class="form-group__label"> {{ field.label }} {% if field.field.required %}* {% endif %} </label> {% if field.field.widget.input_type == 'checkbox' %} {% render_field field class="form-group__control" %} {% else %} {% render_field field class="input form-group__control" %} {% endif %} {% if field.errors %} {% for error in field.errors %} <div class="form-group__error"> {{ error }} </div> … -
Show error for django unique_together in CreateView form
I'm using Django CBV CreateView and have a unique_together setting on the model class Meta: unique_together = ('field1', 'field2',) When the user adds a non-unique new record, it triggers an error at the database level, which is a 500 error. I'd like to instead just explain to the user that their entry was a duplicate and to add something else. Any idea for an easy way to do this with CBV and the unique_together setting (or a validator)? I'd like to keep this at the model level so the unique check happens regardless if the user creates, edits, or if an admin does it in the Django admin. Thank you! -
Django client.cookies is empty, but when visiting the url there is clearly a CSRF token assigned as a cookie
Django 3.2, python 3.8 I have a function that forces a login so I can grab data from a protected API. Here is the code: def force_client_login(client, base_url): url = urljoin(base_url, '/login/') client.get(url, allow_redirects=False) print(client.cookies) csrftoken = client.cookies['csrftoken'] login_data = { 'username': 'HIDDEN', 'password': 'HIDDEN', 'csrfmiddlewaretoken': csrftoken, } response = client.post(url, data=login_data) For some reason, the client.cookies is printing [] / an empty array. When I visit the URL (which I printed out and verified it is correct), I can clearly see there is a cookie and that it is the CSRF token, I can see this by looking in the browser dev console under networking and looking at the get request. This function worked on a python 3.6 version of the same project I had running on multiple separate machines. Any thoughts? -
Django kills older requests
I am running a Django website over IIS. When a user saves an object it can take some time, so rather than have them wait for it to finish an AJAX request is sent to the server with the submission information and the page is immediately redirected. However, if the server gets many more requests that old saving request is killed rather inelegantly. The log files show that it ends mid execution with no error messages or other indication that it failed. How do I keep older requests alive in Django? P.S. I have already investigated starting a new multithreading Process but encountered issues around Django models, and I am looking for something more simple than Celery. -
Field 'id' expected a number but got <customerlogin: customerlogin object (4)>
I am trying to add customer and salon to their respective tables according to what option is selected by the user.I gave "Customer" and 'Salon owner" in dropdown menu.The name given in dropdown menu is "category". If a user select "Customer" from dropdown menu, registration form details should be added to customerlogin and customerreg tables.Similarly, in the case of "Salon owner".But unfortunately when any of these two option is selected,details were added to both customerlogin table and salonlogin table but not to other two tables. Views.py def register(request): if request.method == 'POST': ufname = request.POST.get('fname') ulname = request.POST.get('lname') uemail = request.POST.get('email') upassword = request.POST.get('password') umobile = request.POST.get('mobile') ucategory = request.POST.get('category') uaddress = request.POST.get('address') if (salonreg.objects.filter(Email=uemail).exists() or customerreg.objects.filter(Email=uemail).exists()): messages.info(request, "Email ID Already Taken") return redirect('register') elif (salonreg.objects.filter(Mobile=umobile).exists() or customerreg.objects.filter(Mobile=umobile).exists()): messages.info(request, "Mobile Number Already Taken") return redirect('register') elif (ucategory=="Customer"): cloginobj = customerlogin() cloginobj.Username = uemail cloginobj.Password = upassword cloginobj.save() cuserreg = customerreg() cuserreg.Login_id_id = cloginobj cuserreg.First_name = ufname cuserreg.Last_name = ulname cuserreg.Email = uemail cuserreg.Password = upassword cuserreg.Mobile = umobile cuserreg.Address = uaddress cuserreg.save() cuserdetail = customerreg.objects.get(Email=uemail) request.session["userid"] = cuserdetail.id return render(request, "profile.html", {'userdetail': userdetail}) else: sloginobj = salonlogin() sloginobj.Username = uemail sloginobj.Password = upassword sloginobj.save() ssalonreg = salonreg() ssalonreg.Login_id = sloginobj.id … -
Django, create form that has copy and paste ability from Excel
As the title states I want create a django from that allows a user to copy and paste data from excel to the form. Right now I just have a very basic form from django import forms from .models import CATEGORIES, Generator class GeneratorForm(forms.ModelForm): class Meta: model = Generator # fields exclude = {'save_id', 'user', 'create_date', 'data_table', 'save_name'} widgets = { 'category': forms.Select(attrs={'class': 'form-check-label', }, choices=CATEGORIES), } And also a very basic html page. <main role="main" class="container"> <div class="d-flex align-items-center p-3 my-3 text-white-50 bg-dark rounded box-shadow"> <div class="lh-100"> <h2 class="mb-0 text-white lh-100">Generator</h2> </div> </div> <div> <form action="" method="post"> <div class="form-check"> {{form.category|as_crispy_field}} </div> <br> <input type="submit" class="btn btn-success text-right" value="Submit"> </form> </div> </main> How would I go about adding another form item/items in my Generator form to be able to take in a 3 column excel table (via copy paste mechanic). Would I need to use js as well to get this done? Apologies in advanced for the minimal amount of code. Kinda new to this Django thing. -
how to convert SQL query to django query?
I have an SQL query but I'm not able to convert it into a Django query. Any help is appreciated! select article_id, count(distinct user_id) as count_of from articles_likes group by article_id -
Django annotate existance in related field
My models: class Character(models.Model): name = models.CharField(max_length=100) class Item(models.Model): name = models.CharField(max_length=100) class Equipment(models.Model): owner = models.ForeignKey(Character, on_delete = models.CASCADE) item = models.ForeignKey(Item, on_delete = models.RESTRICT) And now i need to annotate if items are in equipment: you = Character.objects.get(pk=1) items = Item.objects.all().annotate(ready=Value(True, output_field=models.BooleanField()), filter=Q(equipment__owner__in=you)) but something is wrong : TypeError: 'Character' object is not iterable -
Printing Output from an External Python Script on Django Webpage
I have incorporated an external python script into my Django webpage. I am currently able to display the output of my script in the terminal once a button is clicked, but I want my script to be displayed on my webpage once the button is clicked. The output I want displayed on the webpage from the script is stored in the variable 'res'. This is what I currently have in each file relating to this issue: Views.py def reccomendation_system(request): •external python script for a recommendation system code• return res class IndexPageView(TemplateView): template_name = 'main/index.html' class ChangeLanguageView(TemplateView): template_name = 'main/change_language.html' class MovieReccomdationView(TemplateView): template_name = 'main/recomend.html' def results(request, res): return HttpResponse("Your personalised output:" % res) urls.py path('reccomendation_system/', views.reccomendation_system,name='script'), path('results/', views.results, name='results'), recomend.py <form action="/results"> <button onclick="location.href='{% url 'results' %}'">Output on Webpage</button> {% if data %} {{data | safe}} {% endif %} </form> The error that I am currently getting is: TypeError: results() missing 1 required positional argument: 'res' I am pretty new to Django so I'm not too sure where I am going wrong. The above code is what I seem to have gathered from different tutorials. Any help is appreciated :) thanks -
Adding Abstract Models support to django-rest-framework-mongoengine
In a Django project I am using mongoengine that provides Django style models to MongoDB collections. I am also using django-rest-framework-mongoengine witch extends DRF to support Documents, EmbeddedDocuments, DynamicDocuments and DynamicEmbeddedDocuments the MongoEngine model representation of MongoDB. While Django and DRF allow for using abstract classes in the Models. This is now supported by DRF-mongoengine. However i believe it is possible to add support for abstract Models by writing custom Serializers. So far I was unable to succeed and I would appreciate your help in getting this to work. class Entry(Document) meta = { 'abstract': True, 'allow_inheritance': True, } text = StringField() class Post(Entry) meta = { 'allow_inheritance': True, } class comment(Entry) meta = { 'allow_inheritance': True, } post = ReferenceField(Post) # No Problem serializing this # for the sake of Demonstration, related is a list of posts and comments related = ListField(ReferenceField(Entry)) # This is not supported by DRF-mongoengine class PostSerializer(DocumentSerializer) # Works class Meta: model = Post fields = '__all__' class PostsViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() class CommentSerializer(DocumentSerializer) # Fails class Meta: model = Comment fields = '__all__' class CommentsViewSet(ModelViewSet): serializer_class = CommentSerializer queryset = Comment.objects.all() What I am currently trying to do is to write … -
SonarScanner Error "Line is out of range in the file"
So I'm doing my django project normally, then, out of nowhere I got this error from my SonarScanner when I refactored the function names in formulas.py (and only that, I didn't tweak my sonar.properties nor my ci.yml file): java.lang.IllegalStateException: Line 308 is out of range in the file dietela_quiz/formulas.py (lines: 306) then I decided to add more whitespaces so it reaches 308 lines but ever since then, the error persists, and as I add more whitespaces or even created a dummy function (to increase the length of file legitimately), an error pattern was established like this: java.lang.IllegalStateException: Line n+1 is out of range in the file dietela_quiz/formulas.py (lines: n) where n is the actual number of lines in formulas.py this is my yml file: stages: - test - sonar-scanner - deploy UnitTest: image: python:3.6.5 stage: test before_script: - pip install -r requirements.txt - python manage.py makemigrations - python manage.py migrate - python manage.py collectstatic --no-input - python manage.py runserver 8000 & when: on_success script: - echo "Starting linter..." - sh linter.sh - echo "Starting tests..." - coverage erase - DATABASE_URL=$TEST_DATABASE_URL coverage run --include="./dietela_quiz/*","./nutritionists/*","./dietela_program/*" manage.py test --keepdb - coverage xml -i - coverage report -m artifacts: paths: - coverage.xml SonarScanner: image: … -
Django: Allow data entry into only one of multiple fields of a model
I have a model that needs to be able to store some data. The trouble is, that data may be a number, string, choice or textfield. My models.py looks something like this: class Period(models.Model): """The quarter and the year. May be visualized as the X axis.""" pass class FSLI(models.Model): """Financial statement line items. May be visualized as the Y axis.""" data_type = models.CharField(max_length=20, choices=DATA_TYPE, default='number') class Company(models.Model): """The company to which the data relates. May be visualized as the Z axis.""" pass class FSType(models.Model): """Consolidated or standalone. May be visualized as the report filter.""" pass class Datapoint(models.Model): """A single cell in the above table that points to some data.""" period = models.ForeignKey("Period", on_delete=models.CASCADE, related_name="period_dps") fsli = models.ForeignKey("FSLI", on_delete=models.CASCADE, related_name="fsli_dps") company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="company_dps") fstype = models.ForeignKey("FSType", on_delete=models.CASCADE, related_name="fstype_dps") number = models.FloatField(null=True, blank=True) text = models.CharField(max_length=255, blank=True) choice = models.CharField(max_length=20, choices=DP_CHOICES, blank=True) # Another model will store choices bigtext = models.TextField(max_length=4000) Each Datapoint may contain value only for ONE of number, text, choice or bigtext. The type of data will be determined by the data_type field of the FSLI object. Is there some simple way to ENFORCE this? Maybe by splitting up the Datapoint model into multiple models? -
Django Template Syntax Error - Django Webpack
I'm working on a django webpack bundle. I got a ready template on github. I made a few changes on it. I prepare for future use according to my own file hierarchy. But I am having a problem with template synxtax. First, there is base.html in my project. Thanks to this page, the background of the pages that I will create in the future is formed. Some files were imported in base.html. These are implemented using render_bundle and static tags. I created a new page to be rendered in django. Likewise, I want to import assets/js/table.js and assets/scss/table.scss files on this page separately from other pages. but I am getting a template syntax error. Where do you think I'm making a mistake? i got this error base.html {% load render_bundle from webpack_loader %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block meta %} {% endblock meta %} <title> {% block title %} {% endblock %} </title> <!-- You should added this tags for production files !!! --> {% render_bundle 'app' 'css' %} {% render_bundle 'myapp' 'css' %} <link href="/media/favicon.png" rel=icon> {% block head %} {% endblock %} </head> <body> {% include "navbar.html" %} <!-- Content … -
Django ORM calling the stored procedure in postgresql
I am building a project using Django, I'm thinking What is the best practice on calling the stored procedures in Postgresql using Django ORM? -
Two foreign key fields to one model as an inline in the Admin
I have an artist which has a primary and a secondary contact. I would like to add these two contacts from the Artist admin. But right now both fields are clashing. Any ideas? Thanx in advance. class Contact(models.Model): full_name = models.CharField('Full name', max_length=255) email = models.EmailField() phone = models.CharField('Phonenumber', max_length=255) class Artist(models.Model): name = models.CharField('Name', max_length=255) country = models.CharField(choices=COUNTRIES, max_length=32) contact_1 = models.ForeignKey(Contact, related_name = '+', on_delete=models.CASCADE) contact_2 = models.ForeignKey(Contact, related_name = '+', on_delete=models.CASCADE) class Contactline(admin.TabularInline): model = Contact class ArtistAdmin(admin.ModelAdmin): inlines = [ContactInline] -
hello guys, i have been trying to activate my folder for django but it only kept showing this, can anybody help me
PS C:\users\honnu\onedrive\desktop\yusuf\python\py4e\trydjango> Scripts\activate.ps1 **Scripts\activate.ps1 : The module 'Scripts' could not be loaded. For more information, run 'Import-Module Scripts'. At line:1 char:1 + Scripts\activate.ps1 + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Scripts\activate.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CouldNotAutoLoadModule** -
"<CustomerOrder: admin>" needs to have a value for field "id" before this many-to-many relationship can be used
I want to owerride for my order. But I get an error because it is "ManytoMany" field. views.py: orderform = OrderForm() if request.method == 'POST': orderform = OrderForm(request.POST) if orderform.is_valid() and int(orderform["customer"].value()) == customer[0].id: test = orderform.save(commit=False) orderitems = OrderItem.objects.filter(customer_id=customer[0].id) test.orderitem.add(orderitems ) orderform.save() return redirect('home') models.py class CustomerOrder(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) orderitem = models.ManyToManyField(OrderItem, related_name="orderitem") dealer = models.ForeignKey(Dealer, default=1, on_delete=models.CASCADE) status = models.CharField( max_length=200, choices=WORK_STATUS, default="Waiting", ) pay_method = models.CharField( max_length=2, choices=PAY_METHOD, default=1, ) -
Django - Many to One relationship not working
i am trying to create a relationship between my user model and my article model. Each user can have many articles but each article belongs to one user. When i go to my rest framework and create a user and an article they are not linked together. I think i am missing something in the relationship since when i enter my Article Details i am not entering anything related to the user. MyApp>models.py from django.db import models class User(models.Model): firstname = models.CharField(max_length=255, null=True, blank=False) lastname = models.CharField(max_length=255, null=True, blank=False) email = models.EmailField(null=True, blank=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Article(models.Model): user: models.ForeignKey(User, null=True, blank=False, on_delete=models.SET_NULL) title = models.CharField(max_length=255, null=True, blank=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title MyApp>serializer.py from rest_framework import serializers from .models import User, Article class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id','firstname', 'lastname', 'email'] class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title'] MyApp>views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer -
retrieving a value from nested dictionary API
Im trying to ovveride a POST request from API View and i requested a form like that: { "chp_reference":"522", "income_period":"Weekly", "property_market_rent":"400", "number_of_family_group":"3", "rent_effective_date":"2020-12-4", "state":"NSW", "family_group": [ { "name":"FG_1" }, { "name": "FG_2" } ], "family_member":[ { "name":"FG_1" } ] } FamilyGroup is a child model to Transaction , FamilyMember is also a child for Transaction and FamilyGroup im trying to make a POST request that Include FamilyGroup and Familymember inside Transaction like that: @api_view(['POST', ]) def post_api(request): transaction_data = request.data serializer = TransactionSerializer(data=transaction_data) family_groups = transaction_data["family_group"] family_members = transaction_data["family_group"] fg_ids = [] new_transaction = Transaction.objects.create(chp_reference=transaction_data['chp_reference'], income_period=transaction_data['income_period'], property_market_rent=transaction_data['property_market_rent'], number_of_family_group=transaction_data['number_of_family_group'], rent_effective_date=transaction_data['rent_effective_date'], state=transaction_data['state']) new_transaction.save() for fg in family_groups: c = FamilyGroup(name=fg["name"], transaction=new_transaction ) c.save() for fm in family_members: b = FamilyMember( transaction=new_transaction, family_group=c, name=fm["name"] ) b.save() return Response('Added') but when doing so , im only getting FG_2 , basically it returns me the last name of FamilyGroup and FamilyMember... I would like to return the whole list of names.. would appreciate any suggestion -
Django: template extends. Child template don't find the static image
I'm learning django for a personal project. In this project i create at the first time two app "API" and "Search". Later during the develop i decide to combine search inside API and update the views of "API" with the function that was in the "Search". I create later a base template that render to two different html exstend from the base template.In the first templates (wind_index.html) all the element of the page are perfectly loaded, carousel navbar image etc. when i load in the browser the other templates (search.html), also exstend with the base.html, everything is loaded beside the images of the carousel. Structure of the project: WindPortal API static templates API base.html wind_index.html wind_search.html (here where was my old APP "Search") WindPortal rest of the file setting,urls This is my Setting.py: i set up in APP_DIRS= False for try to don't load anymore file from the old directory but seems not working. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'API', 'templates')], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( 'WindPortal/API/static', 'static/img', ) terminal error: 29/Mar/2021 13:10:17] "GET / HTTP/1.1" 200 3754 [29/Mar/2021 13:10:17] "GET /static/API/style.css … -
How to add bootstrap img-fluid class to images using django-quill-editor
I am working on a blog project with Django using the django-quill-editor. Like the documentation says, I have imported QuillField and added it to my model as shown below. I have also added it to my admin. Now the problem is that whenever i insert an image into the content field of the editor, The image is displayed fully on the details page of the blog. the image is not contained in any div, making it look out of proportion. I realize this is happening because the bootstrap class 'img-fluid' is not applied to the image. I want the image to fit into the text area. So I want know how to customize django quill editor to do this. I can't seem to find it in any documentation for django. models.py from django_quill.fields import QuillField # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='blog_posts') content = QuillField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) banner = models.ImageField(upload_to='banners/', blank=True, null=True, default='/banners/blog-1.jpg') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post, Comment … -
How to pass the correct information to Django modal in templates
So I am able to create a list of all the senders who sent a message to a particular user in Django templates but what I would like to do is that when a user clicks on the view button, A modal should pop up and show what the message is. So for example. If I click on "XYZ sent you a message", I should be able to see what the message is in a pop-up modal. The HTML code I have written sho far: {%for elements in messages %} <ul class="list-group shadow p-3"> <li class="list-group-item"> <img src="{{elements.sender.userprofile.profile_pic.url}}" width="40px" height="40px"> {{elements.sender}} sent you a message </li> <button data-toggle="modal" data-id="{{ elements.pk }}" data-target="#myModal1" class="open-my-modal"> View </button> </ul> {%endfor%} The Modal that should show the message. <div class="modal" id="myModal1"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Ending Survey</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> {{elements.message1}} <h5>here mate</h5> </div> </div> </div> </div> I have tried countless ways. Thank you and Regards -
partial sync of model in django-elasticsearch-dsl
I'd like to do a "partial sync" of model between django and elasticsearch using this library (or any other module for that matter - please suggest). What I mean by "partial sync" is: on the elasticsearch side I have an index with fields _id, FIELD0, field1, field2... on the django side I have a model with fields id(primary key), FIELD0, fieldA, fieldB... I would like to have field0 changes pushed to elasticsearch side whenever it changes on django side. With what I have currently: # in documents.py from django_elasticsearch_dsl import Document as elastic_Doc from django_elasticsearch_dsl import fields from django_elasticsearch_dsl.registries import registry @registry.register_document class elastic_Document(elastic_Doc): class Index: name = 'some_index' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = SomeModel # just one field to the elastic index # this unfortunately removes other fields... fields = ['FIELD0'] the fields that I don't specify to be synced get wiped out on the elasticsearch side. Any suggestion of how this could be achieved would be very appreciated. -
Django JsonField filter by two fields
class Blog: values = JSONField( blank=True, default=list) [ { "id": 1, "value": "31" }, { "id": 2, "value": "Hello" }, ... ] I need to get all objects where the id is 1 and value of that field is greater than 31. I have tried q = queryset.filter(values__0__id=1, values__0__value_gte=31) but it works only for objects if an object that I need located only in first element.