Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
need to get data for choice fields in Django form a loop?
The choice field required in django is in the following format new_choices = ( (1, 'Data 1'), (2, 'Data 2'), (3, 'Data 3'), (4, 'Data 4'), (5, 'Data 5'), (6, 'Data 6'), (7, 'Data 7'), ) I am trying to get the data from db but the data is not getting properly CHOICES = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1) test =([('(' + str(p.head) + '-' + p.detail + ')') for p in CHOICES]) len_of_test = len(test) new_choices =[] for n in range(len_of_test): new_choices = '(' + str(n) + "," + test[n] + ')' The output I am getting from the above code is new_choices = ['(0,(Data 0))','(1,(Data 1))','(2,(Data 2))',...] -
Compile twice in django_tex
I need to compile a .tex file twice with django_tex in order for the table of contents to load correctly. Is there a way to tell the interpreter in django_tex to run the compiler twice (I use pdflatex)?? Code: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \begin{document} \tableofcontents \section{Introduction} Introduction text. \section{Second section} Second section text. \end{document} -
if add new blog in database than sent mail to all subscriber to notified current blog in Django
Note: Add new blog only admin panell. model.py class blog(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) blog_id = models.AutoField(primary_key=True) blog_title=models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=500, blank=True) tags = TaggableManager() blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True) blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True) written_by = models.CharField(max_length=200, default='Prymus Brandcom') image_banner= models.ImageField(upload_to='image_banner') medium_thumbnail = models.ImageField(upload_to='medium_thumbnail') content = RichTextField() # RichTextField is used for paragraphs is_authentic=models.BooleanField(default=False) class Meta: # Plurizing the class name explicitly verbose_name_plural = 'blog' def __str__(self): # Dundar Method return self.blog_title def save(self, *args, **kwargs): # Saving Modefied Changes if not self.slug: self.slug = slugify(self.blog_title) #super(blog, self).save(*args, **kwargs) super(blog, self).save(*args, **kwargs) def snippet(self): return self.content[:300] and it's my subscriber table: class subscriber(models.Model): name=models.CharField(max_length=150,default="") email=models.EmailField(max_length=100) def __str__(self): # Dundar Method return self.name Add new blog in blog table than send mail to all registerd user in subscriber table ??? -
Django vs Django Rest framework , security concern
A traditional website using Django over HTPPS vs Same website using Django rest framework and React JS or other platforms to consume the API. Which would be more secure against DDOS,Spoofing,etc like security breaches ? I hope Rest API is on HTTP and its less secure. Does enabling HTTPS on the REST API server make its API Secure ? -
How can updatee manytomanyfield data
i am trying to update manytomany field data in django. Here is my view: def editRolesView(request, role_id, shop_id): shopId = get_object_or_404(Shop, pk=shop_id) roleId = get_object_or_404(Roles, pk=role_id) permissions = Permission.objects.filter( shop=shopId.id, ) if shopId.user == request.user: if request.method == "POST": permissions = request.POST.getlist("permissions") # cnv_pp = ''.join(permissions) roleId.role_title = request.POST.get("role_title") roleId.shop = Shop.objects.get(id=shopId.id) roleId.save() roleId.permissions = roleId.permissions.set(permissions) roleId.save() return HttpResponse("Edited") # roleId.permissions_set.all() args = { "shopId": shopId, "roleId": roleId, "permissions": permissions, } return render(request, "roles/edit-role.html", args) else: return redirect("warning") Here i tried to update manytomanyfield data. Here is my Model class Permission(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) permission_title = models.CharField(max_length=255) class Meta: ordering = ["-id"] def __str__(self): return self.permission_title class Roles(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) role_title = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) class Meta: ordering = ["-id"] def __str__(self): return self.role_title Whenever i try t save the data it says this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. The data is saving but its throwing this error. Is there any way to solve this issue ? Here is my template <form action="" method="POST"> {% csrf_token %} <label>Set Role Title</label></br> <input type="text" name="role_title" value="{{ roleId.role_title }}"><br> {% for p in roleId.permissions.all %} <input … -
How to return to previous version of pip install in django
I have recently downloaded a django project from github, and I downloaded all of the pip install requirements using: pip install -r requirements.txt However, I realised that I did not set a virtual env for this project, so it seems that the pip installs have affect the entire computer. I am now getting an error like below when I try to runserver my other django projects: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration leads.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') Traceback (most recent call last): File "C:\Users\jsooh\projects\Sevenenglish\11-3\manage.py", …