Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enforce or test on_delete behavior of all ForeignKey fields using a specific model
Let's say I have a proxy user model as class UserWithProfile(User): profile_description = models.TextField() class Meta: proxy = True ordering = ('first_name', ) I want to make certain that all data which could in the future be associated with a UserWithProfile entry is deleted when this profile is deleted. In other words I want to guarantee the on_delete behavior of all existing and future ForeignKey fields referencing this model. How would one implement either a test checking this, or raise an error when another on_delete behavior is implemented? I know it would be possible to make a custom ForeignKey class, which is what I will be probably doing, ... class UserWithProfileField(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs.setdefault('to', UserWithProfile) kwargs.setdefault('on_delete', models.CASCADE) super().__init__(*args, **kwargs) ... however that couldn't stop future users from using the ForeignKey class with a different on_delete behavior. -
UNIQUE constraint failed: authtoken_token.user_id while performing login using Django Framework
Getting the below error while trying to login using DRF API** IntegrityError at /api/auth/login UNIQUE constraint failed: authtoken_token.user_id Request Method: POST Request URL: http://127.0.0.1:8000/api/auth/login Django Version: 2.2.16 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: authtoken_token.user_id Exception Location: D:\Django\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: D:\Django\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['D:\\Django\\UserAPI', 'c:\\program files\\python38\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'D:\\Django\\venv', 'D:\\Django\\venv\\lib\\site-packages'] Server time: Tue, 12 Jan 2021 19:12:18 +0000 UNIQUE constraint failed: authtoken_token.user_id while performing login using Django Framework serializer.py from django.contrib.auth import get_user_model from rest_framework.authtoken.models import Token from rest_framework import serializers from django.contrib.auth.models import BaseUserManager,AbstractBaseUser User = get_user_model() class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=8, required=True) password = serializers.CharField(max_length=6,required=True, write_only=True) class AuthUserSerializer(serializers.ModelSerializer): auth_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id','username', 'password', 'email', 'mobileno','auth_token') def get_auth_token(self, obj): token = Token.objects.create(user=obj) return token.key class EmptySerializer(serializers.Serializer): pass class UserRegisterSerializer(serializers.ModelSerializer): """ A user serializer for registering the user """ class Meta: model = User fields = ('id','username', 'password','email','mobileno') def validate_username(self, value): user = User.objects.filter(username='username') if user: raise serializers.ValidationError("Username is already taken") return AbstractBaseUser.normalize_username(value) views.py from django.contrib.auth import get_user_model,logout from django.core.exceptions import ImproperlyConfigured from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import AllowAny from rest_framework.response import Response from .import … -
Django Update Existing ImageField not working
I want to give a user the ability to update the image associated to a record. I have an edit form that allows the user to update various elements of a record all of which are updating correctly except for the image fields. The image field when assigned to the record is displaying so adding the image to the record on creation fo the record works fine. I have reviewed similar Q&As and they have not helped. Models.py class ComicInput(models.Model): CoverPic = models.ImageField(upload_to='Comic_Pics', default='Comic_Pics/default.png',blank=True) def __str__(self): return '%s %s %s' % ( self.CoverPic) def __unicode__(self): return '%s %s %s' % ( self.CoverPic) Forms.py class ComicInputForm(forms.ModelForm): class Meta: model = ComicInput fields = '__all__' Views.Py def edit(request, id): record = ComicInput.objects.get(pk = id) return render(request, 'app/edit.html',{"ComicInput":record}) def update(request, id): updaterecord = ComicInput.objects.get(pk = id) if request.method == "POST": form = editform(request.POST or None, request.FILES or None, instance=updaterecord) if form.is_valid(): edit = form.save(commit=False) edit.save() return ComicInventory(request) else : form = editform(instance=updaterecord) messages.error(request,"Error, please try again taking note of validation rules on the right") return render(request, 'app/edit.html', {'form':form,"ComicInput":updaterecord}) def delete(request, id): deleterecord = ComicInput.objects.get(pk = id) deleterecord.delete() return ComicInventory(request) Urls.py path('edit/<int:id>', views.edit, name='edit'), path('update/<int:id>', views.update, name='update'), path('delete/<int:id>', views.delete, name='delete'), Template - edit.html <!DOCTYPE … -
checking if a certain many to many foreign key is present on django-polymorphic models
So in order to create an object model, I have to first see if a supplier has a relation of type many to many from BusinessModel, WarehouseModel or StoreModel to in a django-polymorphic My main idea is to check if BusinessModel, which is connected to Order through BusinessOrderModel, StoreModel, which is connected to Order through StoreOrderModel or WarehouseModel which is connected directly to Order, have FKs on a many to many relationship going to the article that we want to order through a POST request. class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class OrderModel(models.Model): id = models.AutoField(primary_key=True) order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() class OrderToModel(Porrodriguez@odoogrp.comlymorphicModel): id = models.AutoField(primary_key=True) class WarehouseModel(OrderToModel): warehouse_num = models.IntegerField(unique=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return "Warehouse"+ str(self.warehouse_num) class StoreOrderModel(OrderToModel): reference = models.IntegerField(unique=True) store_num = models.ForeignKey('StoreModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class StoreModel(models.Model): store_num = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return str(self.store_num) class BusinessOrderModel(OrderToModel): reference = models.IntegerField(unique=True) business_num = models.ForeignKey('BusinessModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class BusinessModel(models.Model): Business_num = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return … -
Specify multi-language description tag when using Django i18n
I recently published a webapp made with django, which serves content in both Italian and English. To accomplish that, I used Django's internalization pack, i18n. The content is currently being served according to user's accept-language header, with Italian being served if the user asks for it language in the header, and English being the default for when the header is absent or containing any other language code. In addition to that, I also have the following tags <link rel="alternate" hreflang="it" href="https://mywebsite.com/it/" /> <link rel="alternate" hreflang="en-us" href="https://mywebsite.com/en-us/" /> <link rel="alternate" hreflang="x-default" href="https://mywebsite.com/en-us/" /> Which I accomplished with the following urls.py config: urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(packages=['appname'], domain="django"), name='javascript-catalog'), ) as suggested in the official docs. I would like my website homepage (which is the only publicly accessible page of the website) to have a meta description tag to be shown to Italian users, and one in English. What's the best way to accomplish this with my current configuration, given that ultimately it's a single page that's being served and not one per language? -
How do i create and use variables in django
New to Django and its templates. I'm trying to set a variable given a specific situation, and that part I think ill be able to do, the code below isn't the exact conditions its just there as a demo. The part im stuck on is how do i create a variable name, and then use that name variable elsewhere. Such as within a div or within a method or anywhere else within the html file, and withing different <Script> tags to run methods and for really any purpose. demo scenario : {% for row in table.rows %} {% if row == 2 %} {% var name = row.name %} {% endif %} {% endfor %} {% if name %} <div>{{name}}</div> {% endif %} my actual code Im trying to implement: <script type="text/javascript"> function map_init_basic(map, options) { var markerClusters = L.markerClusterGroup({ chunkedLoading: true }); {% for row in table.rows %} var x = "{{ row.cells.x }}" var y = {{ row.cells.y }} var m = L.marker([y, x]) m.bindPopup("{{row.cells.first_name}} {{row.cells.last_name}} <br>{{row.cells.chgd_add}}"); m.on("click" , ()=>{ //console.log(`${first_name} ${last_name}`) {% var first_name = {{row.cells.first_name}} %} }) //changed row.cells.chgd_add to row.cells.Chgd_add to make sure its matching the table markerClusters.addLayer(m); {% endfor %} markerClusters.addTo(map); } {% if … -
Django correct list using article_id
views.py def article(request, article_id): return render(request, 'article.html', { 'article': Article.objects.get(id=article_id) }) urls.py from . import views urlpatterns = [ path('articles/', views.articles, name='articles'), path('articles/<int:article_id>/', views.article, name='article'), ] article.html <div class="pagination"> <a href="#">&laquo;</a> <a class="active" href="/articles/{{ article.id }}/">1</a> <a href="/articles/{{ article.id }}/">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> <a href="#">6</a> <a href="#">&raquo;</a> </div> Someone can tell me how add to pagination list correct article by correct id and last and end article ID in HTML? Thanks a lot -
Can I get the property of a specific object in a Django template?
I am using django-filters in my project. Let's say I get this address after a search: ?title=my title&ms=8 As you can see, I've searched for 'my title' and for a manuscript which the user sees as 'my manuscript', but whose get parameter (and ID) is 8. Now, I'd like to add to my template a courtesy 'you've searched for' field. How can I show the title of that manuscript, rather than its ID? I already have the ms objects in my view: mstunes = MsTune.objects.all() ms = Manuscript.objects.all() <- manuscripts f = MsTuneFilter(request.GET, queryset=MsTune.objects.all()) return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'f': f, 'request':request, 'ms': ms}) and I can indeed access them with {{ms.all}}. Is it possible to do something, in pseudo code, like: show the ms.title of the ms object with id = request.GET.ms ? -
Auto fill up Django model
I'm building an application that display tests included in a project. User can set the test result of each tests. My model contain 3 basic classes: Requirement - in this class i want to hold every tests. Something like template table. class Requirement(models.Model): requirement_name = models.CharField(max_length=256, default=None) nist = models.CharField(max_length=10, blank=True, null=True, default=None) cwe = models.CharField(max_length=10, blank=True, null=True, default=None) lvl1 = models.BooleanField(default=True) lvl2 = models.BooleanField(default=True) lvl3 = models.BooleanField(default=True) stand2 = models.IntegerField(default=2) stand3 = models.IntegerField(default=2) stand4 = models.IntegerField(default=2) stand5 = models.IntegerField(default=2) stand6 = models.IntegerField(default=2) stand7 = models.IntegerField(default=4) Project - contain all projects created by users class Project(models.Model): project_name = models.CharField(max_length=256, default=None) date_made = models.DateTimeField( auto_now_add=True) owner = models.ForeignKey(User, default=None, on_delete=models.CASCADE) lvl1_project = models.BooleanField(default=True) lvl2_project = models.BooleanField(default=True) lvl3_project = models.BooleanField(default=True) stand2_project = models.BooleanField(default=True) stand3_project = models.BooleanField(default=True) stand4_project = models.IntegerField(default=1) stand5_project = models.IntegerField(default=0) stand6_project = models.IntegerField(default=2) stand7_project = models.IntegerField(default=4) ReqsProject - in this table i want to store all of requirements that are stored in class Requirements class ReqsProject(models.Model): project_id = models.ForeignKey(Project, default=None, on_delete=models.CASCADE) requirement_id = models.ForeignKey(Requirement, default=None, on_delete=models.CASCADE) status = models.BooleanField(default=True) result = models.BooleanField(default=True) How can I automaticly fill up table ReqsProject when user create own Project. This may be something like this: ID Project ID Requirement ID Status Result 1 1 … -
Why isn't the BooleanField changing value in Django models?
I'm working in an Auction website which let the user list an auction and close it afterwards. The auction models has a boolean field called is_closed that stores if the auction is closed or not. When the user clicks a "Close Auction" button, he will be lead to this view that only changes the value of this field (that is false by default) and then saves the changes. def close_auction(request, auction_id): if request.method=="POST": target_auction = Auction.objects.get(id=auction_id) target_auction.is_closed=True target_auction.save() return HttpResponseRedirect(reverse('auction', kwargs={'auction_id':target_auction.id})) However, the field doesn't change, even though I am redirected to a html page that is loaded when the auction is closed successfully. When I go to the admin/ page the is_closed field indeed is unchanged (still marked as false). If what I did here is illegal, why there is no error message? Here is the Auction model: class Auction(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=100, default="") image_url = models.CharField(max_length=100, default="https://elitescreens.com/images/product_album/no_image.png") category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", related_name="auction_category") bid = models.OneToOneField(Bid, on_delete=models.CASCADE, null=True) creation_date = models.CharField(max_length=30, default="-----") owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="") is_closed = models.BooleanField(default=False) Any ideas? -
Django admin actions bar missing? Template expecting "action_form" context variable but mine is showing "action_confirm_form"
As the title says, I'm having an issue that I cant seem to find any reference of anywhere else online. I was working on creating a custom Django admin action that provides and intermediate page for additional request data before updating the selected models. I followed these posts to accomplish this: Displaying an Admin Action Popup and Displaying an Admin Action Confirmation Page. I got everything working and then I went back to add some comments and after the server restarted when detecting changes, the admin action bar completely disappeared (see screenshot below). Another thing to note, my Django project has two separate apps, each with their own admin site and the actions drop-down disappeared from both sites for all model's change list view. Admin Actions Missing When inspecting the context of the admin site using the debug_toolbar I see this: {'action_confirm_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... And when looking at the admin site context of a different clone of the repo with the admin actions working as expected I see this: {'action_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... It appears that the context variable action_form was … -
like button for a blog post in Django
Looked over a few posts on Stack, but don't appear to see an answer. I am trying to get the blog post to send the like button as a notification. I currently have the comments working fine, i can comment on a blog and that will send a notification to the user who wrote the blog. I just cant appear to get the like button to notify. The blog post can be accessed by the title, to show you the post-detail screen of the individual post. On there we have a like button which i would like to be pressed and notify correctly. Thank you, i am a little experienced but still trying to gain a better understanding. Models.py from typing import cast from django.contrib.auth.decorators import user_passes_test from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save, post_delete from notifications.models import Notification class Category (models.Model): named = models.CharField(max_length=100) def __str__(self): return self.named def get_absolute_url(self): return reverse('home') # Create your models here. cat_new_choice = Category.objects.all().values_list('named', 'named') # first BLOG table - TEST this is how you create it! class Post(models.Model): title = models.CharField(max_length=100) … -
Wagtail - How to save a record which uses InlinePanel containing M2M
I have a model which uses an InlinePanel to reference another model (ClubTimetable) which itself contains an M2M relationship to DayOfTheWeek. It seems as though I am unable to save the record because ClubTimetable is not yet saved and cannot create the M2M relationship to DayOfTheWeek, causing the following error: "<ClubTimetables: Club Timetable (str) 18:00:00>" needs to have a value for field "id" before this many-to-many relationship can be used. What can I do to solve this issue? My models look like this # ClubManager @register_snippet class ClubManager(ClusterableModel): name = models.CharField('Club name', max_length=255, help_text='The name of the club.') panels = [ FieldPanel('name'), InlinePanel('club_timetable', heading='Timetable Information') ] # ClubTimetables class ClubTimetables(Orderable, AddressBase): attached_to = ParentalKey( 'club.ClubManager', related_name='club_timetable') weekday = models.ManyToManyField(DaysOfTheWeek) start_time = models.TimeField() end_time = models.TimeField() panels = [ ... ] + AddressBase.panels # DaysOfTheWeek class DaysOfTheWeek(models.Model): weekday = models.CharField(max_length=9) def __str__(self): return self.weekday Visually, it looks like this (Initial) (Adding timetable) -
Missconfigures Django settings, ModuleNotFoundError: No module named 'DeveloperRoad'
I'm making a django blog app and I created a Custom User, modifying the AUTH_USER_MODEL constant in the settings.py file. But the database drop an IntegrityError, so I though it was that the configuration file wasn't being imported, and I did the following command,with virtualenv activated: export DJANGO_SETTINGS_MODULE=DeveloperRoad.settings My project app is named DeveloperRoad and the settings file is settings,so I'm not sure what I'm doing wrong. My project structure is the following: DeveloperRoad ├── blog │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ │ └── blog │ │ ├── add_category.html │ │ ├── add_post.html │ │ ├── author.html │ │ ├── categories.html │ │ ├── categories_list.html │ │ ├── delete_post.html │ │ ├── details.html │ │ ├── edit_post.html │ │ └── index.html │ ├── templatetags │ │ ├── extra_filters.py │ │ ├── __init__.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── DeveloperRode │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── members │ ├── admin.py │ ├── apps.py │ ├── backends.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ … -
preventDefault doesn't always work and the event is executed
I have encountered such a problem that the cancellation event of the form submission does not always work, namely in 30% of cases the event is not cancelled. I send a request by GET method to Django server and get json from it. In 70% of the cases I get the json and my function is already called which handles that json. But in the other 30% I get the json and it is immediately displayed on the screen and I get this text in the console: "content.js:200 JSON Formatter: Type "json" to inspect." Can you please tell me why this happens and how to fix it? let form=document.querySelector('form') form.onsubmit=(e)=>{ e.preventDefault(); setTimeout(()=>{ fetch(form.action, { method: "GET", }) .then(response => response.json()) .then(function(json) { if (json.status){ caseFormation(json) } }) .catch(function(error) { console.log(error) }); },1000) } -
django reathenticate middleware
as a relative noob to django I have been creating a users app. I would like a logged in superuser to have to reauthenticate if they access the admin area having used the rest of the app. I am trying this custom middleware that I have written. Is there a django integrated solution to this problem already, and are there any issues that you can see with my code? from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth import logout import re class ReauthenticateMiddleware: def __init__(self, get_response): self.get_response = get_response self.pages = [] # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_superuser: match = re.match(r'/admin/', request.path) if len(self.pages) and self.pages[-1] is not None and match is not None: referred = re.match(r'/admin/', self.pages[-1]) if referred is None and match is not None: messages.add_message(request, messages.INFO, 'You must reauthenticate') logout(request) self.pages = [] return redirect('/admin/login/') if request.path[-1] == '/': self.pages.append(request.path) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response I have the custom middleware on the python path and have added it to settings … -
'relation "django_site" does not exist' only when running Django tests in GitHub Actions
I have a Django 3.1 project with an Admin class like this really simple example: from django.contrib import admin from .models import Book class BookAdmin(admin.ModelAdmin): def book_title(self, obj): return obj.title admin.site.register(Book, BookAdmin) And I test that class: from django.contrib.admin.sites import AdminSite from django.test import TestCase from myapp.admin import BookAdmin from myapp.models import Book class BookAdminTestCase(TestCase): def test_book_title(self): book = Book(title="Hello") book_admin = BookAdmin(Book, AdminSite()) self.assertEqual(book_admin.book_title(book), "Hello") This works fine when I run tests (./manage.py test) on my local development site. But when I run tests in a GitHub Action step... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...while other tests all work fine, tests using the AdminSite() call fail with: psycopg2.errors.UndefinedTable: relation "django_site" does not exist 196 LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... These tests use the same Django settings as when run locally. If I run migrations in the GitHub Actions step before I run the tests... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py migrate --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...this error doesn't occur, so I can get round this, but … -
charfield Connect to another model charfield (django)
I have a question answer quiz. I have 2 models of question and answer. The answer model I have related to the reading model. But in html I could not figure out how to build it properly. I want something like that. Show the question and below the question be the answer model charfield "answer" then check if the answer is equal to the question answer "answer_question". How do I guess I have a problem in vieweb. If you can help me, thanks in advance. for example (image) this is code -> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def _unicode__(self): return unicode(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if … -
Search by foreign key in admin
models.py class Supplier(models.Model): name = models.CharField(blank=True, max_length=50,) city = models.CharField(blank=True, max_length=50) email = models.CharField(blank=True, max_length=50) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=100) DDT = models.FileField(upload_to="DDT/%Y/%m/%d") fattura = models.FileField(upload_to="DDT/%Y/%m/%d") admin.py @admin.register(Supplier) class SupplierModelAdmin(admin.ModelAdmin): model = Supplier @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): model = Product list_display = ['supplier'] search_fields = [ 'supplier'] when i search for a supplier , django return an error : Related Field got invalid lookup: icontains -
Django twitter clone Following and Follower problem
Hy, I am trying to make a twitter clone using django however I am having issues implementing following and follower system. Suppose I have 2 users A and B. If A follows B, B should be in user A following List furthermore user A should be in user B followers List. However my code seems to implement the reverse and I am confused. e.g I if I follow elon musk he would be in my following list but I would be in his followers list Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True, max_length=30) profile_picture = models.ImageField(upload_to="images/profile/",default='default.png') following = models.ManyToManyField(User, symmetrical=False, blank=True,related_name='all_following') followers = models.ManyToManyField(User, symmetrical=False, blank=True, related_name='all_followers') def __str__(self): return str(self.bio) def get_absolute_url(self): return reverse('home') def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print('Profile Created') post_save.connect(create_profile,sender=User) def update_user_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() print('Profile Updated') post_save.connect(update_user_profile, sender=User) def profile_picURL(self): try: url = self.profile_pic.url except: url = " " return url HTML CODE SNIPPET <div class="column3"> {% for user in users%} {% if not request.user == user%} <div class="follow-users"> <h5>{{user.username}}</h5> <div class="follow-user"> <div> <span>{{user.all_followers.all.count}} followers</span> <span>{{user.all_following.all.count}} following</span> <p><a href="{% url 'view_user_profile' user.id %} ">View {{user.username}} profile</a></p> </div> <form action="{% url 'follow_unfollow_user' user.id %}" method="POST" … -
divisibleby requires 2 arguments error in django
i am probably making a dumb mistake but why does the divisibleby template tag give me an error that it needs two arguments for me when i have seen many others use one argument and get it to work. here is the full error: divisibleby requires 2 arguments, 1 provided templates: {% for item in posts %} {% if item in ads and forloop.counter|divisibleby 5 %} //print ads {% endif %} //print products {% endfor %} -
Django Signal For Updating User
View def transfer(request): if request.method == 'POST': t_form = TransferForm(request.POST, instance=request.user.profile) if t_form.is_valid(): t_form.save() messages.success(request, f'Amount sent!') else: t_form = TransferForm(instance=request.user.profile) context = locals() return render(request, 'transfer.html', context) Models.py from django.contrib.auth.models import User from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=400, default='Hi! I am new :D') image = models.ImageField( default='default.png', upload_to='profile_pics') balance = models.IntegerField(User, default=10) def __str__(self): return f'{self.user.username} Profile'``` class Transfer(models.Model): to_user = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) amount = models.IntegerField(default=0) def __str_(self): return f'{self.to_user.username} Transfer' def transferred(sender, instance, **kwargs): Transfer.to_user = User.objects.first() Transfer.amount = 35 Transfer.amount += Transfer.to_user.profile.balance Transfer.to_user.save() post_save.connect(transferred, sender=Transfer) Form: class TransferForm(forms.ModelForm): class Meta: model = Transfer fields = ['to_user', 'from_user', 'amount'] What's wrong here? What to do so that when I enter the transfer class fields using TransferForm, the to_user's (who is the user whom im sending the amount) balance field updates with the amount we sent? -
Prevent Dropdown menu from closing if I click a menu item
I have a drop down menu in sidebar and it has links as menu items. When I click a menu item(link) then link works fine but drop down menu gets closed. But I want that dropdown menu stay opened even after clicking a menu item. HTML Code: <button class="dropdown-btn button">Products <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="{% url 'shop:admin_products_list' %}">View Products</a> <a href="{% url 'shop:admin_product_create' %}">Add New Product</a> </div> I tried these two following ways: $('div.dropdown-container a').on('click', function(e) { e.preventDefault(); }); $('div.dropdown-container a').on('click', function(e) { e.stopPropagation(); }); But these two ways did not work. Please help me to resolve it. -
How to extend user model for Social_auth uisng pipeline?
I have successfully implemented the social_auth package for django and it is successfully populating the fields in postgres. I am trying to extend the user models so that i can add some additional data while creating the account by user. This is what i could come up with, till now. I have almost tried all the available resources online available but are not very helpful in this case. settings.py #pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'django_social_app.pipeline.requestprofiledata', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) models.py from django.db import models from django.contrib.auth.models import User, auth # Create your models here. class profiledata(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) #first_name =models.CharField(max_length=120) #last_name =models.CharField(max_length=120) #email =models.CharField(max_length=120) registeredemail = models.CharField(max_length=120) mobile = models.CharField(max_length=10) instname = models.CharField(max_length=10) idproof = models.FileField(upload_to='documents/') profiledatacomplete = models.BooleanField() views.py def getprofiledata(request): return render(request,'createCertificates/profile.html') pipeline.py from django.shortcuts import redirect from .models import profiledata #from socia.pipeline.partial import partial from django_social_app import views from social_core.pipeline.partial import partial @partial def requestprofiledata(strategy, details, user=None, is_new=False, *args, **kwargs): print(details) print(type(user)) #print(user.first_name,"..............") #print(user.registeredemail) test = 0 #if user and user.email and test != 0: if test == 1: return #elif is_new and not details.get('email'): else: registeredemail = strategy.request_data().get("registeredemail") #user['registeredemail'] = strategy.request_data().get("registeredemail") mobile = strategy.request_data().get("mobile") instname = strategy.request_data().get("instname") idproof = strategy.request_data().get("idproof") ''' … -
Django filter a prefetched queryset returning an empty list
In my app I have some Users and Groups, that are related by a many to many relation through GroupMember. class User(models.Model): ... class Group(models.Model): ... users = models.ManyToManyField(User, through='groups.GroupMember', related_name='groups') class GroupMember(models.Model): ... user = models.ForeignKey(User, related_name='group_members', on_delete=models.CASCADE) group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE) Now I am trying to build an endpoint that retrieves a list of user instances that are in any one of the groups that your user is in. So if user A and B are in group1, user A and C are in group2, and C and D are in group3, retrieving the users as A would return B and C (since those are in groups with A). That filter part can be done in multiple ways, but the part where I am stuck is how to show which groups were the cause of the relation. I tried to use prefetch_related with a custom filter, to fetch only the groups that have user A in them, like this: User.objects.exclude(id=user.id).annotate( # Annotate the amount of groups related between the users related_group_count=Count('groups', filter=Q(groups__users=user)) ).filter( # Only users that have at least 1 relation with this user related_group_count__gt=0 ).prefetch_related( # Prefetch the specific groups to show Prefetch('groups', User.groups.all(), to_attr='related_groups'), …