Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a Django FormSet accept m2m but store them as multiple FK records?
I need to provide a test for students, but some questions accept multiple answer. Can I make it create multiple records for storing multiple answers instead of using a M2M? e.g. if a student select A and B for a question, would act like the following: StudentAnwer.objects.create(question=question, answer=answer_a) StudentAnwer.objects.create(question=question, answer=answer_b) formsets.py from django import forms StudentAnswerFormSet = forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], formset=forms.BaseInlineFormSet) models.py class Question(BaseModel): title = models.CharField(max_length=250) is_multiple = models.BooleanField(default=False) class StudentAnswer(BaseModel): student = models.ForeignKey(Student, related_name='answers') question = models.ForeignKey(Question, related_name='student_answers') answer = models.ForeignKey(Answer, related_name='student_answers') views.py from formtools.wizard.views import SessionWizardView class StudentWizardView(SessionWizardView): ... def get_answer_form(self, step=None, data=None, files=None): ... question_list = get_question_list() return forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], extra=len(question_list), formset= forms.BaseInlineFormSet) def get_form(self, step=None, data=None, files=None): form = super(StudentWizardView, self).get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current if step == self.STEP_ANSWER: initial_dict = self.get_form_initial(step) prev_form_data = self.get_cleaned_data_for_step(self.STEP_PROFILE) form = self.get_answer_form(step, data, files) for form_index in range(len(initial_dict.keys())): question = initial_dict[form_index]['question'] answer_list = question.get_answer_list() if question.is_multiple: form.forms[form_index].fields['answer'] = ModelMultipleChoiceField(queryset=answer_list, widget=CheckboxSelectMultiple) else: form.forms[form_index].fields['answer'].widget.choices.queryset = answer_list I'm trying to avoid M2M for making it easier to display the possible answers per question on the template. {{ wizard.management_form }} {{ wizard.form.management_form }} {% … -
Getting Failed to construct 'Worker' with JS worker file located on other domain when using react-pdf
I am using react-pdf to render a PDF file inline on my Django/Wagtail website. To do this, I create a div in my HTML template with ID react, and I run a file called index.js which is a pretty straightforward React file that creates a DocumentViewer element and uses ReactDom to render it to the div with id 'react'. I get an error when running my website on production when loading the worker file from my main bundle, specifically an error about how script worker.js cannot be accessed from origin 'example.com' The exact code is not really relevant (although I can post it if necessary, but the thing that's giving me issues is loading the react-pdf worker. I use the following import statement as the docs recommend: import {Document, Outline, Page} from 'react-pdf/dist/entry.webpack'; I then use webpack to bundle and minify this file, with the following webpack.config.js: var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './project/app_name/static/js/index.js', output: { path: path.resolve('./project/app_name/static/bundles/'), publicPath: '/static/bundles/', filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', … -
Django Permission Required
I'm trying to check permissions for some api requests. I've already set auth users and auth_user_user_permissions and auth_permissions tables like view_company add_company bla bla, but problem is not that. The problem is when i'm trying yo use decarator which @permission_required('api.view_company', raise_exception=True) it said to me AttributeError: 'CompanyDetailView' object has no attribute 'user' Most probably it's looking for user because its gonna check user_permission is it available to view companies or not but my view which i declared in urls (path('companies//', CompanyDetailView.as_view()),) has not have user object thats why error message returned attribute error, how can i solve this, thanks a lot I tried to set example user in view class in the beginning it worked because view was looking for user object, i can not use that way because every request has different user import rest_framework from rest_framework import status from django.contrib.auth.models import User from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.decorators import permission_required class CompanyDetailView(APIView): @permission_required('api.view_company', raise_exception=True) def get(self, request, id): try: request_data = {} request_data['request_method'] = request.method request_data['id'] = id companies = Company.objects.get(id=id) status = rest_framework.status.HTTP_200_OK return Response(companies, status)``` bla bla bla my error message was : AttributeError: 'CompanyDetailView' object has no attribute 'user' -
Generate Django Password
In my Postgres DB, there is a password column, which has passwords stored in the format argon2$argon2i$v=19$m=512,t=2,p=2$Z1BlYkltRjNhakFE$1cgxZNRetdjoCYwBrjAICA Is there a way to generate this password manually? I am not a backend developer and hence not much idea about how these things are usually handled. -
background-image not showing up in Django
I have an accounts app, and I have an icon in accounts/static/accounts/images/mail-icon.png that I want to use as a background-image in my CSS, and in my template I have: <a id="mail-icon" href="{% url 'register' %}">Registration via Email address</a> In my register.css (which is located in accounts/static/accounts/css/register.css I have: #mail-icon { background-image: url(../images/mail-icon.png); } When I check Network tab of my developer tools, I see that I'm getting a 200 or 304, however the image is not appearing for some reason. I have tried to restart the server but had no success. The image is appearing if I use: <img src="{% static 'accounts/images/mail-icon.png' %}"> What could be the issue? -
Vanilla Python for web development?
I'm about to start a project, I want to do this in Python, I'll been working with PHP an Js for a while so I want to change and learn new language/framework. I know a little of Python and I started to learn Django, but I want to know if there is a way to build a simple program in vainilla Python to fully understand the concepts and how Python work for web development. Like when you work in PHP that you usually develop a program in MVC and after that you use a framework. -
Entire Application in Django shuts down with single error
I am new to Python and django , I was a php developer earlier. My problem here is Entire Application in Django shuts down with single error. for example i start my website with "python3 manage.py runserver 0.0.0.0:8000" example:-- i have two pages home and register 1) if i make error in register page code(register.py) , It shuts down home page too. Is there a way to prevent that as in php one page do not effect other. 2) how to work in django with team one errors full team hangs. 3) How to work with live working websites things may become too risky. also i am not able to find article related to this. kindly help -
How to make a robots.txt on Django
I've seen other answers here, but they aren't really helpful, which is why I am asking. I tried the django-robots framework as well, but it gives me an error when i just put 'robots' in my INSTALLED_APPS INSTALLED_APPS = [ 'index.apps.IndexConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', ] -
cant query from django where field name has double underscore
Cant query from django where field name has double underscore. This is because in the django query language __ has its own meaning so how can i query a field whose actual name is "my__fyeild__name" ? template.fields.filter(my__fyeild__name="aaa") -
What is purpose of routes.js in Django?
I am developing web application using django latest version & I have reference of old website of our company. There are routes.js which is responsible for routing urls. .when('/test/web_test',{ templateUrl: '/test/web_test/', controller: 'testCtrl', resolve: loader(['test/js/test.js?v=1.2']) above kind of url routing kind of new to me. how does above kind of url patterns works & when django calls such routes.js file. -
Django templates - add a block to an imported file though an extended one
Yes, the title is confusing, so here I'm gonna try to put an example base.html: (I omit the non related code) <body class=""> <div class="wrapper"> {% include "includes/sidebarDashboard.html" %} <div class="main-panel"> {% include "includes/headerDashboard.html" %} </div> {% block content %} {% endblock %} </div> </body> headerDashboard.html <div class="container-fluid"> <div class="navbar-wrapper"> <div class="navbar-toggle"> <button type="button" class="navbar-toggler"> <span class="navbar-toggler-bar bar1"></span> <span class="navbar-toggler-bar bar2"></span> <span class="navbar-toggler-bar bar3"></span> </button> </div> {% block breadcrumb %} {% endblock %} </div> </div> So having this, now I want to extend the base and, in that file, try to add the breadcrumb block also. Something like: important-information.html {% extends 'includes/base.html' %} (some loads and styles and scripts..) {% block breadcrumb %} <a class="navbar-brand" href="#">Data Management</a> {% endblock %} {% block content %} (the content) {% endblock %} The result of this is just get the block content filled, but I need to get filled the block breadcrumb too from the same file. Because if not, for every change in any of the 10+ files that extends the body, I have to make changes on the header too and I want to manage everything from the same file. Also I think is always good to ask if what I'm … -
How to update requirements?
I would like to know how to update outdated requirements with the multi requirements files setup that cookie cutter uses (base, local, etc...) ? If i launch a "pip freeze" it will write the requirements in a single file. It will not dispatch them in correct files Do I miss something ? -
Image not uploading to the folder
I want to upload an Image, but it is not showing in the media folder. This is the HTML template <form class="form" action="/profile/edit/{{user.id}}" method="post" enctype="multipart/form-data" style="padding-top:20px;"> {% csrf_token %} <input type="file" class="btn " name="pro_pic" accept=".png, .jpg, .jpeg"> <button type="submit" class="btn text-success" name="pr_pic" id="pic_submit"><i class="fas fa-check"></i> Submit</button> </form> Models.py class UserDetails(models.Model): user_id = models.IntegerField(unique=True) bio = models.TextField(null = True) profession = models.CharField(max_length = 100, null = True) city = models.CharField(max_length = 100, null = True) country = models.CharField(max_length = 100, null = True) img = models.ImageField(upload_to='pic_user', null = True) views.py def edit (request, id = '') : if request.user.is_authenticated == True : if request.method == 'POST' : # MyModel.objects.filter(pk=some_value).update(field1='some value') if request.POST.get('pr_pic') == '' : post_image = request.FILES['pro_pic'] # pic = UserDetails.objects.filter(user_id = id).update(img = post_image) # UserDetails.objects.filter(user_id = id).update(img = post_image) pic = UserDetails.objects.filter(user_id = id) pic.img = post_image pic.save() Whenever an user is created his user_id gets updated in another table(UserDetails model), and the fields are null. But in the HTML ive an option to upload image later (that ive shown in the HTML). I think my views.py is wrong, please help me correct it -
How to display many fields' values with ForeignKey relationship?
Looking for solution of this problem I encountered some similar threads, but referring to older versions of Django/DRF and thus not working in my case. There are these two models: class CsdModel(models.Model): model_id = models.CharField("Item ID", max_length=8, primary_key=True) name = models.CharField("Item Name", max_length=40) active = models.BooleanField(default=True) def __str__(self): return self.model_id class CsdListing(models.Model): model_id = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_id') name = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_name') (...) What I'd like to see, is model_id and name from CsdModel displayed inside a form created based on CsdListing model. But instead, the ID is duplicated: How should I rebuild the model(s) to have both ID and name displayed in the form? -
django - upload file to a specific folder (named after a field from the userprofile)
I have a userprofile that captures the username and the group the user is assigned to. I want the uploaded files to be saved under the group name folder. The folders already exit at the media root, the files shoud be routed to these folder I tried adding a user directory path to the models, it does not solve my problem models.py class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, verbose_name="ID", on_delete=models.PROTECT) doc = models.FileField(upload_to='', verbose_name="Dataset") def get_absolute_url(self): return reverse('file_list', kwargs={'pk': self.pk}) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username it just creats new folders and saves the files in the media root -
How to debug django web application using specific port & localhost in visual studio code?
I want to debug django web application using visual code for that I have found solution that I have to edit launch.json for debugging django web application. launch.json "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\sparrow_fe\\manage.py", "port": "8005", "address" : "192.168.1.195", I have implemented above code in launch.json but still I am not able to start my web application on above port it automatically running on default port & localhost. -
TypeError: 'Tega' object not iterable
Here is my code in views.py user_driver_list = [] tega_list = [] for driversprofiles in check_all_columns: fetched_profile = fetch_rafiki_profile()[0] driver_rafiki_session_existance = RafikiDriverSession.objects.filter(rafiki_number=fetch_rafiki_profile()[0], drivers_profile=driversprofiles) user_driver = User.objects.filter(username=driversprofiles.user) user_driver_list.append(UserSerializer(user_driver, many=True).data) print("A") latest_tegas = Tega.objects.filter(driver_profile=driversprofiles).latest(field_name='start_time') tega_list.append(TegaSerializer(latest_tegas, many=True).data) print("B") I am trying got filter and get all latest Tegas for every matching driver in the check_all_columns QuerySet. -
How to filter_fields from coming list
User can select several genres for story. When I list all stories in Postman I receive genre field in list and when I type in url /stories/?genre=CD, I receive 0 stories. How to filter from coming list? class Story(models.Model): ... genre = MultiSelectField(choices=name_choices) class StoryView(viewsets.ModelViewSet): ... filter_fields = ['genre'] in Postman when listing all stories genre field look like: "genre": [ "FN", "CD" ] -
How to sort a merged querysets Django
I would like to combine multiple SQL queries into a single query, and then sort the merged query by a date field datas = None for product in products: if datas is not None: datas = datas | Data.objects.filter(product=product) else: datas = Data.objects.filter(product=product) datas = datas.all().order_by('created_on') Current result is that each "data set" is "sorted by the created_on field" and they appear one below the other. So essentially sorting is by Product Name, and then by created_on field but what I want is the combined "datasets" to be sorted as one by just the "created on field". -
Django. How to delete items from database with postman, because it doesn't work
So I am making a web app with Django api and everything works pretty fine, just the fact that postman can't delete my items from database. To my mind it is because django gives that confirmation pop up. Everything works from django ui itself, but I need postman to do the thing. How can I solve this? -
'datetime.date' object has no attribute 'days' error while using timedelta
Here I am writing property method to display the remaining leave days and total leave days.The total leave days are working fine but def leave_remaining_days(self) this is not working. I go this error 'datetime.date' object has no attribute 'days' Here the problem is while returning the no.of days return leave_remaining.days but when i return return leave_remaining just then it works. How can I calculate the remaining leave days here ? Only if leave.is_accepted True then i want to calculate remaining days. models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateField() end_day = models.DateField() is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) @property def leave_days(self): diff = self.end_day - self.start_day return diff.days @property def leave_remaining_days(self): if self.is_accepted: leave_remaining = self.end_day - datetime.timedelta(days=1) return leave_remaining.days -
How to add a column in table from frontend in django
I want to add columns to my Django app from frontend. For this, I have created a separate table for table fields but I don't know how can I add a field so that it automatically becomes a column in Contact table. Thanks in advance. class Contact(models.Model): fname = models.CharField(max_length=200) lname = models.CharField(max_length=200) email = models.CharField(max_length=100) mobile = models.CharField(max_length=12) address = models.CharField(max_length=200,default=None) pincode = models.CharField(max_length=10) created_date = models.DateField(auto_now=True) class Field(models.Model): field_name = models.CharField(max_length=100) field_type = models.CharField(max_length=50) is_required = models.BooleanField() -
Invalid argument for include_parents
Invalid argument for include_parents getting error when I use inplace_edit in django 2.3 v {% inplace_edit "object.title" %} -
Django UpdateView and ModelForm for file upload is not working
issue Whenever I am trying to submit form without uploading a new file, I am getting error due to form clean method. How will one submit update form with same file. error - AttributeError: 'FieldFile' object has no attribute 'content_type' views.py class DocUpdate(UpdateView): model = Document form_class = CreateDocForm template_name = 'mydoc/doc_update.html' success_url = reverse_lazy('mydoc:doc_list') context_object_name = 'document' def get_form_kwargs(self): kwargs = super(DocUpdate, self).get_form_kwargs() kwargs['request'] = self.request return kwargs forms.py class CreateDocForm(forms.ModelForm): file = forms.FileField(label='Select a file', help_text='only img/jpg/jpeg, pdf, doc/docx, xls/xlsx files are ' 'allowed with max. 50 megabytes size.') def __init__(self, *args, **kwargs): self.extension = '' self.size = '' self.password = '' self.name = '' self.request = kwargs.pop("request") super(CreateDocForm, self).__init__(*args, **kwargs) class Meta: model = Document fields = ['file', 'description'] def clean(self): # validate mime type of file file = self.cleaned_data['file'] self.name, self.extension = os.path.splitext(file.name) if self.extension not in settings.VALID_FILE_EXTENSIONS: raise forms.ValidationError("Invalid file extension.") mime = file.content_type self.size = int(file.size) if mime not in settings.VALID_FILE_MIME_TYPES: raise forms.ValidationError("Invalid file content.") if self.size > settings.MAX_UPLOAD_SIZE: raise forms.ValidationError("File size exceeded.") return self.cleaned_data def save(self, *args, **kwargs): self.instance.extension = self.extension self.instance.size = self.size self.instance.password = self.password self.instance.user = self.request.user file_instance = super(CreateDocForm, self).save(*args, **kwargs) return file_instance doc_update.html <form id="createDocForm" method="post" enctype="multipart/form-data"> {% … -
Is there any way in python to seperate meaningful words from paragraph?
Using python I want my paragraph breaks into meaningful phrases for Example I have a paragraph format like this: Input: interpreted high-levelGeneral-purpose programming languageCreated by GUIDO VAN ROSSUMFirst released in 1991 Output: interpreted high-level, General-purpose programming language, Created by GUIDO VAN ROSSUM, First released in 1991, Note: There is no space between two phrases in Input, So by using this input I want the output and mentioned above.