Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get the ID for formset form that's generating error?
I have the following tags in my html template so that I can view formset errors. Is there any way of getting the id number of the formset that is generating the error? <div class="alert alert-warning" role="alert"> {{formset.errors}} </div> <div class="alert alert-warning" role="alert"> {% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {{ dict.key }} {% endfor %} {% endfor %} </div> At the moment I get the following, and as I'm doing something complex with the formsets I can't match the errors to forms in the formset: -
Mirror/inherit a module for outputting some fields of the original
Is it possible, in Django, to create a module which is linked via a OneToOneField to another one, which only outputs a single field of its parent? Something like: class Venue(models.Model): # this is the parent venue_name = models.CharField(max_length=50) venue_city = models.CharField(max_length=50) venue_country = models.CharField(max_length=50) class VenueCity(models.Model): # should this be (Venue)? venue_city = # this is the OneToOneField linked to the venue_city field of the parent I need this because it'd be very handy for using it with a select2 field ( django_select2 - limit the returned text to a specific field in module) and I cannot use a @property, only a proper module. -
Unique value error without unique parameter
I'm trying to be able to create Accounts with usernames unique for each Server class Server(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True) class Account(models.Model): server = models.ForeignKey(Server,on_delete=models.CASCADE) username = models.CharField(max_length=100) account_name = models.CharField(max_length=100) password = models.CharField(max_length=50) right now I'm getting the duplicate key value violates unique constraint "zuya_aaccount_username_5f0a17d4_uniq" When I create a non-unique account_name it doesn't show any problem -
Django Rest FrameWork: Combining data from different models before sending response
I have a default user model I created a userprofile model as shown below. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from users.utils.age_validator import MinAgeValidator from django.core.validators import MaxValueValidator, MinValueValidator class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.IntegerField(blank=True, unique=True, null=True) profile_image = models.ImageField(upload_to="proile_image", blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) There is a search view written as shown below class FindUser(ListAPIView): permission_classes = [IsAuthenticated] search_fields = ['username', 'first_name', 'last_name'] queryset = User.objects.all() serializer_class = FindUserSerializer filter_backends = (filters.SearchFilter,) pagination_class = SearchLimitPagination Then I defined serializers to combine data from both models. class UserProfileImageSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('profile_image',) read_only_fields = ['profile_image'] class FindUserSerializer(serializers.ModelSerializer): image = UserProfileImageSerializer(read_only=True) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name','image') The question is similar to the this(Django REST Framework and combining models). But this is not working for me. It is not giving error but a response without the profile data as shown below. { "count": 11, "next": "http://127.0.0.1:8000/user/userprofile/finduser/?limit=5&offset=5&search=a", "previous": null, "results": [ { "id": 43, "username": "pikachu", "first_name": "", "last_name": "" }, } Iam using django 2.7 -
Using Django + MongoDB with unstructured data
I've boradly seen Django used together with MongoDB (with modules like djongo) with structured data using Models. This conflicts one of my requirements: being able to store data in an unstructured way (missing fields, nested objects ...) since the usage of Django Models enforces the specification of all document fields. I thought of encapsulating all the required DB calls in a DAO object but it sounds a bit alien in the Django scene. -
save inputs from 2 forms, through one view into 2 tables django
I am new to django and wanted to know if it is possible to save inputs from 2 forms (displayed on the same html page) into 2 different models through 1 view. Currently, only the first form saves to the table. Form 2 is ignored. If there is anything missing or incorrect, please explain so I understand what my errors are. Here is my View: class SubmitChoiceView(TemplateView): template_name = 'test/test_page1.html' def get(self, request): form1 = SubmitChoiceForm() form2 = SubmitMethodForm() return render(request, self.template_name, {'form1': form1, 'form2': form2}) def post(self, request): form1 = SubmitChoiceForm(request.POST) form2 = SubmitMethodForm(request.POST) if form1.is_valid(): post = form1.save(commit=False) post.user = request.user post.save() if form2.is_valid(): post2 = form2.save(commit=False) post2.user = request.user post.save() return redirect('home') args = {'form1': form1, 'form2': form2} return render(request, self.template_name, args) -
Selectable table with django
My mission here is to add a checkbox in first <td>, so I can select the rows I want and only export those to csv. I got the export function working and everything, but I can't figure out how to sort so it's only those I check, who will be exported. They as well needs to change a boolean from False to True when they've been exported. Let's therefore say, to keep it simple, that I'd like to do X with the chosen rows and change a boolean, on a button click. I got a table looking like this: <table id="example" class="display" style="width:100%"> {% for shipment in object_list %} <tr role="row" class="odd"> <td class="sorting_1">{{ shipment.increment_id }}</td> <td>{{ shipment.full_name }}</td> <td>{{ shipment.street }}</td> <td>{{ shipment.zip_code }}</td> <td>{{ shipment.city }}</td> <td>{{ shipment.telephone }}</td> <td>{{ shipment.email }}</td> <td>{{ shipment.products }}</td> <td>{{ shipment.lost_because_of }}</td> <td>{{ shipment.custom_comment }}</td> <td>{{ shipment.date }}</td> </tr> {% endfor %} </table> My views.py is as following: class ShipmentList(LoginRequiredMixin, ListView): html_title = 'All Shipments' page_title = 'All Shipments' login_url = '/log-in/' redirect_field_name = 'accounts:log_in' model = models.NewShipment paginate_by = 100 # if pagination is desired template_name = 'shipment-list.html' How can I make this happen based on a ListView? Further related code … -
AttributeError: module 'urllib.request' has no attribute 'user'
I am trying to create article so i need to request the current user's information. user = User.objects.get(id=request.user.id) profile = Profile.objects.filter(user=user).get() instance = profile It gives me this error while trying to do it: File "C:\...app\views.py", line 41, in aRTİCLECreateView user = User.objects.get(id=request.user.id) AttributeError: module 'urllib.request' has no attribute 'user' -
AWS S3 Rejects API Call with HTTP 400
I am following this tutorial on getting Django to upload files to AWS S3 asynchronously. The problem is that I am getting this message back from the call that actually uploads the file (the other two come back HTTP 200). <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> The first hunch was to set AWS_S3_SIGNATURE_VERSION = "s3v4" in the settings.py, but that was both futile and superfluous since the version of Boto supports only this signature and so does the region of the AWS. In case you are wondering, the policyData JSON looks roughly as follows: { file_bucket_path: "videos/25/" file_id: 25 filename: "25.mov" key: <key-here> policy: "CnsiZXhwaXJhdGlvbiI6IjIwMjEtMDEtMDFUMDA6MDA6MDBaIiwKImNvbmRpdGlvbnMiOlsKeyJidWNrZXQiOiJ6ZHJhdm9zdC13ZWItZXVyb3BlLXRlc3QifSwKWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJ2aWRlb3MvMjUvIl0sCnsiYWNsIjoicHJpdmF0ZSJ9LAoKWyJzdGFydHMtd2l0aCIsIiRDb250ZW50LVR5cGUiLCIiXSwKWyJzdGFydHMtd2l0aCIsIiRmaWxlbmFtZSIsIiJdLApbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDUyNDI4ODAwMF0KXQp9Cg==" signature: "qECJMNncmLNF6pMKBAQRQa64O3M=" url: "https://<bucket-name-here>.s3-eu-central-1.amazonaws.com/" username: "email@test.com" <prototype>: {…} } The following are the views: import base64 import hashlib import hmac import os import time from rest_framework import permissions, status, authentication from rest_framework.response import Response from rest_framework.views import APIView from django.conf import settings from .models import FileItem class FilePolicyAPI(APIView): """ This view is to get the AWS Upload Policy for our s3 bucket. What we do here is first create a FileItem object instance in our Django backend. This is to include … -
how to get distance in drf api reponse?
I have exactly the same problem as this SO question (Sorry for the link and not writing the whole content again.) Also, I have already implemented the solution given for the same problem. but I am not getting distance in API response. I haven't added distance in serializer fields so definitely, it won't show up in response. But when I add it to fields I get following error. Field name distance is not valid for model Address. I also tried to write a serializer method field but was not sure how to pass the location received in query params to the serializer for comparison. So the question is how the distance is supposed to send in API response? -
Brython and Django Working Together in a App?
I am curious to see what will happen if I both use Brython & Django together? what can you make with it together and what will happen -
Using Python Django how could I do custom function, save to db and return json response
I am new to Python Django so please bare with me. Basically I created a scraper and want to integrate it with API. Starting with Python Django is great and offers easy start, but I am having trouble with the following structure of code: GET request on /test Scrape data Save data to db Return data as a response Basically I am having trouble with saving data of a list in database and returning that data as response. Scraper would be in another python file in utils.py and api would call a function and it would return list of scraped data Does anyone have an example of what I am trying to achieve? -
My bootstrap drop-down items are not clickable (showing)
Anytime I include a link to bootstrap.min.css lying locally in my Django project, my drop-down menu becomes non-clickable. Am a learning Django with no much knowledge of bootstrap. The tutorial am following used cdn to include the bootstrap but I downloaded it manually because of internet connection. Although the downloaded bootstrap is working but the drop-down menu is not working. Can someone help me out.. I can't continue learning at this stage. Thanks in advance. The code is below. {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-"> <meta name="viewport" content="width=device-width, initial-scale=, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" integrity="sha-MCw/SFnGEfJTGXwEOngsVZtNXFoaoApmYmi\ uXoPkFOJwJERdknLPMO" crossorigin="anonymous"> <title>{% block title %}Newspaper App{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" data-toggle="dropdown "href="#" id="userMenu" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> … -
Cannot see the value of text input fied present inside a for loop
I was trying a project where one blog can have multiple blocks, I can see the content written in {{block.content}} Now when I inspect the input field inside the for loop, value attr has some value, but the browser is not showing it, its only because i have kept it inside for loop, any input field outside of the for loop shows value, but the ones inside does not :( You can check my output below the code index.html: <form action="" class="form" enctype="multipart/form-data"> {% csrf_token %} <input type="text" class="form-control" name="title" placeholder="Title" value="{{blog.heading}}"> {% for block in blog.block_set.all %} {{block.content}} <input type="text" class="form-control" value="{{block.content}}" name="block[]" autocomplete="false"> {% endfor %} </form> Ouput: Getting this output Explanation: Blog{ "id": 1, "heading": "Title" } Block{ "id": 1, "blog": #this is the foreign key referencing the above block, "content": "This is content block" } Currently i have added only 1 block, How do I show the value attr on the browser. Thank you in advance :) -
Celery, Django and @shared_task
I am trying to use celery in combination with Django; I have a task in one of my apps and I want to run that with celery. Unfortunately I can not get celery to find the task, and instead I get the following error message in the shell running celery: bash% celery -A webflow worker -l info [2020-05-10 10:47:28,942: ERROR/MainProcess] Received unregistered task of type 'simulation.tasks.unpack_simulation'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[["1b9944d2-f874-42d2-9dce-a0387c431b65"], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (115b) Traceback (most recent call last): File "/home/hove/sleipner/venv/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'simulation.tasks.unpack_simulation' The django project is called webflow and it has one Django app called simulation - all in all the file system look like this: |── manage.py ├── requirements.txt ├── simulation // Django App │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── tasks.py // Module with celery task └── webflow // Django Project ├── asgi.py ├── celery.py // Celery app ├── __init__.py ├── secrets.json ├── … -
What is the significance of fields in Meta Class of UserCreationForm in Django?
I am a Django noob and I have a question I know the people of this beautiful community can help me answer. In my Django project I have created a custom user (using AbstractUser) having a custom field 'number'. The custom user model is named AdminUser. #models.py class AdminUser(AbstractUser): number = PhoneNumberField(blank=False, unique=True, editable=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) REQUIRED_FIELDS = ['number'] objects = AdminUserManager() def __str__(self): return self.username I have assigned a custom UserAdmin for this class #admin.py class CustomUserAdmin(UserAdmin): form = AdminUserChangeForm add_form = AdminUserCreationForm model = AdminUser list_display = ['username', 'first_name', 'last_name', 'number'] list_filter = ['is_superuser', 'first_name'] """Fields when editing users""" fieldsets = UserAdmin.fieldsets + ( ('Primary Contact', {'fields': ('number',)}), ) """Fields when adding new user""" add_fieldsets = UserAdmin.add_fieldsets + ( ('New User Credentials', {'fields': ('number', 'is_staff', 'is_superuser', 'first_name', 'last_name', 'email')}), ) And forms like so #forms.py class AdminUserCreationForm(UserCreationForm): class Meta(UserChangeForm.Meta): model = AdminUser #how does 'fields' below affect the form structure?? fields = ('username', 'email', 'number') class AdminUserChangeForm(UserChangeForm): class Meta: model = AdminUser fields = ('username', 'email', 'number') My question is how do the 'fields' tuple in Meta class in forms.py affect the structure of the creation and change forms? When I remove or add … -
why update a field in related model on save doesn't work in django?
I'm a bigginer to Django. I have the following two models: class Case(models.Model): location = models.CharField() caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE) class StatusRecord(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True, blank=True) caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE) def save(self, *args, **kwargs): Case.objects.filter(pk=self.case_id).update(caseStatus=F('caseStatus')) super().save(*args, **kwargs) I'm trying to update the caseStatus field in the Case Model when user create new record of StatusRecord Model. I have overridden the save function . but the field caseStatus in Case Model never updated. Thank you -
I am getting the following error while querying my module in django. I used Pycharm IDE. Please help me if you know the solution
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Restart Django Application, Deployed on IIS with FastCGI
I've successfully setup Django on IIS with FastCGI, the problem is how to restart Django application after views.py update. I've tried restarting the IIS site and application pool and it does not make any change. -
django rest issue: get_extra_actions with listApiView
I developed a rest API project. But When I run my project on my server I got an error. get_extra_actions I searched google and StackOverflow but I could not found any solution. I got this error File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/rest_framework/routers.py", line 153, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: type object 'CustomerListAPIViewSet' has no attribute 'get_extra_actions' Serializer File class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['name', 'phone_number', 'address', ] Views File class CustomerListAPIViewSet(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer URL file from django.urls import path, include from accounts_app.views import CustomerListAPIViewSet from rest_framework import routers router = routers.DefaultRouter() router.register(r'customer/', CustomerListAPIViewSet) urlpatterns = router.urls -
how to debug this UnboundLocalError at /register/ local variable 'form' referenced before assignment?
from django.shortcuts import render , redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method =='POST': form = UserCreationForm(request.POST) if form.is_vali`enter code here`d(): username=form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('subject_home') else: form = UserCreationForm(None) return render (request,'user/register.html',{'form':form}) UnboundLocalError at /register/ local variable 'form' referenced before assignment -
How can I call a django model function in a graphene resolver?
I have model with getQuality function defined in it. Graphql type is class Person(DjangoObjectType): class Meta: model = PersonModel quality = graphene.String() def resolve_quality(self, info): person = PersonModel.objects.get(pk = self.id) return person.getQuality() This might work but I will be querying the same object twice. How can I call a model function in a resolver? -
Django sort query by related model
I am trying to sort a query set based on a related model in a django function view. My models are: class Musician(models.Model): full_name = models.CharField(max_length = 70) def __str__(self): return str(self.full_name) class Instrument(models.Model): instrument_name = models.CharField(max_length = 50) def __str__(self): return self.instrument_name class Member(models.Model): musician = models.ForeignKey(Musician, on_delete = models.CASCADE) band = models.ForeignKey(Band, on_delete = models.CASCADE) def __str__(self): return str(self.musician) class Role(models.Model): instrument = models.ForeignKey(Instrument, on_delete = models.CASCADE) member = models.ForeignKey(Member, on_delete = models.CASCADE) def __str__(self): return str(self.member) + ' | ' + str( self.instrument) class Album(models.Model): album_name = models.CharField(max_length = 50) band = models.ForeignKey(Band, on_delete = models.CASCADE) role = models.ManyToManyField(Role) def __str__(self): return self.album_name + ' | ' + str( self.band) My function looks something like this (passing the album id into the function): def album_view(request, alb_id): album = Album.objects.get(id= alb_id) band = album.band allroles = album.role.all() context = { 'band' : band, 'album' : album, 'artists' : allroles, return render(request,'bandapp/album_view.html', context) allroles is the query I am having issues with. It returns the Role objects (as expected), however, this list is difficult to iterate over in the template. I essentially want to end up with (within the template) Artist One | Guitar, Artist One | Vocals, Artist … -
django export csv issue while try to export the cvs
class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field = ['organisation', 'organisation_id', ] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(queryset) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field]) return response export_as_csv.short_description = "Export Organisation" @admin.register(Show) class ShowAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = ['organisation_id'] def organisation_id(self, obj): return obj.organisation.named_by actions = ['export_as_csv'] In my csv organisation_id field is showing organisation_id instead of the actual mail. how can i export the right data data? Thank you very much please have a look into my code -
There is an error while using perform create in django rest framework?
serializers.py from rest_framework import serializers from question.models import Question, Quiz, Answer class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ['id', 'text', 'is_correct'] class QuestionSerializer(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = Question fields = [ 'id', 'label', 'order', 'answers' ] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id','user', 'name', 'questions_count', 'questions'] read_only_fields = ['user'] def create(self, validated_data): questions = validated_data.pop('questions', None) quiz = Quiz.objects.create(**validated_data) if questions is not None: for question in questions: answers = question.pop('answers', None) question = Question.objects.create(quiz=quiz, **question) if answers is not None: for answer in answers: Answer.objects.create(question=question, **answer) return quiz def update(self, instance, validated_data): questions_data = validated_data.pop('questions', None) questions = (instance.questions).all() questions = list(questions) instance.name = validated_data.get('name', instance.name) instance.questions_count = validated_data.get('questions_count', instance.questions_count) instance.save() if questions_data is not None: for question_data in questions_data: answers_data = question_data.pop('answers') question = questions.pop(0) answers = (question.answers).all() answers = list(answers) question.label = question_data.get('label', question.label) question.order = question_data.get('order', question.order) question.save() if answers_data is not None: for answer_data in answers_data: answer = answers.pop(0) answer.text = answer_data.get('text', answer.text) answer.is_correct = answer_data.get('is_correct', answer.is_correct) answer.save() return instance views.py from rest_framework.authentication import SessionAuthentication from rest_framework.views import APIView from rest_framework import generics, mixins, permissions from question.models import Quiz, Question, Answer from .serializers import …