Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination in filtered detailview in Django?
def get_context_data(self, **kwargs): context = super(ProductCategoryView, self).get_context_data(**kwargs) #dropdown menu context['subs'] = ProductSubCategory.objects.filter(category=self.object) #sidebar menu sub_id = self.request.GET.get('sub_id') if sub_id: context['products'] = Product.objects.filter(category=sub_id) else: context['products'] = Product.objects.filter(category__in=context['subs']) return context I have this detailview. First two lines linked eachother and product items filtered by them too. I want to paginate the products only but not the dropdown and sidebar. Limit items with simple paginate_by * is possible? Or create listview with the same function? -
Django: how to edit 4 records at the same time in a table presentation?
I have a new Django project with specific constraints for displaying data to be edited? Until now, I had edit and update forms that 'works' for a specific record. I have a index.html form that display data of my model. Records are group by four records. What is expected, is: to display the same table in a edit/update form but with fields that can be modified have four records to edit prefilled with data of the four last line of the table Bras (based on date) When I valid modification, 4 new records are stored I do not really know how to do... models.py class Bras(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE bra_ide = models.AutoField(primary_key = True) pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) bra_00A_act = models.IntegerField("Arm A activated", default=0, null=True, blank=True) bra_00A_lib = models.CharField("Arm A label", max_length=50, null=True, blank=True) bra_00B_act = models.IntegerField("Arm B activated", default=0, null=True, blank=True) bra_00B_lib = models.CharField("Arm B label", max_length=50, null=True, blank=True) ... bra_log = models.CharField("User login", max_length = 50) bra_dat = models.DateTimeField("Date of settings") log = HistoricalRecords() index.html {% extends 'layouts/base.html' %} {% load … -
Django register url is falling in infinitive loop
So relevant part of urls.py: path('register/', views.register, name="register"), path('login/', views.login_user, name="login_user"), path('logout/', views.logout_user, name="logout_user"), Settings.py: LOGIN_URL="/auth/register/" HTML call: <p><a href="{% url 'auth:register' %}" class="btn btn-success">REGISTER»</a></p> But that url is returninh this: http://127.0.0.1:8000/auth/register/?next=/auth/register/%3Fnext%3D/auth/register/%253Fnext%253D/auth/register/%25253Fnext%25253D/auth/register/%2525253Fnext%2525253D/auth/register/%252525253Fnext%252525253D/auth/register/%25252525253Fnext%25252525253D/auth/register/%2525252525253Fnext%2525252525253D/auth/register/%252525252525253Fnext%252525252525253D/auth/register/%25252525252525253Fnext%25252525252525253D/auth/register/%2525252525252525253Fnext%2525252525252525253D/auth/register/%252525252525252525253Fnext%252525252525252525253D/auth/register/%25252525252525252525253Fnext%25252525252525252525253D/auth/register/%2525252525252525252525253Fnext%2525252525252525252525253D/auth/register/%252525252525252525252525253Fnext%252525252525252525252525253D/auth/register/%25252525252525252525252525253Fnext%25252525252525252525252525253D/auth/register/%2525252525252525252525252525253Fnext%2525252525252525252525252525253D/auth/register/%252525252525252525252525252525253Fnext%252525252525252525252525252525253D/auth/register/%25252525252525252525252525252525253Fnext%25252525252525252525252525252525253D/auth/register/%2525252525252525252525252525252525253Fnext%2525252525252525252525252525252525253D/auth/register/ What am I doing wrong? -
TypeError: 'BasePermissionMetaclass' object is not iterable
I got this problem when i was trying to do an authentication function.Anybody got solution? REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } -
Django system date time lapse
I am preparing a web project using django in python, but I have to make time lapse. If the current date is 22.04.2020, I want to get this date back and forth as I want. how can I do that. In short, how can I get the system date back and forth? -
Sphinx doesn't show docstring
is my first time using sphinx and I'm trying documenting a django project. I created a docs folder and launch the sphinx-quickstart commands. After that I've edited the conf.py adding: import os import sys import django sys.path.append(os.path.abspath('..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'controller.settings' django.setup() Then I've created a modules folder where I've added all the modules of which I want the documentation. For example, the modules for the copycat app is: Copycat =============== Submodules ---------- Admin -------------------- .. automodule:: copycat.admin :members: :undoc-members: :show-inheritance: Apps ------------------- .. automodule:: copycat.apps :members: :undoc-members: :show-inheritance: Forms -------------------- .. automodule:: copycat.forms.py :members: :undoc-members: :show-inheritance: Models --------------------- .. automodule:: copycat.models :members: :undoc-members: :show-inheritance: urls ------------------- .. automodule:: copycat.urls :members: :undoc-members: :show-inheritance: Views -------------------- .. automodule:: copycat.views :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: copycat :members: :undoc-members: :show-inheritance: And, taking as an example the copycat forms file, I've added some docstring: class TransferRequestForm(forms.ModelForm): """ Docstring example """ class Meta: model = TransferRequest fields= ['view_count', 'time_span'] But when I create the documentation I get the right structure but I cannot see anywhere my docstring comment. What am I missing? -
django sites and showing id in admin editor
I'm using the Site module in django. In the admin interface, I see domain name and display name. I'd really like to see the primary key id, as well, however, since I specify the sites by SITE_ID. Now I could do this by editing ./venv/lib/python3.7/site-packages/django/contrib/sites/admin.py, but that's poor form in so many ways. I'd just add "id", thus: class SiteAdmin(admin.ModelAdmin): list_display = ('id', 'domain', 'name') search_fields = ('id', 'domain', 'name') I did the following in one of my models.py files, which helps in the shell but doesn't show up in admin: def site_name(self): return '{domain} ({id})'.format( domain=self.domain, id=self.id) Site.__str__ = site_name Any suggestion how to do this (or pointer on what I'm doing wrong that I think I want it)? -
Inject variables into Model Form CharField
Pretty quick question - Is it possible to inject variables into CharFields "initial" fields in Model forms on Django? I would like to pass the current year and some link the customer fills out in a previous form field (link) and have it populate the "message." subject = forms.CharField( widget=forms.TextInput(attrs={'placeholder': ('Subject')}), initial="Subject", required=False) link = forms.CharField() message = forms.CharField(widget=forms.Textarea, initial="Dear User, today is **datetime.now()** and here is **link**", required=False) -
How to run a python code on django containing script for opening webcam on browser
I want to run a python script on django. My python code is on hand detection, and I am not able to open webcam on web browser and take inputs from it. -
Django rest framework incorrect nested serialization
I started a new django rest framework project and bumped into an annoying problem. The nested serialization doesn't work as expected. Instead of serializing relationship models and returning serialized object it returns an extra "relationship" field in addition to defaul "attributes" json field. Here is my python 3.6 code: models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='User', null=True, blank=True) first_name = models.CharField('First name', max_length=50) last_name = models.CharField('Last name', max_length=50) phone_number = models.CharField('Phone number', max_length=15) activated = models.DateTimeField('Activated') def __str__(self): return f'<Profile {self.first_name.title()} {self.last_name.title()}>' serializers.py from rest_framework import serializers from .models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('id', 'first_name', 'last_name', 'phone_number') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('id', 'email', 'username', 'profile') views.py from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import UserSerializer from .models import Profile class UserViews(APIView): def get(self, request, format=None): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) The answer I expect to get: { "data": [ { "type": "UserViews", "id": "1", "attributes": { "email": "", "username": "admin", "profile": { "id": 1, "first_name": "name1", "last_name": "name2", "phone_number": "+79999999999", } … -
post request and url not working on google app engine django project
I am hosting my blogging app on google app engine in a standard environment. the website deploys successfully. but when I try to go to any other URL like anirudhmalik.in to anirudhmalik/blog/list/ it shows me 500 server error on the server side I am using PostgreSQL instance and the logs message only show me the error projects/anirudhmalik-274008/logs/appengine.googleapis.com%2Frequest_log" but I couldn't get any hint from this message and none of the post requests isworking on the website and everything is working fine in a local server or my local machine you can check the website on anirudhmalik.in and you can also give suggestion is google app engine is good to host your Django project and other cheap college student type hosting service thankyou main.py from annyportfolio.wsgi import application app=application app.yaml file handlers:# This configures Google App Engine to serve the files in the app's static# directory.- - url: /static static_dir: static-storage/ # This handler routes all requests not caught above to your main app. It is# required when static routes are defined, but can be omitted (along with# the entire handlers section) when there are no static files defined. - url: /.* secure: always redirect_http_response_code: 301 script: auto env_variables: DJANGO_SETTINGS_MODULE: annyportfolio.settings … -
How to update templates automatically in Django?
Consider I am having a basic model like this: class Text(models.Model): msg = models.TextField() I'm rendering a template like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <h1>Messages<h2><br> {% for message in messages %} <a> {{forloop.counter}} - {{message}} <br> {% endfor %} </body> </html> With a corresponding views: from django.shortcuts import render from .models import Text def home(request): context = { "messages": Text.objects.all(), } return render(request, 'app/home.html', context) Assuming i am creating new objects of Text through admin page. If I save an object, I want to render it without refreshing the page. I don't have good knowledge on Javascript/jQuery/AJAX, but I'm aware that it is possible to acheive with the help of this. Can anyone guide me through on how to render the contents without refreshing the page? -
DRF how to filter user and product by Foreign key company?
How can I filter by Foreign key(company) to get Only those product which got same company and authorized user? I have these models: models: class User(AbstractBaseUser): first_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) serializer class ProductSerializers(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' view class ProductViewSet(ModelViewSet): serializer_class = ProductSerializers queryset = Product.objects.all() permission_classes = [IsAuthenticated] -
How can I create a search box with drop down filter in Django or python
I just used Django Python about 1 month ago. Can anyone guide me just where can I learn this, Thank you -
Storing a image in Django file-system (without using a database)
index.html <form method="POST" action="."> {% csrf_token %} {{ image_form.as_p }} <input type="submit" name="submit" value="Search via URL"> </form> forms.py class UploadImageForm(forms.Form): image_field = forms.ImageField(required=False) views.py if request.method == 'POST': if request.POST.get('submit') == 'Search via Image': print(request.POST) print(request.FILES) So I want to take the image uploaded by the user and save it in my storage, perform a few operations on it, display it on the webpage and delete it. But I am not being able to go this. In request.POST I'm getting a dict containing the file name, but that's plain text. And while using request.FILES I'm getting, <MultiValueDict: {}> How should I go about this? Thanks, in advance. -
unable to import models: for comment
i'm trying to import comment models but i'm getting error while migrate my code from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image from django.urls import reverse class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=300) image = models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) class Comments(models.Model): Post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') user_id = models.ForeignKey(User,on_delete=models.CASCADE,default=True) comment = models.TextField() commented = models.DateTimeField(default=timezone.now) the error is :- django.db.utils.IntegrityError: The row in table 'userpost_comment' with primary key '1' has an invalid foreign key: userpost_comment.author_id contains a value 'sd' that does not have a co rresponding value in auth_user.id. -
How can we export dict containg list as value in csv file
Suppose this is input format... {'ID':[1,2,3,4,5,6,7,8,9,10], 'Name':['A','B','C','D','E','F','G'], Flag:['True'], City:'', } and i want to export this data as follow in csv file in python ID Name Flag City 1 A True '' 2 B '' 3 c 4 D 5 E and so on...How can we do it ..? Thankx in advance PF:Im getting input formate from django models -
How to implement Django Session Wizard with multiple templates
Im trying to implement a multi step form in django using the form wizard that comes with django-formtools and so far it steps through all the forms till the last one then instead of calling the done method, the page goes back to the first form. Some of my code is shown below: Urls.py from django.urls import path from minereg import views urlpatterns = [ path('',views.ContactWizard.as_view(views.FORMS),name="registration"), ] Views.py from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import RegForm1,RegForm2 FORMS = [("home",RegForm1),("bank",RegForm2)] TEMPLATES = {"home":"home.html", "bank":"bank.html"} class ContactWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self,form_list, **kwargs): #Required form_data = [form.cleaned_data for form in form_list] print(form_data) return render(self.request,template_name = "thanks.html") The print(form_data) in the done method doesn't happen, showing the code never gets to that point. home.html {% extends "base.html" %} {% load widget_tweaks %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="{%url 'registration' %}" method='post'> {% csrf_token %} {{wizard.management_form}} <div class="container col-md-9"> <h1>PERSONAL DETAILS</h1> <p>Please fill in this form to create an account.</p> <hr> <!-- Name --> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.name.label_tag }} {{ wizard.form.name|add_class:"form-control form-control-lg" }} </div> <div class="form-group col-md-4"> {{ wizard.form.middle_name.label_tag }} {{ wizard.form.middle_name|add_class:"form-control form-control-lg" }} … -
Visual studio code doesn't read db.sqlite3 in django framework
I saw a tutorial of django on youtube. That tutorial explain that I must open and write the db.sqlite3 file. Unfortunately Visual Studio Code doesn't read that file. Can anyone help me? -
How Do I Create A Socail Media App With Python?
Hello Guys I Wanted To Create An Social Media App Which Does Not Mine With User's Data. I Want To Build The App Purely With Python. I Know Kivy, Postgreql, Sockets And Finally Python. Is There Anything Else I Need To Learn To Create An Social Media App? Thanks In Advance. -
MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2
Hi I'm trying to develop an e-commerce website using Django. I have two models and views on separate folders, one is an order model and view, another is the checkout model and view. The order view creates a new order everytime an item is added to the cart. And the checkout view creates a new billing address. I want to associate the billing address that is created to the order when the checkout form is submitted. But for some reason, it's not happening. It throws an error: MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2! What is the problem? My orders.models.py: from django.db import models from shopping_cart.models import Cart from django.contrib.auth import get_user_model from accounts2.models import BillingAddress STATUS_CHOICES = ( ("Started", "Started"), ("Abandoned", "Abandoned"), ("Finished", "Finished"), ) User = get_user_model() class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) order_id = models.CharField(max_length=120, default='ABC', unique=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started") sub_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) tax_total = models.DecimalField(default=0.00, max_digits=1000, decimal_places=2) final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) billing_address = models.ForeignKey(BillingAddress, on_delete=models.SET_NULL, blank= True, null=True) My orders.views.py: @login_required def order(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return … -
Best approach to multiple user types in django
I have the need for multiple user types in my application, each with different type specific information, and potentially different FK associations to other entities. In my research on the topic I've seen the recommended approach in the documentation is to create a OneToOne related user profile model to the user here. I've also seen this approach suggested in this example and this question. Let's say for the sake of an example: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_number = models.CharField() class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) department = models.ForeignKey(Department) class Course(models.Model): convenor = models.ForeignKey(Teacher) students = models.ManyToManyField(Student) Contrary to the above examples, I've found only one example recommending the use of subclassing of the User model, here. For the above context this would instead be class User(AbstractUser): pass class Student(User): student_number = models.CharField() class Teacher(User): department = models.ForeignKey(Department) This seems to me to be the much more intuitive and less verbose implementation of the same thing. Is a subclass of a model not just a OneToOne association to the parent model? However in the above stack overflow selected answer this approach is specifically advised against, saying it will lead to problems later. How? I … -
Is it a problem to have two or more exactly same class name at different files?
For my django application, I created class based views and each of them is defined at different file: # foo.py from django.views import View ... class MyView(View): def get(...): foo() # bar.py from django.views import View ... class MyView(View): def get(...): bar() Actually, it is not necessary to have same class names because the views (the web pages) does not have the same content. They have different content created by foo() and bar(). What I want to ask is that is having the same class names at different files is contrary to Object-Oriented Programming (OOP) concepts? Any explanation is appreciated. -
.core problem. just want to do simple login app?
using VSCode i am trying to create a basic signin login app. I change to my Python 3.9 env the "no module named" **.core problem seems to be solved but its really because "couldn't import django" problem. I tried my python 3.7 venv but then "couldn't import django". -
Cloud ndb middleware for django Notimplemented error. How can I solve it?
I using django==2.2 and python==3.7. I install latest google-cloud-ndb library using pip. I added the middleware 'google.cloud.ndb.django_middleware.NdbDjangoMiddleware' in the middleware list inside settings.py file. When I try to run runserver command it gives me following error File "S:\Python\Python37\lib\site-packages\google\cloud\ndb\django_middleware.py", line 23, in __init__ raise NotImplementedError NotImplementedError