Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django - multiple choice for ForeingKey
I am designing the models for the database that will consist of several apps. It has been decided to add a simple Document Management System to allow infinite documents to be attached to different models. This is the solution that I have thought but I don't know if it there is a better way to do it. Let's say for simplicity 3 models models.py class Contract(models.Model): .... class Invoice(models.Model): .... class Personal_record(models.Model): .... Each model can have multiple documents associated at user discretion for example: "Contract" can have 1 contract_file.pdf and 'n' amendments_to_the_contract.pdf "Invoice" is the only model that can have, in theory, an invoice.pdf per record "Personal_record" is free to the user to attach/upload any file he desires, therefore 'n' records.pdf The solution I thought of is to create another model called Documents that will store all the documents uploaded from any upload form. I would list all the links to the other models and make them blank and use a simple if/else to which type of ForeignKey update. class Documents(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE,blank=True, null=True) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE,blank=True, null=True) p_records = models.ForeignKey(Personal_record, on_delete=models.CASCADE,blank=True, null=True) .... Is there a better way to do it? Maybe having only one … -
ModuleNotFoundError: No module named 'graphql.execution.executors' using graphql-ws
I try to write a subscription for my django webapp by using graphql-ws. I followed instruction that are written in README file inside the github repository (https://github.com/graphql-python/graphql-ws) but when I execute ./manage.py runserver, this error raises: File "/myproject/urls.py", line 16, in <module> from graphql_ws.django_channels import GraphQLSubscriptionConsumer File "/myproject/env2/lib/python3.8/site-packages/graphql_ws/django_channels.py", line 11, in <module> from .base_sync import BaseSyncSubscriptionServer File "/myproject/env2/lib/python3.8/site-packages/graphql_ws/base_sync.py", line 1, in <module> from graphql.execution.executors.sync import SyncExecutor ModuleNotFoundError: No module named 'graphql.execution.executors' I understand that this is caused by an in import inside graphql-ws: from graphql.execution.executors.sync import SyncExecutor. Here the problem is the graphql-core's version, in my project I need 3.1.6 for a lot of other things, and there isn't executors folder with file sync.py... but graphql-ws requires 2.* for graphql-core. Here is a part of my requirments: graphene~=3.0b7 graphene-django==3.0.0b7 django-graphql-jwt==0.3.2 graphql-ws==0.4.4 graphene-django-optimizer==0.9.0 graphene_file_upload==1.3.0 graphql-core==3.1.6 How can I fix it? Thanks a lot in advance -
Use function in Django Include Tag?
I'm trying to pass a value into a template via an include tab, like so: {% include "shared/page_title.html" with text=local_time_format(job.date, user.timezone, "M j P") %} So basically, i want the text value to be the result of calling local_time_format (a filter function) with job.date (context object value) and a user property and the final argument. Getting Could not parse the remainder error-- how to fix? -
Generate a new database when insert row in table
First of all i need to say i'm noob here and probably it is silly question I have a database called Projects, with one table like this: ID Project_name For example: ID projec_name 1 P301 2 P302 I want that every time I insert a record in this table of the database , generate a new database called db_project_name (e.g db_P301) with a structure that i have already defined. It is possible to do this by means of triggers? As far as i know, the triggers are only used to insert, update and delete records in a table, if it can not be done by a trigger I would like to know what options I have Or maybie it could be possible to do this via a scheduled task or an event? All this would be for a database of a web developed with django. Thanks -
Field 'xxx' expected a number but got <django.forms.boundfield.BoundField>
Here is my code: In forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ("title","business_partner","transaction") widgets = { 'transaction': forms.NumberInput() } In views.py def uploadpdf(request,pk): project_form = ProjectForm(request.POST) if project_form.is_valid() and request.FILES: project_form.instance.user = request.user project = Project.objects.get(id=pk) project.title = project_form['title'] project.business_partner = project_form['business_partner'] project.transaction = project_form['transaction'] project.save() project = Project.objects.get(id=pk) file_path = None for file in request.FILES: file = request.FILES[file] pdf_file = PDFFile(file=file, filename=file.name) pdf_file.project = project pdf_file.save() if PRODUCTION: file_path = HOST_NAME +'/'+ str(pdf_file.file) else: file_path = HOST_NAME +'/media/'+ str(pdf_file.file) resp = HttpResponse(f'{{"message": "Uploaded successfully...", "id": "{project.id}","url":"{file_path}","title": "{project.title}"}}') resp.status_code = 200 resp.content_type = "application/json" return resp else: return reverse("dashboard:homepage") When I run this, it says like "TypeError: Field 'transaction' expected a number but got <django.forms.boundfield.BoundField object at 0x000001A803935250>." Looking forward to hearing a good solution. -
How to sent to a personal mail with django contact form?
I'm creating a contact form on my Django website, I created a form, now I need to add into function an option when the contact form is filled to be sent to my private Gmail. Can I do this within a views function, if I can, please tell? views.py from .forms import ColorfulContactForm def contact(request): form = ColorfulContactForm() if request.method == 'POST': form = ColorfulContactForm(request.POST) if form.is_valid(): pass # what to add here? else: form = ColorfulContactForm() return render(request, 'contact.html', {'form': form}) forms.py class ColorfulContactForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) email = forms.EmailField( max_length=254, widget=forms.TextInput(attrs={'style': 'border-color: green;'}) ) message = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={'style': 'border-color: orange;'}), help_text='Write here your message!' ) -
Django-NuxtJs: can't get cookie from request
I am using django and nuxt js to create a webapplication but I am having a problem with getting the user's data from the server after authentication. I tried using cookies but it didn't work so far. the server can't get the cookie from the request even though I have set credential: true. appreciate any help Views.py: from django.contrib.auth import authenticate from rest_framework.reverse import reverse import requests import jwt,datetime from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.decorators import api_view,permission_classes from rest_framework.permissions import * from .serializers import * from .models import * class BrandView(APIView): def get(self, request, *args, **kwargs): brands = Brand.objects.all() serializer= BrandSerializer(brands,many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializers= BrandSerializer(data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) return Response(serializers.errors) class ProductViewSet(viewsets.ModelViewSet): queryset=Product.objects.all() serializer_class= ProductSerializer class CustomersViewSet(viewsets.ModelViewSet): queryset=Customers.objects.all() serializer_class= CustomersSerializer class OrderdetailsViewSet(viewsets.ModelViewSet): queryset=Orderdetails.objects.all() serializer_class= OrderdetailsSerializer class OrdersViewSet(viewsets.ModelViewSet): queryset=Orders.objects.all() serializer_class= OrdersSerializer @api_view(['POST']) def register(request): username= request.query_params['username'] email= request.query_params['email'] password= request.query_params['password'] user = User.objects.create_user(username,email,password) @api_view(['POST']) def login(request): username= request.data.get('username') # email= request.query_params['email'] password= request.data.get('password') user = authenticate(username=username, password=password) if user is None: if not User.objects.filter(username=username): raise exceptions.AuthenticationFailed('User does not exist') else: raise exceptions.AuthenticationFailed('Incorred password') serializers = UserSerializer(user) token_endpoint = reverse(viewname='token_obtain_pair',request=request) token = requests.post(token_endpoint, … -
Django get_object Not found
On two different PCs I run same code, which contains 'get_object_or_404' user = get_object_or_404(User, username = self.kwargs.get('username')) On my PC it runs ok, I get 'MVidić' as value. On other PC I get: MVidi%C4%87:1 GET http://app.local/user/MVidi%C4%87 404 (Not Found) Why is that? Is it some localization setting? All Django/Python files are the same on both PCs. When user is a person without diacritic simbols it works ok. views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) user_id=user.id return Post.objects.filter(author=user_id).order_by('-date_posted') models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) settings.py LANGUAGE_CODE = 'hr-BA' TIME_ZONE = 'Europe/Zagreb' USE_I18N = True USE_L10N = True USE_TZ = True -
how to send variable from JS to Python using queryparameter
I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However I want pass my variable through this ajax call. it is being sent as a queryparameter. however the result that is printed is just: "Variable: local" and not the actual variable details. How can i fix this? JS function calling (){ var local = 25 $.ajax({ type:'GET', url:'printsome/?variable=local', success: function(response){ console.log('success'); console.log(local); }, error: function (response){ console.log('error'); } }); PY from django.http import JsonResponse def print_some(request, ): variable = request.GET.get('variable', 'default') print('Variable:', variable) return JsonResponse({}) -
Django Form Wizard not saving FileField
I have a 5 step form wizard, each their own form. I have a FileField in the first, but something is going wrong. When I reach the final step and press submit, my model gets saved but the file field is empty in my database. It's not "null", but actually empty. I created the "file_storage" variable but that only stores the file temporarily, it get's deleted as soon as I submit the form this is my wizard class: import json import logging import os import keyboard from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.mail import EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import * logger = logging.getLogger('django') FORMS = [ ("company", CompanyForm), ("addresses", AddressesForm), ("references", ReferenceFormSet), ("contacts", ContactFormSet), ("payment", PaymentForm), ] TEMPLATES = { "company": "form/step-1.html", "addresses": "form/step-2.html", "references": "form/step-3.html", "contacts": "form/step-4.html", "payment": "form/step-5.html", } form_data = [] form_data2 = {} class RegisterWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp')) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) context.update({'callme_forms': CallMeForms(prefix='callme')}) return context @property def first_step_files(self): return self.storage.get_step_files(self.steps.first) def process_step(self, form): data = {} form_data.extend(self.get_form_step_data(form)) for attr, value in self.get_form_step_data(form).items(): if 'reference' not in attr: if 'company-' in attr: attr = attr.replace('company-', '') … -
Django: how to include missing pk field into serializer when updating nested object?
I have a serializer in my Django app that is meant for updating a nested object. Updating works, but I'm facing another problem: I can't delete objects that are not in validated_data['events] because I don't have the id to be compared with my instance id's. For reference, these are my Models: class Plan(models.Model): planId = models.CharField(primary_key=True, max_length=100, unique=True) name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) id = models.CharField(primary_key=True, max_length=100, unique=True, blank=False, null=False) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) This is my PlanEventUpdateSerializer: class PlanEventUpdateSerializer(serializers.ModelSerializer): class Meta: model = PlanEvent fields = ('done', 'title') Is there some way to include the id, so I could compare the id's like this in my update method: class PlanUpdateSerializer(serializers.ModelSerializer): events = PlanEventUpdateSerializer(many=True) class Meta: model = Plan fields = ('name',) .... def update(self, instance, validated_data): events_validated_data = validated_data.pop('events') events = (instance.events.all()) events = list(events) event_ids = [item['id'] for item in events_validated_data] for event in events: if event.id not in event_ids: event.delete() -
Django Error - Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
When I first ran the server everything was fine and the project was running properly. But after few days when I ran the server again, it gave me an error Traceback (most recent call last): File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 22, in <module> main() File "C:\Users\Admin\Desktop\Django Project\first\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? To be specific, I'm on Windows 10, using VS Code as my IDE (I've not setup any virtual environment). Django version installed - 3.2.9 Python version installed - 3.10.0 PIP version installed - 21.2.3 Here is a screenshot of my Environment Variables [ -
Django test a view return 302 insteatd of 200
I am writting some tests in a Django project. For example, I want to test an index view in one app fo my Django project. But I am not sure test code below is correct, event if test passed. User need to be authentified to access this index view. So, in SetUp, I first create test user and logged in. And finally, I test I can get index view by testing status_code return. But if I omit follow=True, it return 302 and test failed. Is my test code correct? class IndexPageTestCase(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_superuser(username='test', password='test', email='test@test.fr') self.client.login(username='test', password='test') def test_index_page(self): response = self.client.get(reverse('ecrf:index'), follow=True) self.assertEqual(response.status_code, 200) Django project architecture - core - urls.py - ecrf - urls.py - views.py core/urls.py urlpatterns = [ path('ecrf/', include('ecrf.urls')), ] ecrf/urls.py urlpatterns = [ path("", views.index, name="index"), ] ecrf/views.py @login_required def index(request): ... return render(request, "ecrf/index.html", context) -
How to process webcam frames in django views using opencv
I want to have a django view with python code which uses opencv like... cap = cv2.VideoCapture(0) while(True): ret, image = cap.read() if ret == False: break result = <Some opencv processing > if <condition1>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error1'}) if <condition2>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error2'}) elif <condition3>: return render(request, 'myapp/dashboard.html', context={"welcome": 'Error3'}) else: return render(request, 'myapp/dashboard.html', context={"welcome": 'Welcome to dashboard'}) if cv2.waitKey(1) & 0xFF == ord('q'): break I want while loop running continuously and then based on if else conditions make changes in template using context. Is there a simple way to do this without using gen() for capturing frames and then processing them. -
Errors deploying my web application with elastic beanstalk and django
First time using aws and elastic beanstalk. My Django site works fine when I host it locally. I've followed the instruction on deploying a Django application using eb on the aws guide. I think my issues are related to my virtual environment. Can someone take a look at these screenshots and see if there are any obvious issues I am missing? command line pycharm elastic beanstalk errors -
Compress to zip file and add a password
I compress the csv file and returned the zipped file as follows in a Django project def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() z = zipfile.ZipFile(response, 'w') z.write(file_path) z.close() return response Is there any way to add a password protection to the files? I tried with pyminizip but dont know how to return it as a response object -
Make calculations for records inside pagination, django
I want to calculate the sum of two records but only inside the pagination. class MacaListView(ListView): model = Maca paginate_by = 20 def get_context_data(self, *, object_list=None, **kwargs): context = super(MacaListView, self).get_context_data(object_list=None, **kwargs) maca = Maca.objects.all() for i in range(0, maca.count()): maca = Maca.objects.get(maca[i].id) maca.number = maca.number + 1 maca.save() This will go to every single record and do the logic. I want the logic to be executed for only records in pagination (do calculate for only 20 records) -
import sqlparse ModuleNotFoundError: No module named 'sqlparse'
I have installed pip install sqlparse pip3 install sqlparse conda install sqlparse But still getting sqlparse module Why is that? -
JQuery Tablesorter: How to add changing icons to table column headers?
I'm trying to create a weather data website as my first project using django and bootstrap. Wanting to implement table sorting to sort the weather data table I happened upon this JQuery Tablesorter. I have implemented the sorting feature but how do I add the sorting icons to my column headers and have them change based on how the column is sorted? I have little to no experience with JavaScript. -
How to trim whitespaces from inside of string with min_length and max_length validation?
How to trim whitespace from inside of string with min_length and max_length validation? name = serializers.CharField(min_length=18, max_length=18, trim_whitespace=True, allow_blank=True, allow_null=True, required=False) test_string_that_should_be_invalid = "1111111111111111 1" test_string_valid = "111111111111111111" -
Can't access django url (page not found)
I have models like this : class Region(models.Model): region_parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) title = models.CharField(max_length=255) description = RichTextField() description_on_list = RichTextField(blank=True) thumbnail = models.ImageField( upload_to="thumbnail-region", blank=True, max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) logo_on_navbar = models.ImageField( upload_to="logo-on-navbar/", blank=True, max_length=255) display_on_navbar = models.BooleanField(default=True) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region_parent is not None: return reverse('vineyards:region', kwargs={'parent': self.region_parent.slug, 'region': self.slug}) else: return reverse('vineyards:region-without-parent', kwargs={'region': self.slug}) class Vineyard(models.Model): name = models.CharField(max_length=255) text = RichTextField() rating = models.FloatField() custom_overlay = models.ImageField( upload_to="custom-rating/", blank=True, max_length=255) google_map = models.TextField() wine_rg_url = models.URLField(blank=True) wine_rg = models.CharField(max_length=255) wines_url = models.URLField(blank=True) wines = models.CharField(max_length=255) size = models.CharField(max_length=255) grapes = models.CharField(max_length=255) owner_url = models.URLField(blank=True) owner = models.CharField(max_length=255) visits = models.CharField(max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) regions = models.ManyToManyField( Region, blank=True, related_name="regions") cover = models.ImageField(upload_to="vineyard/", max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) top_slider = models.BooleanField(default=False) cover_slider = models.BooleanField(default=False) hide_rating = models.BooleanField(default=False) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region.region_parent is not None: return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent.slug, 'region': self.region.slug, 'slug': self.slug}) else: return reverse('vineyards:detail-without-parent', kwargs={'region': self.region.slug, 'slug': self.slug}) And this is my urls.py: app_name = 'vineyards' urlpatterns = [ path('<str:parent>/<str:region>/<slug:slug>/form/', rr_form, name="detail-form"), path('<str:region>/<slug:slug>/form/', rr_form, name="detail-without-parent-form"), path('<str:parent>/<str:region>/', vineyard_region, name="region"), path('<str:region>/', vineyard_region, name="region-without-parent"), path('<str:parent>/<str:region>/<slug:slug>/', … -
Passing a variable to python using Ajax method
I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function. JS function calling (){ var local = 25 $.ajax({ type:'GET', url:'printsome/', success: function(response){ console.log('success'); console.log(local); }, error: function (response){ console.log('error'); } }); } python def print_some(request): from django.http import JsonResponse print('this python function was called') return JsonResponse({}) -
Django : Page Not Found when trying to access static files
I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue. I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this : Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index). Here are my settings: I have debug = True ÌNSTALLED_APPS contains django.contrib.staticfiles settings.py looks like this : STATIC_URL = "/static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) But I still can't access anything from the /static/ directory. I tried to access the CSS and JS files in base.html this way : {% load static %} ... <link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet"> I really have no clue how I could solve this. Thanks in advance for your help ! -
if am searching something iam getting the result from post but when i press next button it is going to get function to get data
#here when i search button iam getting data i want from post but when i used pagination to go to the next page it is again visiting to get function pls help me to class CrawlMonitorOverall(View): ELEMENTS_PER_PAGE = 1 def get(self, request: HttpRequest) -> HttpResponse: print("get") print(request) form = SearchButtonForm() execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def post(self, request: HttpRequest) -> HttpResponse: print("post") form = SearchButtonForm(request.POST) if form.is_valid(): execution_queryset = self._get_execution_queryset(form) context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def _get_execution_queryset(self, form: SearchButtonForm) -> QueryType[CrawlRuleExecutionModel]: print(1) crawl_execution_name = form.cleaned_data["crawl_execution_name"] if crawl_execution_name: execution_queryset = CrawlRuleExecutionModel.objects.filter( crawl_rule__name__contains=crawl_execution_name).order_by('-id') else: execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') return execution_queryset def _get_execution_data(self, request: HttpRequest, execution_queryset: QueryType[CrawlRuleExecutionModel], form) -> \ Dict[str, Union[Paginator, Any]]: print(2) paginated_data = self._get_paginated_data(request, execution_queryset) execution_data = GenCrawlMonitorOverallContext().get_context(paginated_data) print(execution_data) context_data = { "execution_data": execution_data, "form": form, "paginator": paginated_data } return context_data def _get_paginated_data(self, request, query_set: QueryType[CrawlRuleExecutionModel]) -> Page: print(3) paginator = Paginator(query_set, self.ELEMENTS_PER_PAGE) page_number = request.GET.get('page') paginated_data = paginator.get_page(page_number) return paginated_data -
Hello design option : React + Django
I need your help on a design best option please, I am working on an app, the front is using react and the back is on Django. This is more a general question on how one should think when designing models! Should I rely on my front representation or what I personally think better is to align to objects normalization and abstraction. Here as an example: Let's say you two objects Company and Investment. A company could have many investments but an investment is linked to only one company. So you would add a foreign key to investment and in API level you would be able to list investment by companies like this : /api/company/id/investments Now this will return a list of investments per company. Now in front side I have only one investment to display, because only one investment/company could be active at a time (business rule). Here is my question, if let's say I filter by active= True /api/company/1/investments/?active=True I will get an array but this array will be always holding one investment. Is this a good design? Is there a way to force django to make an API filter response a json object instead of an array? …