Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use elasticsearch for mutiple models in Django using the same search api
I am trying to implement an elastic search in Django for multiple models in a single search api. If I had to implement using different apis I can do in the following way. my models.py class Category(models.Model): name = models.CharField(max_length=32) description = models.TextField(null=True, blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return f'{self.name}' ARTICLE_TYPES = [ ('UN', 'Unspecified'), ('TU', 'Tutorial'), ('RS', 'Research'), ('RW', 'Review'), ] class Article(models.Model): title = models.CharField(max_length=256) author = models.ForeignKey(to=User, on_delete=models.CASCADE) type = models.CharField(max_length=2, choices=ARTICLE_TYPES, default='UN') categories = models.ManyToManyField(to=Category, blank=True, related_name='categories') content = models.TextField() created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.author}: {self.title} ({self.created_datetime.date()})' my serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer() categories = CategorySerializer(many=True) class Meta: model = Article fields = '__all__' views.py class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() documents.py @registry.register_document class CategoryDocument(Document): id = fields.IntegerField() class Index: name = 'categories' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = Category fields = [ 'name', 'description', ] @registry.register_document class ArticleDocument(Document): categories = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField(), }) type = fields.TextField(attr='type_to_string') class Index: name = 'articles' settings = { 'number_of_shards': … -
Get Session Data in Django Consumer
I want to get session data in consumers.py, this session data will be used to filter data. The code like this. queryset = Mail.objects.filter(status='session_data') serializer_class = PostSerializer permissions = permissions.AllowAny async def connect(self, **kwargs): await self.model_change.subscribe() await super().connect() @model_observer(Mail) async def model_change(self, message, observer=None, **kwargs): await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return dict(data=PostSerializer(instance=instance).data, action=action.value) How can i get it ? -
Trouble replying Django to heroku
so I’ve just finished building my first project. Just when I thought I was done, I ran into an issue during deployment. I’m getting an H10 error that is causing my app to crash when I try deploying it. I’ve checked my Procfile, settings, etc. I’ve tried just about everything , still can’t seem to find what the issue is. I’ve attached a few photos for anyone that is willing to help. Thanks in advance! enter image description here -
How to filter by field in django rest framework class based views
I have an app (class based views) with content in many languages and I want to give the option to filter by language in my endpoint like this: localhost:8000/api/resources/?language=ES This is my JSON data: { "id": 10, "contents": [ { "id": 5, "language": "EN", "name": "First" }, { "id": 6, "language": "ES", "name": "Primero" } ], "created_at": "2022-08-07T20:27:16.581115-05:00", "updated_at": "2022-08-07T20:27:16.581115-05:00" } What is the most elegant way of doing this? -
how do i change the language prefix to the user stored prefered language
I am working on a multilanguage Django project and i am using i18n for that, what i want to do is store the user-preferred language, I have already done that and added a language field in the User model, so my approach to solve this problem was creating a middleware to change to the user preferred language: from Django.utils import translation class LanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated and request.user.language: translation.activate(request.user.language) else: translation.activate(translation.get_language()) response = self.get_response(request) return response and I set the user language to 'ar', but if I try to enter with the URL 127.0.0.1:8000/en it doesn't work as expected and gives me this 1.ar/ The current path, en/, didn’t match any of these. but what I wanted is to redirect it to this 127.0.0.1:8000/ar either from this 127.0.0.1:8000 or this 127.0.0.1:8000/en and of course, that will be based on the preferred language, and if the user is not authenticated it will be just based on the language data in the request, how can I do that please? -
CS50 Project 1 Help - Wiki Search w/ Django - Stuck on how to save a new page
So I am creating my Wiki Search Page with Django and everything is going fine so far. I am now stuck on how to create a new entry in my search encyclopedia. On my home bar the "Create new Page" link works fine and takes me to a new page where I can create a new entry. The problem is when I try and save the entry into my encyclopedia I get this message: ValueError at /new/ The view encyclopedia.views.new didn't return an HttpResponse object. It returned None instead. I think it is a problem in my views.py section but can't seem to figure it out. Here is my views.py def new(request): if request.method == 'GET': return render(request, "encyclopedia/new.html", { "create_form": CreateForm(), "search_form": SearchForm() }) file_content = request.POST.get("content","") file_title = request.POST.get("title", "") if (len(file_content) == 0 or len(file_title) == 0): return render(request, "encyclopedia/error.html", { "message": "Bad Request", "description": "Title and content cannot be empty", "status": 400 }) if util.get_entry(file_title): return render(request, "encyclopedia/error.html", { "message": "Bad Request", "description": "This page already exists", "status": 400 }) Everything with the page works fine. I get the correct error when trying to save the page without any entry. The problem is it just won't … -
Overriding Django's default id in it's User Model
We have a working Django project in a multi-master database environment. That means the we have multiple instances of the project's database running in separate machines and that all individual changes are propagated to the other databases. Is working very well in this setup and without any issues. Up to now, we were not using Django's Auth tooling, meaning that there was not user login or password. That has to change. For this to work in our replication environment, thou, we need to change User's default id to something akin of a UUID to avoid collisions when the replications occurs. So, the challenge at hand is this: how to change the id field of the User model in the Auth App? We don't have any other specific requirement except this. We don't need any extra field and anything. Just to change the id. In the case that writing our own custom User model is inescapable maybe someone could point us at some good blog post about it or share any other resource. Ideally we would like to preserve everything else. including access to admin's interface, groups and permissions. Thanks in advance -
Customer isn't created for a user while trying to log in with google
For my website, its all okay if I register and then log in. But when I try to log in with google Customer objects is unable to create. Therefore I found the error that User has no Customer. Here's my model view for customer: user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) I tried to implement Customer creation but it seems no effect. here's my views.py: def google_login(request): redirect_uri = "http://127.0.0.1:8000/accounts/google/login/callback/" % ( request.scheme, request.get_host(), reverse('pain:google_login') ) if('code' in request.GET): params = { 'grant_type': 'authorization_code', 'code': request.GET.get('code'), 'redirect_uri': redirect_uri, 'client_id': settings.GP_CLIENT_ID, 'client_secret': settings.GP_CLIENT_SECRET } url = 'https://accounts.google.com/o/oauth2/token' response = request.post(url, data=params) url = 'https://www.googleapis.com/oauth2/v1/userinfo' access_token = response.json().get('access_token') response = request.get(url, params={'access_token': access_token}) user_data = response.json() email = user_data.get('email') if email: user, _ = User.objects.get_or_create(email=email, username=email) Customer.objects.get_or_create(email=email, username=email) gender = user_data.get('gender', '').lower() if gender == 'male': gender = 'M' elif gender == 'female': gender = 'F' else: gender = 'O' data = { 'first_name': user_data.get('name', '').split()[0], 'last_name': user_data.get('family_name'), 'google_avatar': user_data.get('picture'), 'gender': gender, 'is_active': True } user.__dict__.update(data) user.save() user.backend = settings.AUTHENTICATION_BACKENDS[0] login(request, user) else: messages.error( request, 'Unable to login with Gmail Please try again' ) return redirect('/') else: url = "https://accounts.google.com/o/oauth2/auth?client_id=%s&response_type=code&scope=%s&redirect_uri=%s&state=google" scope = [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ] scope = " ".join(scope) … -
QuerySet object has no attribute "email"
I am trying to get a list of all pathologists in my system. I need to filter the user on 2 basis i-e is_pathologist and Lab_Id=request.data[email] I have tried switching between filter and get but then I get Authentication.models.User.MultipleObjectsReturned: get() returned more than one User -- it returned 12! This is the code of my view @api_view(['POST']) def getAllPathologists(request): user = get_user_model().objects.get(is_pathologist=True) # If user exists, get the employee print("user is: ", user) pathologist = Employee.objects.get(user=user.email, Lab_Id=request.data['email']) pathologistSerializer = EmployeeSerializer(pathologist, many=True) return Response(pathologistSerializer.data) This is user model class User(AbstractUser): # Add additional fields here id = None email = models.EmailField(max_length=254, primary_key=True) name = models.CharField(max_length=100) password = models.CharField(max_length=100) contact_number = models.CharField(max_length=100) is_patient = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) is_homesampler = models.BooleanField(default=False) is_pathologist = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_lab = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now=True,editable=False) last_login = models.DateTimeField(auto_now=True) first_name = None last_name = None username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'password'] objects = CustomUserManager() def __str__(self): return self.email # Ensure that the password is hashed before saving it to the database def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return self.is_superuser This is Employee model class Employee(models.Model): user = … -
How can I send a message to all posts in Django Allauth?
I am trying to send an email to all registered users in Django Allauth, but when I try to get a list of all users' emails and send it via the send_mail() method, I get an error : too many values to unpack (expected 2) When I manually specify the mail in the recipient_list list, then everything works. But I need it to be automatically sent to the emails of all users. Tried to do through : def email(request): cleaned_data = super().clean() title = cleaned_data.get('articles_title') message = cleaned_data.get('articles_text') recipient_list = User.objects.get('email') email_from = 'mymail' send_mail(title, message[:50], email_from, recipient_list) return title, message or iterate through the for loop: def email(request): cleaned_data = super().clean() title = cleaned_data.get('articles_title') message = cleaned_data.get('articles_text') mails = User.objects.get('email') recipient_list = [] for i in mails: recipient_list.append(i) email_from = 'mymail' send_mail(title, message[:50], email_from, recipient_list) return title, message But nothing helps, does someone know some alternative method? -
Should I use Django or FastAPI?
I am developing an app Can I use FastAPI? Or is using apps only in Django? And in general If I need to develop a very fast application In which framework would you recommend? (My application is coded in Python, React Native, and Mongo) -
Why is Django having trouble accessing my User table?
I am new to Django and web development in general. I am trying to test my app, recipe_book, using the admin page. When try to login at http://127.0.0.1:8000/admin, I get the following error: no such table: recipe_book_user I have a model class named "User", defined below: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I then successfully made migrations and migrated the changes. To resolve this issue, I've tried registering the User class in admin.py, with no success. I've also tried following the steps to reset the database in the following question: Django - no such table exception Does anyone know how I can resolve this? -
Query with two ForeignKeys in a model and filter on one of the ForeignKey
I have the three models: class SegmentEffort(models.Model): id = models.BigIntegerField(primary_key=True) activity = models.ForeignKey(to=Activity) segment = models.ForeignKey(to=Segment) class Segment(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=255) class Activity(models.Model): id = models.BigIntegerField(primary_key=True) user = models.ForeignKey(to=settings.AUTH_USER_MODEL) name = models.CharField(max_length=255) I want to get all distinct segments from SegmentEffort where SegmentEffort is filtered by Activity belonging to a specific user. I can get a list of all the segment ids by: sids = SegmentEffort.objects.filter(activity__user=10).order_by('segment_id').values_list('segment_id', flat=True).distinct() But I can't get my head around getting distinct a segment queryset... Not enough experience with queries on two ForeignKeys in a model (SegmentEffort). Thanks for your help, and don't hesitate to ask for clarification id the question is unclear! -
Application Load Balancer Health Django Elastic Beanstalk Barebones
Using this guide below to setup a simple app: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I used the interactive eb create to chose an Application Load Balancer vs the Classic (I used CLASSIC before and it works).. Anyways, why does this not work "OUT OF THE BOX" like the Classic Load Balancer? What do I need to configure as the docs are all over the place (and outdated)? Like really, this should work out of the box (I am using the most barebones django test app) Works in Classic Load Balancer and not in Application Load Balancer. Thanks. some docs: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.elb.html -
Trying to create a separate comments app for a django ticket project
I'm trying to create a separate comments app for a ticket project using class-based views for both the tickets and the comments. I think I got most of the functionality down, because when I try to use the comment feature on the site itself, it shows up in the django admin but not on the site. I believe the problem lies in my urls.py files or it could be my model, but I'm not so sure how to proceed. Please help Here's the traceback Installed Applications: ['tickets.apps.TicketsConfig', 'users.apps.UsersConfig', 'comments.apps.CommentsConfig', 'demo.apps.DemoConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\contrib\auth\mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 174, in post return super().post(request, *args, **kwargs) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 144, in post return self.form_valid(form) File "C:\Users\mikha\issuetracker\comments\views.py", line 41, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 128, in form_valid return super().form_valid(form) File "C:\Users\mikha\bug_env\lib\site-packages\django\views\generic\edit.py", line 59, in … -
Assistance Required to select and set different OAuth ClientId and ClientSecret credentials for all views
I am working on my first ever Django project and have been trying to do something that I have been stuck with for weeks and looking for any assistance, please. each of my views uses a CLIENT_ID, CLIENT_SECRET and I have a page with a drop-down to select one of the OAuth Accounts that I would like to use. Menu Screenshot HTML Snippet <h2>Select Menu</h2> <p>To style a select menu in Bootstrap 5, add the .form-select class to the select element:</p> <label for="cust" class="form-label">Select list (select one):</label> <select class="form-select" id="cust" name="customer"> <option>Auth 1</option> <option>Auth 2</option> <option>Auth 3</option> <option>Auth 4</option> </select> <input type="submit" value="click" class="btn btn-primary"> Views.py snippet def data(request): # OAuth when using Client Credentials CLIENT_ID = CLIENT_ID CLIENT_SECRET = CLIENT_SECRET def getdata(request): # OAuth when using Client Credentials CLIENT_ID = CLIENT_ID CLIENT_SECRET = CLIENT_SECRET When an Auth Selection is made via the dropdown, I would like to set the CIENT_ID and CLIENT_SECRET to be used for all of my views. Ultimately I would like to use dotenv as well. I am struggling to get the selection and then set the CIENT_ID and CLIENT_SECRET to each view. Thank you very much. -
Querying One model item from another model
Please help me. I have a list of Artist (Musicians) and their Albums they created. T My models looks like the following: from django.db import models # Create your models here. class ArtistModel(models.Model): Artist_name = models.CharField(max_length=50, null=True, default=False) def __str__(self): return self.Artist_name class AlbumsModel(models.Model): Genre = { ('Hip-Hop','Hip-Hop'), ('Rnb','Rnb'), ('Rock n Roll','Rock n Roll'), ('House','Housep'), ('Gospel','Gospel'), ('Classical','Classical'), } Album_name = models.CharField(max_length=50, null=True, default=False) Album_by = models.ForeignKey(ArtistModel ,max_length=50, null=True, default=False, on_delete=models.CASCADE) Music_genre = models.CharField(max_length=50, null=True, default=False, choices=Genre) def __str__(self): return self.Album_name My Views from django.shortcuts import render from . models import AlbumsModel, ArtistModel # Create your views here. def Albums(request): AllAlbums = AlbumsModel.objects.all() return render(request, 'Albums/Home.html', {'AllAlbums':AllAlbums}) def Artist(request): AllArtist = ArtistModel.objects.all() return render(request, 'Albums/Artist.html', {'AllArtist':AllArtist}) My HTML is the following: {% extends 'Albums/Layout.html' %} {% block content %} <h1>Artist</h1> <br/> {% for artistview in AllArtist %} <a href="{% url 'Artist_album' %}"> {{artistview}}<br> </a> {% endfor %} {% endblock %} My shell looks like the following: In [24]: All_Albums Out[24]: <QuerySet [<AlbumsModel: THE EMINEM SHOW>, <AlbumsModel: THE MARSHELL MATHERS LP>, <AlbumsModel: BLUEPRINT>, <AlbumsModel: THE BLACK ALBUM>, <AlbumsModel: 4:44>, <AlbumsModel: MAGNA CARTA HOLY GRAIL>, <AlbumsModel: JESUS IS KING>, <AlbumsModel: DONDA>, <AlbumsModel: GRADUATION>]> In [25]: Artist_all Out[25]: <QuerySet [<ArtistModel: Eminem>, <ArtistModel: Jayz>, <ArtistModel: … -
How to update value in JSON field in Django Rest Framework
I am making an API with Django Rest Framework and I have a problem. When I try to change the value of JSONfield from False to True (or vice versa) it doesn't change the value of specific key, but it changes the whole JSONfield to True(or False). How do I change the value of just a key? My models.py: class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=100) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) fruit = models.JSONField(default={"Apple":False, "Pear": True, "Orange":False}) #This is that field USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) My serializers.py: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ["fruit"] def update(self, instance, validated_data): instance.fruit = validated_data.get('fruit', instance.fruit) instance.save() return instance My views.py: class UpdateFruitView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = FruitSerializer permission_classes = (IsAuthenticated,) def update(self, request, *args, **kwargs): fruit = request.data.get("fruit") select_fruit = request.user.fruit[fruit] if select_fruit == False: select_fruit = True data_to_change = {'fruit': select_fruit} serializer = self.serializer_class(request.user, data=data_to_change, partial=True) if … -
Unable to use ManyToMany Field with Django and Postgres
I am working on a project with Django, Postgres. I typed that : user_test = User.objects.first() food_test = Food.objects.first() user.food.add(food_test) When I type that : user.food I got that : <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7471bd30> Then if I type that : user.food.name I got that : AttributeError: 'ManyRelatedManager' object has no attribute 'name' Whereas the field name exists. Could you help me please ? Thank you very much ! -
How to remove an already selected option from options list to avoid double bookings
I've been scratching my head with this for 2 days hoping for a sudden brainwave and getting nowhere. I've completely drawn a blank with my logic and all attempts have resulted in me breaking my code. I'm trying to get it so that on a specific date, if a user has already selected a time slot with a selected barber, that that time slot will be removed from the list of time slots, so it cannot be selected again by another user. From models.py from django.db import models import datetime from django.core.validators import MinValueValidator from django.contrib.auth.models import User SERVICES = ( ('Gents Cut', 'Gents Cut'), ('Kids Cut', 'Kids Cut'), ('Cut and Shave', 'Cut and Shave'), ('Shave Only', 'Shave Only'), ) TIME_SLOTS = ( ('9.00 - 10.00', '9.00 - 10.00'), ('10.00 - 11.00', '10.00 - 11.00'), ('11.00 - 12.00', '11.00 - 12.00'), ('12.00 - 13.00', '12.00 - 13.00'), ('13.00 - 14.00', '13.00 - 14.00'), ('14.00 - 15.00', '14.00 - 15.00'), ('15.00 - 16.00', '15.00 - 16.00'), ('16.00 - 17.00', '16.00 - 17.00'), ('17.00 - 18.00', '17.00 - 18.00'), ) BARBER_NAME = ( ('Nathan', 'Nathan'), ('Chris', 'Chris'), ('Ben', 'Ben'), ('Dan', 'Dan'), ) class Booking(models.Model): date = models.DateField(validators=[MinValueValidator(datetime.date.today)]) time = models.CharField(max_length=50, null=True, choices=TIME_SLOTS) … -
Django Friend Request system
I am trying to make a friend request system with Django for a cat app, and I am having a problem. I have models to track the friends and the friend request. In the views I have a redirect view with a try except clause that creates a new instance of the friend request model. Then the friend request will be shown to whoever it was sent to, and they will accept or decline it. The problem I have is i don't know how to grab the info about the user to whom the friend request is sent. Any help would be appreciated. Here is the link to my project repository https://github.com/codewiz9/chatter modles.py from django.db import models from django.utils.text import slugify from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Chat(models.Model): messages = models.TextField(blank=True, max_length=2000, null=False), date = models.DateTimeField(blank=False, editable=False), slug = models.SlugField(allow_unicode=True, unique=True,), friends = models.ManyToManyField(User, through='Friend_List'), class Friend_List(models.Model): friend_name = models.ForeignKey(User, related_name='name', on_delete=models.CASCADE), is_friend = models.BooleanField(default=False), def __str__(self): return self.user.username class Friend_Info(models.Model): friend_name = models.ForeignKey(User, related_name='name', on_delete=models.CASCADE), slug = models.SlugField(allow_unicode=True, unique=True,), class Friend_Request(models.Model): yes_or_no = models.BooleanField(default=False), friends = models.ManyToManyField(User, through='Friend_List'), slug = models.SlugField(allow_unicode=True, unique=True,), Views.py from django.shortcuts import render from django.urls import reverse from … -
How to create an like/dislike buttons for more than one fields for on Django model without page reload?
My Model from django.db import models # Create your models here. class Musician(models.Model): name_of_blog_maker = models.CharField(max_length=200, null=True, blank=True) name_of_musician = models.CharField(max_length=200) name_of_band = models.CharField(max_length=200) published_date = models.DateTimeField("Published At", blank=True, null=True) appreciation = models.TextField(null=True, blank=True) cover = models.ImageField(upload_to="images/", default=None) music_1 = models.FileField(upload_to="music/", default=None) music_1_name = models.CharField(max_length=200, null=True, blank=True) music_1_votes = models.IntegerField(default=0) music_1_users = models.JSONField(default=dict) music_2 = models.FileField(upload_to="music/", default=None) music_2_name = models.CharField(max_length=200, null=True, blank=True) music_2_votes = models.IntegerField(default=0) music_2_users = models.JSONField(default=dict) music_3 = models.FileField(upload_to="music/", default=None) music_3_name = models.CharField(max_length=200, null=True, blank=True) music_3_votes = models.IntegerField(default=0) music_3_users = models.JSONField(default=dict) def __str__(self): return self.name_of_musician In my "Musician" Model "music_1_votes" is storing the number of votes by all logged in users for "music_1". The "music_1_users" is storing the "username" and "user_id" in dictionary format. Same goes for music_2 and music_3. My View class MusicianDetailView(DetailView): model = Musician template_name = "guitar_blog/blog_detail.html" def post(self, request, **kwargs): song = self.get_object() user_id = request.user.id user_username = request.user.username if request.user.is_authenticated: if "Like1" in request.POST and user_username not in song.music_1_users.keys(): song.music_1_votes += 1 song.music_1_users[user_username] = user_id song.save() elif "Unlike1" in request.POST and user_username in song.music_1_users.keys(): song.music_1_votes -= 1 song.music_1_users.pop(user_username) song.save() elif "Like2" in request.POST and user_username not in song.music_2_users.keys(): song.music_2_votes += 1 song.music_2_users[user_username] = user_id song.save() elif "Unlike2" in request.POST and user_username in song.music_2_users.keys(): … -
Problem with Django Error during template rendering, maximum recursion depth exceeded
enter image description here I have gone through everything you say in answers to similar problems but I can't find the solution. -
problem with django multitable inheritance and django-parler
i have these models: class Product(TranslatableModel): productId = models.UUIDField(default=uuid4, primary_key=True, editable=False) translations = TranslatedFields( title = models.CharField(max_length=100), description = models.TextField(max_length = 2000) ) picture = models.ImageField() price = models.FloatField() art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) purchase_num = models.PositiveBigIntegerField() objects = InheritanceManager() class Course(Product): languages = models.ManyToManyField(Language) isChaptersOpen = models.BooleanField(default=True) but whenever i try to add a new course i get this error message in the django admin panel: ImproperlyConfigured at /en/admin/products/product/ InheritanceQuerySet class does not inherit from TranslatableQuerySet why this is happening -
Django Migration to add Group and permissions not adding permissions
I have a custom migration that is intended to automatically create a new group and add permissions. The group is being created but the permissions are not being added. Any ideas about how to fix this? from django.db import migrations, models from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) group, created = Group.objects.get_or_create(name='Employee') if created: permissions_qs = Permission.objects.filter( codename__in=[ 'can_add_how_to_entry', 'can_change_how_to_entry', 'can_view_how_to_entry', ] ) for permission in permissions_qs: group.permissions.add(permission) group.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ]