Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change django application basepath with gunicorn
I want to launch my django app with basepath=/api, every url should start with /api, something like. urlpatterns = [ path("/api", include([ # all my urls ])) ] But I really don't want to do this in the code Is it possible to do this using gunicorn? -
Can't override drf nested serializer CREATE
I am trying to create an instance of Product class with postman but nothing works for me. I have tried just to add one category, also give a list of categories with category_ids, still no success. Can anyone point, what am I doing wrong? I have searched everywhere but couldn't find a solution. Why am I getting this keyError? models: class Category(models.Model): name = models.CharField(max_length=80) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): category = models.ManyToManyField(Category, blank=False) name = models.CharField(max_length=100) description = models.TextField(max_length=250) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(default=0) class Meta: ordering = ("name", ) def __str__(self): return self.name serializer: class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(many=True, required=False) category_ids = serializers.PrimaryKeyRelatedField(source='category', many=True, queryset=Category.objects.all()) class Meta: model = Product fields = ( "id", "name", "category_ids", "category", "description", "price", "quantity" ) def create(self, validated_data): categories = validated_data.pop('category') product = Product.objects.create(**validated_data) Category.objects.create(product=product, **categories) return product views: class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def perform_create(self, serializer): serializer.save(created_by = self.request.user) def perform_update(self, serializer): serializer.save(updated_by = self.request.user) def perform_destroy(self, instance): instance.deleted_by = self.request.user instance.deleted_at = timezone.now() instance.save() error: Exception Type: KeyError Exception Value: 'category' -
Couldn't import Django. Are you sure it's installed and available?
I built a django app. Now I am trying to run the project on local. then i got the issue. -
DRF Serializer is returning empty dictionary while doing serializer.data
I have a serializer like following: class LoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255, write_only=True) password = serializers.CharField(max_length=255, write_only=True) def validate(self, validate_data): username = validate_data.get('username', None) password = validate_data.get('password', None) if username is None: raise serializers.ValidationError({'error': 'Email is required!'}) if password is None: raise serializers.ValidationError({'error': 'Password is required!'}) user = authenticate(username=username, password=password) token = Token.objects.get_or_create(user=user) return {'username': user.username, 'token': 'token'} and a view for this: class LoginAPIView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) # this prints {} return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) I don't know what is wrong here, do I have to return validate_data? -
Rendering DataFrame to html using dynamic column names
I want to render a pandas dataframe on html as a table. The problem I am facing is that the column names are dynamic. Here is what I am doing in views. def index_1(request): df = pd.read_csv("my.csv") columns = df.columns json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = { 'dataframe': data, 'columns': columns } return render(request, "positions/options.html", context) Below is the relevant part of my html code. {% block content %} <table id="positions-table"> <thead> <tr> {% for i in columns %} <th>{{i}}</th> {% endfor %} </tr> </thead> <tbody> {% for i in dataframe %} <tr> {% for j in columns %} <th>{{i.j}}</th> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endblock %} I am able to add the column names dynamically but when I try to populate the table using i.j that's using i'th row and j is the column name, it returns a blank table. How can I populate my table dynamically without having to specify column names? -
Django - signing up multiple user-types with Dj-Rest-Auth
Would like some advice about authentication via Rest API, especially signing up with multiple user-types. I am quit new to Djangorestframework so hope to find some help. I Think Dj-Rest-Auth because 'django-rest-auth' is not supported anymore. Is this the right choice? This is how I modelled my User, Student and Teacher class models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) .... class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) .... I would like to sign-up either as a student or as a teacher. So I have to set the 'is_student' field or 'is_teacher' field direct after signing up. What is the best approach and has to be changed or added in the code to make this work? Best regards, Martijn -
Issue getting model name from ForeignKey
I have two models: Exercise and UserExercise class Exercise(models.Model): options = ( ('run', 'run'), ('jog', 'jog'), ('lift', 'lift'), ('yoga', 'yoga'), ) name = models.CharField(max_length=50, choices=options, unique=True) def __str__(self): return str(self.name) class UserExercise(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.ForeignKey(Exercise, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False, default=0) calories_burned = models.FloatField(null=False, default=0) def save(self, *args, **kwargs): self.person_of = self.person_of self.name = self.name self.quantity = self.quantity self.calories_burned = self.calories_burned super(UserExercise, self).save(*args, **kwargs) def __str__(self): return str(self.name) The problem is when I try to create a new UserExercise from a dropdown form containing the choices in Exercise, I can't get the exercise name to be any other than None. if request.method == 'POST': name = request.POST.get('name' 'False') quantity = request.POST['quantity'] calories_burned = request.POST['calories_burned'] exercise = UserExercise.objects.create(person_of=request.user, name=name, quantity=quantity, calories_burned=calories_burned) -
update context in get_context_data
Hi I am trying to use get_context_data succesively by lazy_reverse the page. def get_context_data(self, **kwargs): context = super(PublicationCreate, self).get_context_data(**kwargs) context['files'] = UploadedFile.objects.filter(pk=self.kwargs['pk']) return context How do I save the queryset and concatenate it later on? -
Product Variations in Django: How to handle variant combinations?
I want to implement product variants for size and color. My desired output is: Product #1: Size: Medium, Color: White - Price $10.99 Product #1: Size: Large, Color: White - Price $11.99 Product #1: Size: Medium, Color: Black - Price $11.50 How can I combine color and size into one variant for customers to select. This is the issue I'm dealing it. Eventually, I'll Use Ajax to disable the selected color and size labels that aren't a variant combination. Here are my Models class Products(models.Model): product = models.CharField(max_length=120) created = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Color(models.Model): name = models.CharField(max_length=24) def __str__(self): return str(self.name) class Size(models.Model): name = models.CharField(max_length=24) def __str__(self): return str(self.name) class VariantProduct(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) name = models.CharField(max_length=256) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.PositiveIntegerField(default=0) active = models.BooleanField(default=True) def __str__(self): return str(self.color).upper() + ', ' + str(self.size) + ' - ' + str(self.product).capitalize() class Meta: verbose_name_plural ='Variant Products' HTML {% for product_variation in product_variations %} <input type="radio" name="color-radio" id="color-{{ product_variation.color }}" value="{{ product_variation.color }}"> <label style="background-color:{{ product_variation.color }};" for="color-{{ product_variation.color }}"></label> {% endfor %} {% for product_variation in product_variations %} <input type="radio" name="size-radio" id="size-{{ product_variation.size }}" value="{{ product_variation.size }}"> … -
Django Quiz App, getting previous question
I am trying to create a quiz portal and learning on the go. I am using https://github.com/tomwalker/django_quiz/ as a starting point and adding features on top that. I wanted to add a feature to get previous questions, so I added a button <form action="" method="POST" class="shadow p-4 mb-4 bg" id="question-form"> {% csrf_token %} <input type="hidden" id="duration" value="{{quiz.durationtest}}"> <input type="hidden" id="quizid" value="{{quiz.id}}"> {% if progress %} <input id="currnumb" type="hidden" value ="{{ progress.0|add:1 }}"> <input id="totalques" type="hidden" value ="{{ progress.1 }}"> <div class="countdown float-right" style="font-weight:900; font-size:16px;"></div> <p class="lead">{% trans "Question" %} {{ progress.0|add:1 }} {% trans "of" %} {{ progress.1 }}</p> {% if question.questionmarks %} <p class="lead"><strong>Marks: {{question.questionmarks}}</strong></p> {% endif %} <div class="progress mb-5"> <div class="progress-bar" id ="progress-bar" role="progressbar" > </div> </div> {% endif %} {% if question.figure %} <img src="{{ question.figure.url }}" alt="{{ question.content }}" /> {% endif %} <input type=hidden name="question_id" value="{{ question.id }}" class="question_id"> <div class="row"> <div class="col-md-12 column " oncontextmenu="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false " ondragstart="return false" onselectstart="return false"> <div class="panel panel-primary"> <div class="panel-heading "> <h3 class="panel-title mb-3" style="pointer-events: none;" > {% autoescape off %}{{ question.content }}{% endautoescape %} </h3> </div> <div class="panel-body "> <ul class="list-group"> {% for answer in form.answers %} <li class="list-group-item quiz-answers"> … -
how to manage admins in a django website?
i'm trying to make a realtor website , every real estate has an owner , and its possible to have multiple admins class RealEstate(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) admins = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='managers') code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) real_estate_name = models.CharField(max_length=40,unique=True) when a user register as a realtor there is an option to fill out RealEstate form , to create his/her real estate profile , and he/she can add several admins to his/her RealEstate , whenever a real estate owner adds a new admin to his/her real estate profile , it has to show add new post option in the navbar , but it only show when the user request is owner the real estate this is the template <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if request.user.realestate %} <a class="add-new" href="{% url 'new-post' %}">add new post</a> {% endif %} </div> what tag should i use to display add new post whenever the logged in user is a member of a real estate ? thank you .. -
Remove null fields from within an array in a Django Rest Framework response
I have a question, which is simiar to this one. I'm using django-rest-framework to build an API, using ModelSerializer to return data from a model. The models holds Arrays (using the PostgreSQL ArrayField). models.py class FashionData(models.Model): image_urls_norm = ArrayField(models.TextField(null=True), null=True) serializers.py class ProductLineSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(ProductLineSerializer, self).to_representation(instance) return OrderedDict([(key, result[key]) for key in result if result[key] is not None]) class Meta: model = FashionData fields = ('image_urls_norm', ) (I'm overriding the to_representation function to remove any null fields from the response as outlined in Simon's response to the original question above) output "image_urls_norm": [ "https://somewebsite.com/image.jpg", null, null, null ], The first item in the array is always going to be populated, but the subsequent items can be null My question is, how can I remove the null items from array in the API response? -
Column not updating in django?
I am trying to update user data in Django but it's not updating. Code : customer = Customer.objects.get(email=request.POST["customer_email"]) agent = Agent.objects.get(email=request.POST["customer_agent"]) if request.POST.get("verify"): agent.no_of_verified_customer += 1 agent.save() import django.utils.timezone as tz customers.verified = True #this particular field is not updating customer.verified_on = tz.now() customer.verified_by = request.session["email"] customer.save() -
CSRF errors in Django Fargate Docker when using HTTPS Application Load Balancer
I have implemented a Django web app on AWS Fargate using Docker behind Application Load balancers. When I try to log in to the web app I get the following: Error 403 CSRF verification failed. Request aborted. Environment: I am using Application Load Balancer (ALB) as per the best practices of AWS. The ALB also has a TLS certificate to properly handle HTTPS when I run multiple instances of the web app. I tried to resolve the issue by forcing stickiness of the ALB targets assuming that the Round-Robin lands the requests on different servers. I also reduced the number of docker instances to one (so there is no Round-Robin). None of this made any difference. I managed to log in (to get CSRF to work well) was when I connected directly to a docker instance (no Load Balancer) and when I used only HTTP on the Application Load Balancer - disabling redirect to HTTPS. This leads me to believe that the issue is between the HTTPS part of the load balancer and the Django web app. Disabling HTTPS is not production ready, so I am back at square one. I saw a similar question posted here, without answers: django … -
Why is VSCode intellisense type hints different for these 2 Django model objects?
In the views.py after importing the Video model I am testing how intellisense works in VScode. This is the views.py from django.shortcuts import render from .models import Video # Create your views here. video1: Video = Video.objects.get(id=1) video2: Video = Video.objects.filter(id=1).first() this is the models.py: class Video(models.Model): ''' info about videos ''' video_id = models.TextField(blank=True, null=True) title = models.TextField() description = models.TextField() tags = models.TextField() is_uploaded = models.BooleanField() date_uploaded = models.DateField(null=True) filename = models.TextField() thumbnail_filename = models.TextField() When I start typing I get this for video1 which is from video1: Video = Video.objects.get(id=1): As you can see it offers model fields but for video2 which is from video2: Video = Video.objects.filter(id=1).first(): it doesn't offer model fields. Why is that and how can we fix it? -
external SQL to Django Models
I'm trying to figure out how to convert an external SQL database (that keeps updating) to models in Django. Any help would be greatly appreciated! I have an SQL database that gets updated every day. I have a Django web app that displays information from the SQL database and I'm trying to apply a filter (FilterView) to the displayed information but I need the information to be saved as models for that, right? I'm still pretty new to Django, thanks in advance for any help! -
I can't import css file using 'static' template in django
I'm trying to develop my first web application using Django, so the site looks like that: Site without changes On the other hand, I would like to apply some changes and put it in a CSS file called: cabecalho.css cabecalho.css file (with the changes) - path: (project/static/css/cabecalho.css): <style> body { font-family: Segoe UI; } .logo { float: left; } .logo img { width: 250px; padding: 20px; } .menu { float: right; padding: 40px; font-size: 15pt; } .menu a { margin-left: 15px; margin-right: 15px; } .bemvindo { clear: both; padding: 0 20px; } </style> These changes make the site look like that: Site with CSS changes In my HTML file called cabecalho.html, I tried to import with the line code: 1 try: <link rel="stylesheet" href={% static 'css/cabecalho.css' %}/> 2 try: <link rel="stylesheet" type="text/css" href={% static "css/cabecalho.css" %}/> 3 try: <link rel="stylesheet" type="text/css" href="css/cabecalho.css"> In this way, nothing happens! HTML file (cabecalho.html) - path: (project/templates/django/cabecalho.html): <!DOCTYPE html> {% load static %} <!-- Nova linha que carrega os arquivos estáticos --> <html> <head> <title>Django Form Exemplo</title> <link rel="stylesheet" href={% static 'css/cabecalho.css' %}/> </head> <body> <div class='logo'> <img src="{% static "images/logo.png" %}" alt="Logo da Hacked" /> </div> <div class='menu'> <a href="/app/sobre/">Sobre</a> <a href="/app/sair/">Sair</a> </div> … -
Polymorphic relationships in Django models
I am a newcomer in the Django framework and need some help. How can I create a polymorphic relationship between models? I am building an api in which I need to have a model that belongs to several models at once, let's say we have a comment model and I want it to belong to any model that can be commentable, in this case, the post and video models, but at the same time I want to have some referential integrity, I've tried with The contenttypes framework from Django and I get what I need but it allows me to create comments to videos or posts that don't exist, I've also tried with the django-polymorphic package together with django-rest-polymorphic, in this case I create a commentable model that extends from PolymorphicModel and the post and video models inherit from commentable, Doing it this way I get referential integrity but I see that the autoincrementable id is affected by the other models that also inherit from commentable, for example, if I create a post it is assigned the id 1, when I create a video it is assigned the id 2 even though they are two different tables, this does not … -
WSGIRequest body attribute contains two characters "\n" in place of newline
Noticed after upgrading Python3.7 + Django3.1, in attribute _request.body, newline was converted to two characters of "\n". PyCharm hint shows that _request is an object in class of WSGIRequest. As the partial log shows below, the text record contains "\n" in place of the newline. I suspect this is related to encoding of the new version of Python, and the issue doesn't exist in Python2.7. Any pointers will be highly appreciated. Partial logs: [09/Dec/2020 08:22:37] INFO [application.soap.views:34] b'<?xml version="1.0" encoding="UTF-8"?>\n<env:Envelope ... >...</env:Envelope>\n' [09/Dec/2020 08:22:37] INFO [application.soap.views:28] <HttpResponse status_code=200, "application/soap+xml"> More details of source code: >>> in file main_url.py: ... urlpatterns = [ url(r'^validation/$', soap_views.receive_validation_request, name='validation_request'), ... >>> in file view.py: ... def validate_request(_request, is_fulfillment=False): ... logger.info(_request.body) ... ... -
send message from bot to direct message after typing /slash command
I'm trying to make SlackBot and if I call him in some channel it works fine but when I call him (type slash-command) in any direct message I receive "The server responded with: {'ok': False, 'error': 'channel_not_found'}". Here is some part of my code: if slack_command("/command"): self.open_quick_actions_message(user_id, channel_id) return Response(status=status.HTTP_200_OK) def open_quick_actions_message(self, user, channel): """ Opens message with quick actions. """ slack_template = ActionsMessage() message = slack_template.get_quick_actions_payload(user=user) client.chat_postEphemeral(channel=channel, user=user, **message) Here are my Event Eubscriptions Here are my Bot Token Scopes Can anybody help me to solve this? -
Deploying python API heroku
I've deployed my python API which worked on localhost to heroku. Whenever I do any requests to API it doesn't work. Why is this happening? Site link: http://testapipythonf4.herokuapp.com/api/offers/ OperationalError at /api/offers -
Apply concurrency to allow only user to edit a document at a time
I would like to implement a simple document editor web app, where only one user can be editing one document at a time. Ie., if another user views that document, he will only be able to read it, but won't be able to modify it, until the first user finishes editing it. What would be the best approach for this? This looks like a concurrency problem -- what tools do Python 3 and Django 3 provide in order to tackle this in the best possible way? -
Django custom user model. Deleting user from admin panel
I have been experimenting with creating a custom user model in django. Everything seems to work fine, however, some of the admin panel commands seem to be erroring out. For example. I can delete a user through code using user = User.objects.filter(email="j@j.com").first().delete(). However, if i try to delete the user through the admin panel I get the following error. Internal Server Error: /admin/account/user/ Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File … -
I am heaving trouble in uploading the static files to the Django app. What i am missing i don't understand
{% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block content %} Template homepage {% endblock %} -
List multiple objects in Django UpdateView
Is there a way to update multiple objects at once in Django updateview. I'm trying to do this, when I put UpdateView nothing appears, but I put ListView they appear. Here's the View. class UpdateAllUsers(UpdateView): model = User context_object_name = 'users' paginate_by = 5 fields = ( 'first_name', 'last_name', 'job_title', 'twitter' ) template_name = 'users/edit-users.html' How do I get them listed as in the picture below in update mode?