Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling values from formA to formB in Django
I am new to Django and I am stuck at a certain problem which I believe to be not that complicated or even simple for some. Here it goes: In views.py, I have declared two methods/function namely, formA and formB, now I wanted to get a variable "username" in formA and automatically place it in the first cell in formB. How can I achieve this, here is the part of that code. By the way, everything is working for now, all I wanted is to pull that particular data. def formA(request): #form A is the User model built-in in Django if request.method == "POST": form_A = myFormA(request.POST) if form_A.is_valid(): form_A.save() else: form_A = myFormA() return render(....) def formB(request): #formB is a custom form that I made. if request.method == "POST": form_B = myFormB(request.POST) if form_B.is_valid(): form_B.save() else: form_B = myFormB(form_B = myFormB(initial={'username':request.user.username})) # this is the part where I am having problems with. return render(....) -
Django path converters not working as expected:
this is my url: URL: https://aws.s3.temp.com/st123/1321******12333123 And this is my path: path('pdf/viewer/<path:path>/', pdf.viewer, name="viewer"), This is my view: def viewer(request, path): context = {'path':path} return render(request, 'pdf_viewer.html', context) When i try to pass a url via this, am getting a wired result. Thus when i pass a url, its trimming up the forward slashes into one. OUTPUT: https:/aws.s3.temp.com/st123/1321******12333123 // check the https doesn't have two slashes But the expected output is https://aws.s3.temp.com/st123/1321******12333123 Why one single forward slash is getting removed ? And this happens only in production server but working correctly in localhost. Please help -
Celery task will not execute in django
I am leraning Django using django 3 by example. I want to launch asynchronous task with celery. I set the settings but the task will not execute. i'm using rabbit mq as broker and i'm using windows. Here is my code: celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Onlineshop.settings') app = Celery('Onlineshop') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): """Task to send an e-mail notification when order is successfully created.""" order = Order.objects.get(id=order_id) subject = f'Order nr. {order.id}' message = f'Dear {order.first_name},\n\n' \ f' You have successfully placed an order.' \ f'Your order ID is {order.id}' mail_sent = send_mail(subject, message, 'admin@onlineshop.com', [order.email]) return mail_sent views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart from .tasks import order_created # Create your views here. @login_required def order_create(request): cart = Cart(request) if request.method == 'POST': user = request.user form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) order.user = user order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], … -
How to use google drive api in django for authentication and file storage?
How can I use google drive api as authentication as well file storage in django? I want to save files that they upload to their own google drive -
'AnonymousUser' object has no attribute '_meta' in Django
I am writing a website and when the user logs in, I get this error - 'AnonymousUser' object has no attribute '_meta'. How do I fix it? Here is a structure of my project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates … -
NOT NULL constraint failed: reg_scientificinfo.user_id
Im trying to make a detailview that lets staff users update regulare users information. this is my models: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES) and views: class ScientificInfoView(FormMixin, DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' form_class = ScientificInfoForm def get_success_url(self): return reverse('scientific-info', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(ScientificInfoView, self).get_context_data(**kwargs) context['form'] = ScientificInfoForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form, *args, **kwargs): form.save() return super(ScientificInfoView, self).form_valid(form) but when I try to submit the form it gives me this error: NOT NULL constraint failed: reg_scientificinfo.user_id -
Django Ignoring updates to urls.py
the urls.py file In My Dango Project Is being Ignored, For Exampe I Tried Commenting Out The Admin Urls From the Project And I Could Still Use The Admin. I tried Adding A Name Space And Django Says It Doesn't Exist. mysite/urls.py: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include("Wallet.urls"), path('',include("django.contrib.auth.urls")) ] + static(settings.STATIC_URL, document_root='/home/dh_hemuuv/minicoin.fztl.com/static') Wallet/urls.py: from django.urls import path from .views import signup,viewWallet,transfer,userpage,collectgift urlpatterns = [ path("signup/",signup,name="signup"), path("",viewWallet,name="home"), path("transfer/",transfer,name="transfer"), path("account/<str:username>/",userpage), path("collectgift/<int:id>/",collectgift,name="colgift"), ] Please Help! -
Django path.url with aws s3 gives "https:/" instead of "https://". How to manage this?
I have intergrated pdf js with my django webiste. And by using that, i am using aws s3 as storage. When user uplaod a document and click on a view document button. I am passing the aws url to the pdf js and then it loads. this is the total flow. Everything worked in localhost, but when i switched to pythonanywhere i noticed that the pdf is not opening. And when i checked the source code, i found that the url is coming as "https:/aws.com/a***********"** and actually it should come as "https://" with double slash. I couldnt find the exact mistake. Please help, check the pic with actual path See the https:/ starts with single slash -
Django - Return attribute in response if current logged in user is following queried user
So I have this view that queries for a User via their uuid. Whenever a request is made it must be accompanied by a access token that allows me to know who the current user is. Below I have an endpoint that returns all the queried users info including how many followers they have or number people they are following. I want to be able to return an attribute that determines whether the current user which is pulled from request.user is following the queried user with user uuid user_uuid. I tried the is_following=Count('followee_id', filter=Q(follower_id=str(request.user.uuid)))), but this doesn't seem to be returning the correct value as I have tests that check to see if this is true when it is set in the test database and they are failing. How do I annotated my query to include if the current user is following the user with user_uuid? view.py @api_view(['GET']) def get_user_info(request, user_uuid): query = User.objects.filter(pk=user_uuid) if query.exists(): query_annotated = query.annotate( follower_count=Count('followee_id', distinct=True), followee_count=Count('follower_id', distinct=True), is_following=Count('followee_id', filter=Q(follower_id=str(request.user.uuid)))) else: return Response(dict(error=str('User not found.'), user_message='User not found.'), status=status.HTTP_404_NOT_FOUND) serializer = FullUserSerializer(query_annotated[0]) return Response(serializer.data, status=status.HTTP_200_OK) serializer.py from rest_framework import serializers from cheers.models import User class FullUserSerializer(serializers.ModelSerializer): follower_count = serializers.IntegerField() followee_count = serializers.IntegerField() is_following = serializers.BooleanField() … -
how to edit user info inside a custom admin page
Im a rookie python developer and Im trying to add a feature to my app that allows staff users change some information about regular users. the field that are going to be edited are these: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES) I created a dashboard for the admin which displays usernames and by hitting their name it redirects to the detail view of that user. this is the views I wrote for the detail page: class ScientificInfoView(DetailView): model = ScientificInfo template_name = 'reg/scientific-info.html' def edit_form(self, request, user_id): user = get_object_or_404(ScientificInfo, pk=user_id) if request.method == 'POST': form = ScientificInfoForm(request.post, instance=user) if form.is_valid(): form.save() redirect('scientific-info') else: form = ScientificInfoForm(instance=user) return render(request, 'reg/scientific-info.html', {'form': form}) However when inside the detailview, the form is not displayed. only the submit button is visible and when I click it I get a 504 error! for now the template is as simple as this: {{object.info1}} {{object.info2}} {{object.info3}} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> and finally this is my form: class ScientificInfoForm(forms.ModelForm): class Meta: model = ScientificInfo fields = ['info1', 'info2', 'info3'] what am I doing wrong? and is … -
Aggregate values with foreignkey field
I have model property where I sum foreign key field product_price and model field spend: @property def price_total(self): queryset = self.product.all().aggregate( total_price=models.Sum('price')) return queryset["total_price"] or 0 + self.spend Thats work good, but i need change filter query: @property def total_purchases(self): qs = super(PurchasesFilter, self).qs return qs.filter(regular='False', paid='True').aggregate(total_price=Sum(F('spend') + F('product__price')))['total_price'] This query only adds spend if a product price is added and duplicates value of spend for each product added. I need a query that always sum all the spends and adds the prices of the products, only if are added to the spend. And the value of the spend will not duplicate with each added product. -
How to give permission to AnnonymousUser to get room data using a passkey with django resr framework
I'm new to django and i'm trying to create an app with rooms that can only be created by a user, but anyone can "login" into a room with room Id and a passkey. the thing is, I don't know how to approch this, I read something about overriding AnonymousUser but, since I'm using simplejwt to authenticate a User, I thought maybe it will be better to create json token with room id and passkey instead of username and password, and then let anyone with this token acsses the room... But I dont know how to do it and I would like to get some pointers to what I should do or look up, since I havn't been able to find anything about it myself. -
with the help of django, what are the steps to show data in the website from Apache Solr?
Here I need to show the TEXT and URL in the website from apache solr. what will be the query or ORM? -
Django URL not mapping even there is no error why?
django startproject folder (URLS.PY):- from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('sub.urls')), ] django startapp folder (URLS.PY):- from django.urls import path from . import views urlpatterns = [ path('', views.home, name= 'home'), ] django startapp folder (VIEWS.PY):- from django.http import HttpResponse def home(request): return HttpResponse("hello world") -
How can i do multiple values filter for multiple fields in Django?
for loc,deg,dept,key,job_role,insti_loc,insti_name,mark,gen,job_type in zip(lst2,lst5,lst6,lst1,lst4,lst8,lst9,lst10,lst11,lst12): if sample_register.objects.filter(city=loc,job_role_1=job_role,qualification=deg,qualification_dept=dept).exists(): print("Inside location and jobrole1 and qualification and department search") for i,j,k,l in zip(lst5,lst2,lst6,lst4): pro_log=sample_register.objects.filter(Q(city=j) & Q(job_role_1=l) & Q(qualification=i) & Q(qualification_dept=k)) -
Django -Display a list of post's categories with a number of post
Hi i am trying to make a template in django that displays a post categories table and has a number of posts with it. I can't seem to make it right using annotate when making queries on my model. like this views.py categorylistcount = Post.objects.all().annotate(posts_count=Count('category')) for obj in categorylistcount: print(obj.category + ' : ' + obj.categories_count) #test im receiving list of posts instead and has a posts_count key with value of 1 models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) body = models.TextField() category = models.CharField(max_length=64, default="Uncategorized") date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('blog:post-detail', kwargs={"pk": self.pk}) class Category(models.Model): name = models.CharField(max_length=225) def __str__(self): return self.name where did i miss? thanks -
Set default "This month" choice and date in DateRangeFilter
Now all catalog items are displayed, I would need the default filter to be set to display only items from the current month. In forms I have: date_paid_range = DateRangeFilter(field_name='paid_date') date_range = DateFromToRangeFilter(field_name='paid_date', label='From-To', widget=RangeWidget(attrs={'type': 'date'})) -
Is there anyway to create related entites within a post request with django rest framwork?
If I sound confused, it's because I am. I'm unfamiliar with the django rest framework and I'm attempting to create a relatively simple Recipe-Managing app that allows you to automatically create your shopping list. Motivations : I know that DRF might not be needed and I could just use django, but the point of this app is to learn how to use the DRF. The goal is to create a back with DRF and do some fancy shenanigans with a front framework afterward. Problem: I have a Recipe model which contains a ManyToMany field to Ingredient through RecipeIngredient. And I am a bit confused on how I should approach the RecipeSerializer. So far it looks like that : class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ('id','name','ingredients','tags','prep_time','cook_time', 'servings', 'instructions') But I feel like whenever I will want to create a Recipe, I'll have to fire a post request to create the Ingredients (if they do not exist yet), one to create the Instructions, one to create the Recipe and one to create the RecipeIngredients. Question : Is there a way to make one request containing the recipe and all sub fields (ingredient, recipeingredient, instruction) and to create all the … -
Invalid parameter in django prefetch_related
These are my models: class MemberShip(models.Model): name = models.CharField(max_length=30, blank=False, help_text="Name shouldn't be longer than 30 characters") description = models.TextField(blank=False, null=True) class UserMembership(models.Model): user = models.OneToOneField('accounts.User', on_delete=models.CASCADE) as_member = models.ManyToManyField(MemberShip, related_name='memberships_as_member') as_affiliate = models.ManyToManyField(MemberShip, related_name='memberships_as_affiliate') def __str__(self): return self.user.email I want to get that which user has selected a membership as_member or as_affiliate, I tried following code: user_memberships_all = UserMembership.objects.filter(id=id).prefetch_related("as_member__usermembership_set") but got this error. AttributeError: Cannot find 'usermembership_set' on MemberShip object, 'as_member__usermembership_set' is an invalid parameter to prefetch_related() like in the picture: I want to get user:pradhumnts@gmail.com as_member when I pass Jai Shree Ram Membership. can anyone please tell me what am I doing wrong here? I can make myself more clear if the problem is not clear. Thank You. -
Filtering tags in M2M Field Django
So I have my models Class Category((models.Model) category = models.CharField() class Group(models.Model) Title = models.CharField() category = models.ManyToManyField(Category, related_name= tags) So I want to be able to filter all the groups with similar tags to the group currently in view In my views.py I tried group = Group.objects.get(id=pk) groups = Group.objects.filter(category=group.category) But that doesn't work -
How to display multiple models in one tab in Django admin?
I made the item and quiz apps with the startapp command. I added the apps to INSTALLED_APPS in settings.py, and registered them on the admin page. admin.site.register(Item) admin.site.register(Quiz) In the admin page, Item tab and Quiz tab exist separately, and models can be modified in each tab. I want to combine these two tabs into a tab called 'foo'. How can I solve this? -
TypeError: can't subtract offset Naive and offset-aware datetimes i want to minus two dates and I got this error?
#models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) #views.py from django.shortcuts import render from .models import * from .forms import UserForm def home(request): return render(request, 'home.html') def donor(request): if request.method == "POST": userform = UserForm(request.POST) if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform}) #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import User from datetime import datetime,timedelta class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) existuser = User.objects.get(cnic = cnic) if existuser: print(existuser) previous_date = existuser.last_donation current_date = datetime.now() print(previous_date,current_date) Output:-> Previous:> 2021-12-17 12:38:35.717900+00:00 Current:> 2021-12-18 14:44:23.569193 Here I want to minus these two dates but I Got error this final = Current date - Previous date Last line is not working I want to minus the two dates Both date picked from system automatically -
How to use Substr with an F Expression
I'm trying to build a toolkit of Func classes built on the fuzzystrmatch postgres extension. For instance I have this wrapper which takes in an Expression and a search term and returns the levenshtein distance: class Levenshtein(Func): """This function calculates the Levenshtein distance between two strings:""" template = "%(function)s(%(expressions)s, '%(search_term)s')" function = "levenshtein" def __init__(self, expression, search_term, **extras): super(Levenshtein, self).__init__( expression, search_term=search_term, **extras ) Called like this, using an F Expression: Author.objects.annotate(lev_dist=Levenshtein(F('name'),'JRR Tolkien').filter(lev_dist__lte=2) However if the 'name' field here is greater than 255 it throws an error: Both source and target can be any non-null string, with a maximum of 255 characters. I can truncate the name when I annotate using Substr: Author.objects.annotate(clipped_name=Substr(F('name'),1,250)) But I can't seem to figure out how to place that logic inside the func, which I'm placing inside an ExpressionWrapper and setting the output_field as per the docs: class Levenshtein(Func): """This function calculates the Levenshtein distance between two strings:""" template = "%(function)s(%(expressions)s, '%(search_term)s')" function = "levenshtein" def __init__(self, expression, search_term, **extras): super(Levenshtein, self).__init__( expression=ExpressionWrapper(Substr(expression, 1, 250), output_field=TextField()), search_term=search_term, **extras ) -
How to display a model data dynamically in Html?
I have a model and in a function this model is updating. I want to display this model's data dynamically. So, new values should display without refreshing the page. How can I do it? models.py class MyLongProcess(models.Model): active_uuid = models.UUIDField('Active process', null=True, blank=True) name = models.CharField('Name', max_length=255) current_step = models.IntegerField('Current step', default=0) total = models.IntegerField('Total', default=0) @property def percentage_sending(self): # or it can be computed by filtering elements processed in celery with complete status return int((current_step / total) * 100) views.py def setup_wizard(request): process = MyLongProcess.objects.create(active_uuid=uuid.uuid4(), name=name, total=100) functions.myClass(..., process=process) .... return render(request, 'setup_wizard.html', context) functions.py class myClass(): def __init__(self, ..., process): self.download_all(..., process=process) @app.task(bind=TRUE) def download_all(self, ..., process): .... for s in scans: .... process.current_step += 1 process.save() ... setup_wizard.html <div class="progress-bar" role="progressbar" style="width: {{ my_model_object.percentage_sending }}%;" aria-valuenow="{{ my_model_object.percentage_sending }}" aria-valuemin="0" aria-valuemax="100">{{ my_model_object.percentage_sending }}% </div> All my function works fine. When I looking the MyLongProcess from Django admin and refresh the page, values are updating. Just I want to display it in frontend without refreshing. -
Many parameters with one name in form and get a list of them in
I have a form with dynamic fields.. When submit form, i have this: Localhost:8000/mysite.com/jobs_form?job="Job1"&job="Job2" And i cant get all of them in django with request.POST.get("job") What can i do?