Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any added advantage of using djangorestframework over JsonResponse?
I am new to Django and API creation. I am trying to figure out if it is better to use djangorestframework or just use JsonResponse. I got the suggestion of djangorestframework from Digital Ocean's tutorial but also found out about JsonResponse, which seems simpler given that I don't have to install another package. Goal: I would like to be able to provide user information for both web and mobile applications. I see that there are some reasons provided on this post for djangorestframework, which I pasted below for posteriority. The common cases for using DRF are: 1)You're creating a public-facing external API for third-party developers to access the data in your site, and you want to output JSON they can use in their apps rather than HTML. 2)You're doing mobile development and you want your mobile app to make GET/PUT/POST requests to a Django backend, and then have your backend output data (usually as JSON) to the mobile app. Since you don't want to pass back HTML to the mobile app, you use DRF to effectively create a REST API that your mobile app can call. 3)You're creating a web app, but you don't want to use the Django templating … -
The Request parameter for views function in Django greys out
No matter what I try in vs code the request is always greyed out. I'm following the Django tutorial and I get a 404 when loading the server because the index function can't be called cause the parameter is greyed, This works perfectly fine in Pycharm, but not vs code. Any solutions? def index(request): return HttpResponse("Hello, world. You're at the polls index.") -
View_by_Course_list() missing 1 required positional argument: 'course_code_and_name'
I have used Django to develop a web app. When I tried to pass a string in the url, error occurs: View_by_Course_list() missing 1 required positional argument: 'course_code_and_name' view.py: @csrf_exempt def View_by_Course_list(request, course_code_and_name): if request.method == 'POST': ... url.py: path('View_by_Course_list/$',views.View_by_Course_list, name='View_by_Course_list'), HTML: <a href="{% url 'bms:View_by_Course_list' %}?course_code_and_name={{course_for_select}}" id=" {{course_for_select}}" onclick=""> {{course_for_select}}</a> I got the error: k return view_func(*args, **kwargs) TypeError: View_by_Course_list() missing 1 required positional argument: 'course_code_and_name' How should I correct it? -
ImproperlyConfigured - UserRegisterView is missing a QuerySet. Define UserRegisterView.model, UserRegisterView.queryset, or override
sorry to be a bother. I have just created a user login app for a blog site, but I keep getting this error whenever I try to go to the registration page: "UserRegisterView is missing a QuerySet. Define UserRegisterView.model, UserRegisterView.queryset, or override UserRegisterView.get_queryset()." Below is my view.py file from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_Class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('login') I'm not entirely sure where I need to go from here. Any help/explanation would be really helpful. -
Django project on Heroku processing long requests. Background Jobs and Queueing
I have a Django project on Heroku, The project has an endpoint that accepts the client's request and sends it to other external services, the approximate response of which is from five seconds to two minutes. As known, if the process takes longer than 30 seconds, the platform will return an error h12 request timeout (and in general, the answer to the request must be given as soon as possible). I studied Background Jobs and Queueing and realized that I would need such instruments as RQ and Celery. In general terms, I understand the concept of each individual topic, but I do not really understand how to apply this to the project and whether I correctly assembled a bunch of tools for my task. Also, I don't understand how I can save the response of external services and I will need to inform the initiator of the request to my server (client request) about the result. I would be grateful for any hints, suggestive answers, and helpful resources. Thank you -
I'm unable to get data from RESTful API using DRF and REACT
In the backend I am using permission_classes = [IsAuthenticated], I'm logged in running django server on port 8000 using rest framework interface and then I m trying to fetch data from port 3000 . So I want to know why there is error on port 8000 terminal Forbidden: /api/drive-links/ [04/Jun/2021 18:11:01] "GET /api/drive-links/ HTTP/1.1" 403 58 Django Rest Framework API HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "title": "Clip", "link": "https://drive.google.com/file/d/12345" } ] RESTdataSource.js contains import Axios from "axios"; // Config global defaults for axios/django Axios.defaults.xsrfHeaderName = "X-CSRFToken"; Axios.defaults.xsrfCookieName = "csrftoken"; export class RestDataSource { constructor(base_url) { this.BASE_URL = base_url; } GetData(callback) { this.SendRequest("get", this.BASE_URL, callback); } async SendRequest(method, url, callback) { callback( ( await Axios.request({ method: method, url: url, }) ).data ); } } And Isloated Table contains import React, { Component } from "react"; import { RestDataSource } from "./RESTdataSource"; class IsolatedTable extends Component { constructor(props) { super(props); this.state = { DriveLinks: [], }; this.dataSource = new RestDataSource( "http://localhost:8000/api/drive-links/" ); } render() { return ( <table className="table table-sm table-striped table-bordered"> <thead> <tr> <th colSpan="5" className="bg-info text-white text-center h4 p-2"> DriveLinks </th> </tr> <tr> <th>ID</th> <th>Name</th> <th>Drive Links</th> <th></th> </tr> </thead> … -
Creating custom Django encrypted field with Fernet
I'm trying to create a django custom encryption field using Fernet. The libraries I found for doing it automatically seems to be outdated/non compatible with Django>3.0 In this thread I found the following code: import base64 from django.db.models import CharField from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from core import settings class SecureString(CharField): salt = bytes(settings.SECURE_STRING_SALT, encoding="raw_unicode_escape") kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(settings.SECRET_KEY.encode('utf-8'))) f = Fernet(key) def from_db_value(self, value, expression, connection): return str(self.f.decrypt(value), encoding="raw_unicode_escape") def get_prep_value(self, value): return self.f.encrypt(bytes(value, encoding="raw_unicode_escape")) It seems to work for the encoding part (if I check the database field with a manager program, content is show as a sort of chinese characters), but not for decoding. Everytime I save a record in Admin, this error is triggered (although saved in database): raise TypeError("{} must be bytes".format(name)) TypeError: token must be bytes Aren't supposed to be already as bytes in the database record, due to get_prep_value code? The same error happens when trying to list records in admin (accessing the reading function). How can I solve this? I am using SQL Server as database (in case it might be relevant). -
Access-control-allow-origin header not recognised in browser
We've aded some javascript code to a web-page which needs to POST information to our Django-backend for analysis. In the head of the site, we've added a line like this: <script src="https://somedomain.com/track/" type="text/javascript"></script> In turn it will fetch the complete code and do what it needs to. However, I'm running into an issue with Access-Control-Allow-Origin. I've added a custom middleware to the Django-project that looks like: class CorsMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) response["Access-Control-Allow-Origin"] = "*" return response I can try out the url and its headers via requests: import requests resp = request.get resp = requests.get('https://somedomain.com/track/') print(resp.headers['Access-Control-Allow-Origin']). # Prints "*" Those work - yay. But when I'm trying this out on the actual website, I keep getting the error [Error] Failed to load resource: Origin https://www.websitedomain.com is not allowed by Access-Control-Allow-Origin. What am I missing? -
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()