Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update an m2m field programmatically in django signals
I'm trying to automatically update an m2m field within my model class. It's an observe-execute if true type, meaning if my model instance has a certain attribute, assign it to this group or that group. The model class looks like this: class User(AbstractBaseUser, PermissionsMixin): is_worker = models.BooleanField(_('Worker'), default=False, help_text='register as a worker') is_client = models.BooleanField(_('Client'), default=False, help_text='register as a client') The signal looks like this: @receiver(post_save, sender=User) def assign_user_to_group(sender, instance, **kwargs): if instance.is_client: instance.groups.add([g.pk for g in Group.objects.filter(name='clients')][0]) elif instance.is_worker: instance.groups.add([g.pk for g in Group.objects.filter(name='workers')][0]) Usually, I may need to call the save() method on my instance, but the docs states otherwise, plus defying that just gets me a RecursionError. Could you please suggest a cleaner approach that best solves this? Thank you. -
custom queryset for a foreignkey field in django admin's list_editable
I want to select the category with is_active=True in the List view of django admin, for quickly editing a category for a campaign in the list view itself. While I did peek into the django code and found methods like changelist_view , get_changelist_formset which can be overridden, is there any easier way or an example of how to achieve this? Bottomline, still trying to figure out how to provide a custom queryset for a list_editable field in django admin! # models.py from django.db import models class Campaign(models.Model): name = models.CharField(max_length=20) start = models.DateTimeField() category = models.ForeignKey(Category) def __unicode__(self): return unicode(self.name) class Category(models.Model): name = models.CharField(max_length=20) is_active = models.BooleanField() def __unicode__(self): return unicode(self.name) # admin.py from django.contrib import admin from models import Campaign, Category class CampaignChangeListForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CampaignChangeListForm,self).__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: self.fields['category'].queryset = Category.objects.filter(is_active=True) class Meta: model = Campaign fields = '__all__' class CampaignAdmin(admin.ModelAdmin): list_display = ('name', 'category', 'start') list_editable = ['category'] admin.site.register(Campaign, CampaignAdmin) admin.site.register(Category) -
Sending Email from inside docker container, where emailserver is in another container
I have setup my email server using https://github.com/docker-mailserver/docker-mailserver My website back-end made in Django is in an other container. I am able to send email using my smtp server from my local environment smoothly but when i try same thing in my docker environment it sometimes work, sometimes doesn't, even when it works it works pretty slow like takes few minutes to establish connection and all I tried making an external network and using same network in both docker compose files, but the same issue in my mail console, this log comes right away mailserver | Jun 4 13:00:30 kryptohive postfix/submission/smtpd[2813]: connect from unknown[192.168.32.1] after that it can take time or not, not sure why is it working like that my mailserver docker-compose.yml version: '3.4' services: mailserver: image: docker.io/mailserver/docker-mailserver:latest hostname: kryptohive.com # <-- CHANGE THIS domainname: kryptohive.com # <-- CHANGE THIS container_name: mailserver env_file: mailserver.env # To avoid conflicts with yaml base-60 float, DO NOT remove the quotation marks. # More information about the mailserver ports: # https://docker-mailserver.github.io/docker-mailserver/edge/config/security/understanding-the-ports/ ports: - "25:25" # SMTP (explicit TLS => STARTTLS) - "143:143" # IMAP4 (explicit TLS => STARTTLS) - "465:465" # ESMTP (implicit TLS) - "587:587" # ESMTP (explicit TLS => STARTTLS) - … -
For loop variable doesn't work in an if condition in Django Templates
I am first taking a specific brand of a car from one view and passing it onto the other view so that the user can then choose the model of the car. My views.py... def driver_dashboard_trip_brand (request, brand): brands = VehicleBrand.objects.all() context = { "brands":brands, "chosen_brand":brand } return render (request, "app/driver_dashboard.html", context) My driver_dashboard.html... <div class="mb-3"> <select class="form-select" aria-label="Default select example" id="brand" name="brand" onchange="submitBrand(event)"> <option value="">Choose a brand</option> {% for brand in brands %} {% if brand == chosen_brand %} <option value="{{brand}}" selected>{{brand}}</option> {% else %} <option value="{{brand}}">{{brand}}</option> {% endif %} {% endfor %} </select> </div> But then I realised that the brand variable doesn't get recognized in the if condition. However, if I add something like this {% if chosen_brand == 'BMW' %} it works perfectly fine, but DOES NOT work if I do something like {% if brand == 'BMW' %}. Is there anything that I am missing out on? Any help is greatly appreciated. Thanks!! -
Django - Filter query based on values of another query
I'm fairly new to django so not sure how to do this correctly. I have a filter that matches a foreign key property to a parameter which works fine: @plural_filter_params_filter def trade_group_filter(p): group = p.upper().split('|') # can filter both name or alias as name will always contain 'Companies' re_group = r'(' + '|'.join(group) + ')' if "COMPANIES" in group[0]: return Q(s_book__entity__groups__name__iregex=re_group) & \ Q(b_book__entity__groups__name__iregex=re_group) return Q(b_book__entity__groups__alias__in=group) & \ Q(s_book__entity__groups__alias__in=group) I want to further filter the result of this query for each of the results that match a condition. The entity model has a property type, which I want to check for. If both books in the result have the same type "A", then I want filter the primary_group to match either book with the same group parameter. If any match on either book then include it. Entity model: class Entity(TimeTrackedBase, UserTrackedBase, models.Model): type_choices = ENTITY.CHOICES name = models.CharField(max_length=50) type = models.CharField(max_length=1, choices=type_choices, default='C') primary_group = models.ForeignKey(Group, default=None, blank=True, null=True, on_delete=models.PROTECT) groups = models.ManyToManyField(Group, blank=False, related_name='+') I come from c# so to do this in Linq, I'd utilise a where clause something like this: preFilteredList.Where(x => { if (x.BBook.Entity.Type == EntityType.A && x.SBook.Entity.Type == EntityType.A) return x.BBook.Entity.PrimaryGroup == group || x.SBook.Entity.PrimaryGroup … -
Passing object as kwargs to URL tag in template?
Let's say I have a model like the following from django.db import models class Person(models.Model): first_name = models.CharField(max_length=36) last_name = models.CharField(max_length=36) and I have in urls.py a URL like path(r'profile/<str:first_name>/<str:last_name>/', ..., name='profile') In the template, if there's a variable person I could get their profile url by typing {% url "profile" person.first_name person.last_name %}. However, I would really prefer to not repeat myself and do something more along the lines of {% url "profile" **person %} --- that's not a valid syntax but the point is I'd like to use the attributes on person as the arguments to the URL tag. That way, if I ever change the URL pattern to use, say, middle_name as well, I don't need to edit the template again. Is there a (preferably built-in, but custom tags okay too) way to do this? I've spent a while on google with queries like "django url template tag kwargs" but haven't found anything. (And I want to avoid changing the URL itself since it is exposed to end user.) -
request.user in serializer gives wrong user but printing in a view gives right user
I have modelviewset like this in which if I print the current logged in user it gives me test1@gmail.com but in redirect url when I save the model it gives me diffrent user class ModelViewSet(viewsets.ModelViewSet): serializer_class = ModelSerializer permission_classes = [IsAuthenticated] def get_queryset(self) -> QuerySet: print(self.request.user) #gives test1@gmail.com return Model.objects.all() ``` After that I use Oauth2 to integrate mailchimp and on my redirect URL I save the data and serializer looks like this. I am using JWT ```class ModelSerializer(serializers.ModelSerializer): class Meta: model = Model fields = "__all__" def create(self, validated_data: dict) -> Model: print(self.context["request"].user.email_address, "------------------------") print(self.context["request"].user.profile.user_id, "-----------------------") print(self.context["request"].user.profile.owner_id, "------------------------") #here it gives diffrent user #test2@gmail.com return instance ``` -
Django Celery Changes Not Applied
My django-celery code cannot reload, which I concluded after seeing an error that was supposedly resolved. Can anyone tell me how to properly restart my Celery server, or is the problem still existent? Running on Windows 10, by the way. file structure |-- manage.py |-- nttracker\ |-- celery.py |-- tasks.py |-- settings.py I have not yet added any separate configuration files yet. nttracker/celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nttracker.settings') postgres_broker = 'sqla+postgresql://user:pass@host/name' app = Celery('nttracker', broker='amqp://', backend='rpc://', include=['nttracker.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.update( result_expires=3600, ) app.conf.beat_schedule = { 'add-every-10-seconds': { 'task': 'nttracker.tasks.add', 'schedule': 10.0, 'args': (16, 16) }, } if __name__ == '__main__': app.start() nttracker/tasks.py from __future__ import absolute_import import django django.setup() from celery import Celery from celery.schedules import crontab app = Celery() @app.task def add(x, y): print(x + y) nttracker/settings.py # Celery Configuration Options CELERY_TIMEZONE = "valid/timezone" CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://127.0.0.1:6379' # celery setting. CELERY_CACHE_BACKEND = 'default' # django setting. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } terminal one output (celery -A nttracker worker --pool=solo -l INFO) [2021-06-04 20:03:54,409: INFO/MainProcess] Received task: nttracker.tasks.add[4f9e0e15-82de-4cdb-be84-d3690ebe142e] [2021-06-04 20:03:54,411: WARNING/MainProcess] 32 [2021-06-04 20:03:54,494: INFO/MainProcess] Task nttracker.tasks.add[4f9e0e15-82de-4cdb-be84-d3690ebe142e] succeeded in 0.09399999999732245s: None [2021-06-04 20:04:04,451: … -
Is there a way to use a SerializerMethodField and still write to it?
Building an API I did this serializer mainly to simplify the handling, as I am using the CreateModelMixin with my Viewset. This is a minified example for what I am trying to achieve: class TestSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField() type = serializers.CharField(required=False) class Meta: fields = ['id', 'name', 'type'] model = Test def create(self, validated_data): type = validated_data.pop('type', None) new_obj = super().create(validated_data) OtherModel.objects.create(test=new_obj, test=type) return new_obj The objects get created correctly but the response is very minimal. It just shows id and name and not the type. On my previous serializer I solved this via a SerializerMethodField for type and then a get_type method, but adding the method here doesn't help. I also tried to do this with a SerializerMethodField, but then the objects don't get created. -
Django - custom model save method doesn't show attributes values
while trying to save an instance of a model, I can't access the attributes values in the custom save() method. I think it should be possible straight forward, just like the docs state. Here's what my code looks like: class ModelName(models.Model): attribute1 = models.ManyToManyField("app.ModelName2", related_name="model_name_2") attribute2 = models.ForeignKey("app.ModelName3", related_name="model_name_3") def save(self, *args, **kwargs): super().save() print(self.attribute1.all()) # <---- it prints an empty qs, but in reality there are instances passed to attribute1 field. Does anyone have any idea why that would happen? I'm pretty sure I'm missing something super obvious. Thanks in advance! -
Test imports in whole large python django project
I develop a big python Django project as a part of my team. And there is one little problem with 3rd-party libraries in there: if someone installed new library to his computer, but not added it to a requirements file (or not commited this file), then on another machine project can run correctly until there will be executed line import <this_module> and then project will failed with ModuleNotFoundError. So, the question: what can I use to create a test script, which will be searching for all imports in project files, build an imports tree and will try to import all this libs/modules/functions? PS: It could simplify bugs discovering. E.x.: before pushing code to production server test will fail with ModuleNotFoundError and deploying will be interrupted. -
Django: PhoneNumberField Not getting Installed
I intalled Phonenumber package via pip and mentioned in my installed apps. As well as imported the same as mentioned in documentation to my models.py Even re-checked at the stack answers most of the people did the installation and imported file, but why mine is not working can anyone help pip install django-phonenumber-field[phonenumbers] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rk003.apps.Rk003Config', ] models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Agent(models.Model): agency_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=30) agency_address = models.CharField(max_length=300) agency_city = models.CharField(max_length=50) agency_country = models.CharField(max_length=50) email_address = models.EmailField(max_length=50) contact_nu = models.PhoneNumberField() Error is as follows File "/Users/rishipalsingh/Projects/notes/mdndjango/rk002/rk003/models.py", line 13, in Agent contact_nu = models.PhoneNumberField() AttributeError: module 'django.db.models' has no attribute 'PhoneNumberField' -
NAME CHOICE NOT DEFINED
def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(request.POST['Choice']) except (KeyError, choice.DoesNotExist): return render(request, 'mysite/detail.html',{ 'question':question, 'error_message':"you didn't select a choice", } ) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('mysite:results', args=(question.id,))) -
React and Django session problem that works on Postman but not in browser
I was wondering what I'm doing wrong. I am trying to implement the most simple session with React frontend and Django backend. I am aware that my methods are insecure and bad but its just a project for university and I need something that works so I should do other stuff that require sessions in my project. This is how my backend looks for Login and SessionInfo: @api_view(['POST']) def login(request): data = request.data try: user = MyUser.objects.get(username=data.get('username'), password=data.get('password')) request.session['uuid'] = user.id request.session.modified = True except MyUser.DoesNotExist: return HttpResponse("User does not exist.") return HttpResponse(request.session['uuid']) @api_view(['GET']) def getsession(request): if request.session.has_key('uuid'): return HttpResponse(request.session['uuid']) else: return HttpResponse(False) When I am trying to test this with Postman it always work and I get wanted session ID but when I'm trying to do same stuff with react using Axios post method it always return False. I have no clue why? This is how my post method looks in React: function login(){ axios.post('http://127.0.0.1:8000/evidencija/login/',{ username: 'admin', password: 'admin' }).then( (response) =>{ console.info(response.data) getSession() }, (error) =>{ console.log(error) } ) } -
Embedding an automatically generated Sphinx for python code into a html page
I have a website that I would like to display my Sphinx documentation on. So far i have built it so that I have a _build directory with "doctrees" and "html" as subfolders, the html subfolder containing the generated Sphinx documentation. I would like to embed this on my website so it looks as following: https://damask3.mpie.de/documentation/the-python-library/ This implementation was done by embedding it into an iframe. Is there a different way to do this, or is there an efficient way to create an iframe link for myself from the generated documentation files? -
How to import models.py from one app to another models.py in another app?
I am making an app that is similar to google classroom. I am coding this in repl.it, so i can't see the main application. I have two apps and mysite folder. One app is room and another is users I am trying to import a class from models.py that is in the room app to the models.py in the users app But when I do from room.models import Course, I get an error This is the screenshot for my whole directory, code and error. -
request.user returns AnonymousUser even when user is logged in
I would like to create a user when saving an object to the database but every time it says the user is AnonymousUser even though the user is logged in, below is a snippet, any help would be appreciated. def post(self, request): response = json.loads(self.request.body.decode('utf-8')) result_code = response["Body"]["stkCallback"]["ResultCode"] if result_code == 0: if response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Name"] == 'Balance': del response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2] amount = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] mpesa_receipt_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] transaction_date = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] phone_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] str_transaction_date = str(transaction_date) transaction_datetime = datetime.strptime( str_transaction_date, "%Y%m%d%H%M%S") aware_transaction_datetime = pytz.utc.localize( transaction_datetime) our_model = Mpesa.objects.create( Paid_user=request.user MpesaReceiptNumber=mpesa_receipt_number, PhoneNumber=phone_number, Amount=amount, TransactionDate=aware_transaction_datetime, ) our_model.save() -
Fetch all instances of model in batch and then query in Django
Is there any way to first fetch all or a filtered set of rows from a model and then query the results in Django? Pseudocode: queryset = MyModel.objects.all().fetch_all() inst_one = queryset.get(pk=1) # Sends query to database inst_two = queryset.get(pk=2) # Doesn't query database because everything has already been fetched -
How to impelment DjangoModelPermissions for the class based APIView ? It throws queryset exception. Queryset error
Scenario: I have group and permissions, permissions associated to group and that very group is associated to the user. Now I am trying to implement the permissions to the views through DjangoModelPermissions This works fine for the follwing code lines where queryset is implemented; class UpdateCampaignView(generics.UpdateAPIView): authentication_classes = [TokenAuthentication] permission_classes = [DjangoModelPermissions] queryset = Campaign.objects.all() serializer_class = UpdateCampaignSerializer def get_object(self): campaign_id = self.request.data.get("id") return Campaign.objects.get(id =campaign_id) But I want to implement this to class based APIView without queryset keyword something like this: class RetrieveCampaignView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [DjangoModelPermissions] #this is what i want to do def get(self, request, *args, **kwargs): try: campaign = Campaign.objects.get(id = request.data.get("id")) searializer = GetCampaignSerializer(campaign) return Response({"status":True , "payload":searializer.data}) except: return Response({"status":False}, status=status.HTTP_404_NOT_FOUND) But This Gives following Error: django rest framework error Cannot apply DjangoModelPermissions on a view that does not set .queryset or have a .get_queryset() method -
Django-Graphene: On a model ChoiceField, graphene expects a Type but got a value
On Django-Graphene, I have this model: class Entry(models.Model): STATE_CHOICES = [ ("Open", "Open"), ("Processing", "Processing"), ("Closed", "Closed"), ("Deleted", "Deleted"), ] # ... state = models.CharField(max_length=10, choices=STATE_CHOICES, default="Open") With the following Graphene schema: class EntryType(DjangoObjectType): class Meta: model = models.Entry class Query(graphene.ObjectType): entries = graphene.List(EntryType) def resolve_entries(self, info): return models.Entry.objects.all() But when I use the next query: query AllEntries{ entries{ id state } } I get this error: { "errors": [ { "message": "Expected a value of type \"EntryState\" but received: OPEN", "path": [ "entries", 1, "state" ] } ], } Can someone explain me what I'm doing wrong ? -
can we make an django app as rabbitmq consumer?
I have a django web application that displays messages stored in rabbitmq server Should we use a javascript consumer or add a consumer code to the views file? How to write consumer codes within the Dijango app? How can I make a consumer django app for rabbitmq ? Please Help. -
django channels does not work with more than 20-40 users in one channel
My system: django == 1.11.22, cchannels == 2.1.7, channels-redis == 2.2.1, daphne == 2.2.0, asgiref == 2.3.2 I tried using django pipes to include websockets in my project. The web socket subsystem simply sends system status to administrators and allows messages to be exchanged. My channel layer settings: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', # 'BACKEND': 'channels.layers.InMemoryChannelLayer', 'CONFIG': { "hosts": [(DJANGO_REDIS_HOST, DJANGO_REDIS_PORT)], "capacity": 100000, # default 100 "expiry": 5 # default 60 }, }, } I have increased the capacity of the channels to 100000 messages, but after 20-40 connections to the same URL "/ws/admins/" (this is one group "admins"), I start to get disconnects and duplicate messages, and django on the prod server will stop taking all connections until restarting docker containers. Decreasing expiry does not help either. if i use InMemoryChannelLayer then there are no errors. The server is started by the command: daphne -b 0.0.0.0 -p 8000 web_server.asgi: application -
Stripe API, How to get "subscription.status" from definition of ListView from django
I'm trying to configure Django Stripe Subscriptions for Database WebApp. I want to make sure only "paid user(subscribed user)" can search database. Therefore I need to check whether subscription.status is "active" Here is ListView of view.py from django.http import HttpResponse from.models import TestEu from django.views.generic import ListView import stripe from django.conf import settings from subscriptions.models import StripeCustomer #search class DbList(ListView): model = TestEu def get_queryset(self): stripe_customer = StripeCustomer.objects.get(user=request.user) stripe.api_key = settings.STRIPE_SECRET_KEY subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) if subscription.status == "active": sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) return object_list When executing the above code, an error message occurs at the code below. stripe_customer = StripeCustomer.objects.get(user=request.user) NameError: name 'request' is not defined In this paticuler situation, how can I define "request" to fetch Subscription data? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How to do a format check in Django models
I am trying to allow people to register their vehicles in my system and I want to provide a format check, which is very similar to the format LL-0000. Is it possible to get this done in the models.py or at least in the forms.py. This is my models.py just in case you needed it. class Vehicle (models.Model): model = models.ForeignKey(VehicleModel, on_delete=models.PROTECT) vehicle_colour = models.CharField(choices=COLOURS, max_length=10) vehicle_number = models.CharField(max_length=8) user = models.ForeignKey(User, on_delete=models.CASCADE) I needed the format check for the vehicle_number field. Any help is greatly appreciated. Thanks!! -
Enabled CORS White listing for Cross Origin Requests, Now I do not get CORS Error but my API Code gets Executed
I have enabled Cross Origin Requests by using the following approach: 1.Add corsheaders to INSTALLED_APPS INSTALLED_APPS = [ ... 'corsheaders', ... ] 2.Add CorsMiddleware to MIDDLEWARE LIST MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] 3.Define list of whitelisted Origins from which Request is allowed. CORS_ORIGIN_WHITELIST=['abc.com', 'xyz.com'] By enabling this Cross Origin Request I am not getting CORS Error in Browser for WhiteListed Origins but When I can access my APIs from Origin which mentioned in WhiteListed Origins, it gives me CORS Error in browser but My API Code gets executed means Django is calling my API before checking whether the request is from WhiteListed Origin or not. I want to Block such Cross Origin Request before my API get Called. How can we do it? Note: I have also tried Whitelisting using Signals, but I gets same Result as Whitelisting by CORS_ORIGIN_WHITELIST