Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is PyCharm throwing unresolved references on my Django settings file?
I'm using PyCharm 2020.1.3 (Professional) and Django 3.0.5. My settings file has the following: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( ('css', os.path.join(BASE_DIR, "common/css")), ('js', os.path.join(BASE_DIR, "common/js")), ('fonts', os.path.join(BASE_DIR, "common/fonts")), ('webfonts', os.path.join(BASE_DIR, "common/webfonts")), ('img', os.path.join(BASE_DIR, "common/img")) ) Why does PyCharm highlight each of the above STATICFILES_DIRS entries as below respectively? Unresolved reference 'css' Unresolved reference 'js' Unresolved reference 'fonts' Unresolved reference 'webfonts' Unresolved reference 'img' While it doesn't break anything, I'd also like to understand if there is a more correct way to do this. -
Django How to select differrnt table based on input?
I have searched for the solution to this problem for a long time, but I haven't got the appropriate method. Basically All I have is tons of tables, and I want to query value from different tables using raw SQL. In Django, we need a class representing a table to perform the query, for example: Routes.objects.raw("SELECT * FROM routes") In this way, I can only query a table, but what if I want to query different tables based on the user's input? I'm new to Django, back in ASP.NET we can simply do the following query: string query = "SELECT * FROM " + county + " ;"; var bus = _context.Database.SqlQuery<keelung>(query).ToList(); Is this case, I can do the query directly on the database instead of the model class, and I can select the table based on the user's selection. Is there any method to achieve this with Django? -
django-aspscheduler django.db.utils.IntegrityError: FOREIGN KEY constraint failed
Complete error: return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed Job with id test_job not found in database If I include this line code in the script: @register_job(scheduler, "interval", seconds=1) and run it in the Django environment, it runs without issue and the schedule event is correctly recorded in Django Administration under Django ASPscheduler in both the Django Job Executions and Django Jobs database: However, if a substitute the: @register_job(scheduler, "interval", seconds=1) with; @register_job(scheduler, 'date', run_date=datetime(2020, 7, 13, 8, 7, 00), id="test_job") Although the event executes correctly, I get the following errors: On execution: "Job with id gpio_app.scheduler.test_job not found in database Job with id test_job not found in database I'm a test job!" On python manage.py runserver: "Job with id test_job not found in database" On python manage.py makemigrations: "return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed Job with id test_job not found in database" Django Administration under Django ASPscheduler in both the Django Job Executions and Although the schedule is recorded in the Django Jobs database, there is no record of the execution in the Django Job Executions database. Script: import time from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job … -
Python else if statements
So I have this function that returns false if both the Diagnosis_note and memo fields are empty and true if not. I want the function to also return false if either one of it is empty and true if both of them are not empty. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing') def is_manu_date(self): return date.today() > self.manu_date def is_complete(self): fields_list = [self.Diagnosis_note, self.memo] if any(field is None or field == '' for field in fields_list) is True: return False else: return True -
Is it possible to add a creation and a modification date to a Django TemplateView and refer to it in sitemap.xml?
I am trying to generate my sitemap.xml with django.contrib.sitemaps I have mostly used TemplateView to create my pages. The problem I am facing is that my sitemap.xml does not generate any lastmod info for my pages since I have not used a model with a creation date field to create them. Is there any way to provide this locadate info to sitemap.xml using only TemplateViews? -
How to use the Date widget in views? django
I would like to know how I can use the widget in views file. I created fields in the views file. The display will be like the one I attached. This is my code models.py class Book(models.Model): name= models.CharField(max_length=14) date = models.DateField(null=True) views.py class UpdateBookView(UpdateView): model = Book template_name = "update.html" fields = [ "name", "date", ] def form_valid(self, form): ret = super().form_valid(form) self.object.submit = True self.object.save() del self.request.session["book_pk"] return ret check.html <form method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.name.errors }} <label for="{{ form.name.id_for_label }}">name:</label> {{ form.name}} </div> <div class="fieldWrapper"> {{ form.date.errors }} <label for="{{ form.date.id_for_label }}">date:</label> {{ form.date}} </div> <input type="submit" value="{% trans "Book" %}"> </form> Please advise me on what I should do. Thanks -
Quantity field for each service in the invoice app - django
I am creating an application that allows you to add predefined services to an invoice. It will be used by psychologist to create invoices for the driver examination services. When creating a new invoice You can choose which service you want to add to the invoice. It's working fine. I would like to add a field where you can specify the quantity of services you have done i.e. you have examined 10 drivers so you want only one position with quantity equals to 10 on the invoice. My problem is similar to this I need Your help here. What is the easiest way to achieve this? I tried to use inline_formset but without luck. I tried: FormSet = inlineformset_factory(Service, ServiceItem, fields=('quantity',)) but it coudn't make it. My another idea is that during invoice creation view I'd like to display a text field for each 'Service' where I can put the quantity. If quantity is bigger than 0, the Service item will be created. Please help me because I have already lost plenty of time working on it without results. I probably don't understand something important. Please help me understand. models.py class Service(models.Model): name = models.CharField(max_length=100) price = models.FloatField() class Invoice(models.Model): … -
How to correctly validate an image dimensions in django?
The issues stems from the comparison of actively uploading an image in a form, and updating a form but not updating the image. There are multiple attributes in the form with the image being one of them When I upload an image, the following works fine: file = self.cleaned_data.get('image', False) if file.image: image = file.image if image.height > 1920 or image.width > 1080: raise ValidationError("Height or Width is larger than what is allowed") return file else: raise ValidationError("No image found") If I use the same code but don't upload an image... 'ImageFieldFile' object has no attribute 'image' It looks like when I upload, it finds the file and not the image. And when I don't upload, it finds the image because if I change it to: image = self.cleaned_data.get('image', False) if image: # image = file.image if image.height > 1920 or image.width > 1080: raise ValidationError("Height or Width is larger than what is allowed") return image else: raise ValidationError("No image found") It will allow me to update the form, but not the image. Now, if I try that same code while uploading an image, i get: 'InMemoryUploadedFile' object has no attribute 'height' My attempts to remedy this issue: if file: … -
import user session data to other django app
I have a django project with two apps, the first is called 'main', where the user can login and register and all the authentication stuff is made and the other is 'app' where only authenticated users can access. Main.views: def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New account created: {username}") login(request, user) return redirect("app:app_index") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") return render(request = request, template_name = "main/register.html", context={"form":form}) form = UserCreationForm return render(request = request, template_name = "main/register.html", context={"form":form}) All the code works fine and allows me to login, register, logout... but now I need to export that user to the 'app' app in order to use the user data on the app template, how can I migrate the user and all its data? I wonder I would be able to just do app.views: from main.views import user but definitely this does not work, any suggestion will be much appreciated -
Templates folder in python django 3.x project
i am novice to django and i have problems with best practice project structure understanding. At the moment each my app has a templates folder for itself but what about having it on project level? The main point i do not understand if i can use one "super" base.html template to inherit by each app? Or there is a full misunderstanding from me? What are the pros of creating templates folder on project level if i have several apps in my project? I would be grateful if you could help me -
Django: how to differentiate variables for all users [closed]
i have been working on an "Django" app and i found out a bug in my app. when "user 1" log into the app and doing its work and in the mean time "user 2" is logged into the app so if "user 1" refresh its page "user 1" see the "user 2" name on the navbar. please help me to resolve the issue -
How do I attach image files in Django-summernote?
So I have this Django application with django-summernote, and I'm having trouble uploading image files via the editor. When I click the upload button and choose an image from my computer, I get an error saying "Failed to save attachment". And in the console, I see this error: "POST /summernote/upload_attachment/ 500". Let me show you my code. settings.py INSTALLED_APPS = [ ... 'django_summernote', ... ] ... DEBUG = True ... SUMMERNOTE_CONFIG = { 'iframe': True, 'lang' : 'ko-KR', 'summernote': { 'width': '100%', 'height': '450px', 'placeholder':'First sentence', 'toolbar': [ ['style', ['style',]], ['font', ['fontsize', 'bold', 'italic', 'strikethrough']], ['color', ['forecolor', ]], ['para', ['ul', 'ol', 'height']], ['insert', ['link']], ['misc', ['picture', 'fullscreen', 'print', 'help', ]], ], }, 'js': ( 'static/summernote-ext-print.js', ), 'js_for_inplace': ( '/static/summernote-ext-print.js', ), 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', '/mvp/static/summernote.css', ), 'css_for_inplace': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', '/summernote.css', ), 'codemirror': { 'theme': 'base16-dark', 'mode': 'htmlmixed', 'lineNumbers': 'true', }, 'lazy': False, } SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('summernote/', include('django_summernote.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I don't see what I've done wrong. Everything else except uploading image works fine. BTW, I'm using Django 3.x and Bootstrap 4.x. +++ If it gives you any further info: I … -
Serving subsection of urls on different network card
I have a Django 2.2 web application running on Apache 2.4 Ubuntu 18.04 web server, which has two network interfaces. One network interface is for internet access(eth0) and other one is for local network(eth1). I need to find a way to restrict access to some pages from each network interface, while some pages still be accessible from both interfaces. In projects urls.py I have some urls as follows: url(r'^eth0/', include('eth0.urls')), #accessible to only eth0 url(r'^eth0eth1/', include('eth0eth1.urls')), #accessible by both network interfaces url(r'^eth1/', include('eth1.urls')), #accessible to only eth1 How can I achieve this by Apache or Django configuration? -
Get OperationalError when uploading django project on pythonanywhere
I'm just started working on django and created a simple django website,now want to deploy it on the pythonanywhere,after doing all the settings on the pythonanywhere I found bellow errors, OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Here is my database settings,I'm using postgresql DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sketch', 'USER':'postgres', 'PASSWORD':'1234', 'HOST':'localhost', 'PORT':'5432' } } here is settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ci0a_hv7_s_n#_=!)k+&qk(4#2kse-94r2fe7f^acr-*juocu6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['jaimajarnaz.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'drawings.apps.DrawingsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', … -
Performance issue for rendering components using Vue JS >
Hi I am using Vue JS to render Django forms. In Django I have a seperate App for managing Accounts and related stuff. I am rendering Django Signup and Login form using Vue something like this. In App.js(My custom js file. I am using Vue JS CDN) $(document).ready(function () { Vue.component("signupform", { data() { return { signUpPassword: null, signUpUsername: null, signUpEmail: null, signUpEmailErrors: [], signUpUsernameErrors: [], }; }, template: ` <div> <div class="fieldWrapper"> <span class="errorlist" v-for="error in signUpUsernameErrors">{{error}}</span> <input v-on:keyup="checkNullSignUpForm" type="text" name="username" placeholder="Username" maxlength="150" class="signUpUsername" autocomplete="username" required id="id_username"> </div> <div class="fieldWrapper"> <span class="errorlist" v-for="error in signUpEmailErrors">{{error}}</span> <input v-on:keyup="checkNullSignUpForm" class="signUpEmail" type="email" name="email" placeholder="Email" maxlength="150" required id="id_email"> </div> <div class="fieldWrapper"> <input v-on:keyup="checkNullSignUpForm" class="signUpPassword1" type="password" name="password1" placeholder="Password" maxlength="150" required id="id_password1"> </div> <button v-on:click="checkSignUpForm" type="button" id="test" class="primaryBtn">sign up</button> <div class="directors"> <div>Already with us? <a :href="'/accounts/login'">Log In</a></div> </div> </div> `, methods: { checkSignUpForm: function () { var checkSignUpEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; var checkSignUpUsername = /^[a-zA-Z0-9+-.@]*$/igm; if(!checkSignUpEmail.test(document.querySelector('.signUpEmail').value)){this.signUpEmailErrors.push('Please enter a valid email');} if(!checkSignUpUsername.test(document.querySelector('.signUpUsername').value)){ this.signUpUsernameErrors.push('Username may contain only letters, numbers, and @/./+/-/_ characters.'); } }, checkNullSignUpForm: function () { if( (document.querySelector('.signUpPassword1').value === "") ||(document.querySelector('.signUpEmail').value === "") ||(document.querySelector('.signUpUsername').value === "") ){ document.querySelector('.primaryBtn').disabled=true; }else{document.querySelector('.primaryBtn').disabled=false;} } }, }); Vue.component("loginform", { methods: { loginCheckNull: function () {}, }, template: ` <div> <div class="fieldWrapper"> … -
Exception Type: AssertionError Exception Value: Class RatingSerializers missing "Meta.model" attribute
hi guys i a newbie and learning django-framework and building rest-api i'm stuck at this error . Its gives me error at venv\lib\site-packages\rest_framework\serializers.py in get_fields, line 1020. and says Class RatingSerializers missing "Meta.model" attribute. i did all migration and makemigration Exception Type: AssertionError Exception Value: Class RatingSerializers missing "Meta.model" attribute urls.py from django.contrib import admin from django.urls import path from rest_framework import routers from django.conf.urls import include from .views import MovieViewSet, RatingViewSet router = routers.DefaultRouter() router.register('movies', MovieViewSet) router.register('ratings', RatingViewSet) urlpatterns = [ path('', include(router.urls)), ] models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator class Movie(models.Model): title = models.CharField(max_length=32) description = models.TextField(max_length=500) class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) class Meta: unique_together = (('user', 'movie'),) index_together = (('user', 'movie'),) serializer.py from rest_framework import serializers from .models import Movie, Rating class MovieSerializers(serializers.ModelSerializer): class Meta: model: Movie fields = ('id', 'title', 'description') class RatingSerializers(serializers.ModelSerializer): class Meta: model: Rating fields = ('id', 'stars', 'user', 'movie') views.py from django.shortcuts import render from rest_framework import viewsets from .models import Movie, Rating from .serializers import MovieSerializers, RatingSerializers class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializers class RatingViewSet(viewsets.ModelViewSet): queryset = Rating.objects.all() serializer_class = RatingSerializers i … -
Single CreateView in django for submitting multiple ModelForm data to multiple Model
I have a multiple modelforms form multiple model. I want one single CreateView for submitting all the values. I have three models(Employee, WorkExperience and Education). Models are connected using ForeignKey with each other. forms.py: class EmployeeAddModelForm(forms.ModelForm): """ Creates a form for employee invitations """ class Meta: model = Employee fields = [ 'e_id', 'first_name', 'last_name', 'gender', 'religion', ] class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] class EducationForm(forms.ModelForm): """ Creates a form for saving educational info of an employee """ class Meta: model = Education fields = [ 'institution_name', 'degree', 'passing_year', 'result',] I have three model forms from three models in form.py. I want that my createview inherits all this modelforms and create a single form for posting data. views.py: class EmployeeAddView(LoginRequiredMixin,CreateView): """ Creates new employee """ login_url = '/authentication/login/' template_name = 'employee/employee_add_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm queryset = Employee.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) work_form = self.work_form_class(request.POST, prefix='work_form') print(form.errors) if form.is_valid() and work_form.is_valid(): form.save(commit=True) work_form.save(commit=True) return redirect('employee:employee-list') return render(request, self.template_name, {'form': form, 'work_form': work_form}) def get_success_url(self): return reverse('employee:employee-list') I am … -
Creating UpdateForm by using ModelForm in Django
I have a Django application and I wanna create an update form with ModelForm but I have to get the fields parameter from user_profile model. So I have created my form and view such as below. forms.py; class UpdateForm(forms.ModelForm): class Meta: model = Data fields = [] def __init__(self, *args, **kwargs): input_choices = kwargs.pop('input_choices') super(UpdateForm, self).__init__(*args,**kwargs) self.fields = input_choices views.py; @login_required(login_url = "user:login") def updateData(request,id): features = request.user.profile.selected_features instance = get_object_or_404(Data,id = id) form = UpdateForm(request.POST or None, input_choices=features, instance=instance) if form.is_valid(): data = form.save(commit=False) data.author = request.user data.save() return redirect("data:dashboard") return render(request,"update.html",{"form":form}) However, I'm getting a list indices must be integers or slices, not str error in the return render(request,"update.html",{"form":form}) line. There is an issue with the fields parameter but I couldn't find anything. How can I pass the fields parameter from view to ModelForm? -
Django Model JSON Field display as a form field on Admin page
Postgresql + Django 3.x + python3.7 I have a JSON/Text field in the model. I'm able to add/update the data for this field on the admin page. This admin page is being used by non-technical users and they don't even know what is JSON. So for them editing or adding data in this field becomes tricky because they have to make sure the data they are providing is a valid JSON. To overcome this I thought of converting that text field to a set of forms for each key/value pair, something similar to below - here I can dynamically add as many key/value pairs as I want by dynamically creating the text box. this will effectively translate into {"key1": "val1", "key2": "val2", "key3": "val3"} All keys and values are of string types so no need to worry about casting. Can you provide me with a hint/guide or point me to a relevant source to achieve this. I'm not sure if we already have any library built for the same purpose. -
Django if fields are null mark
I'm working on a project that needs to implement a function in which if memo and diagnosis_note fields are null the system should automatically display an icon. I'm a bit confused about how can this be implemented. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) diagnosis_note = models.CharField(max_length=30, default=False) memo = models.CharField(max_length=100, default=False) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing') -
How to distribute a django *project* and keep it expandable?
I'm currently building a django project that I plan to share with the world eventually. Therefore, I'd like it to be easily "installable" for anyone. In the best case, that would mean the end user won't have to install python at all beforehand. Of course, so far pyinstaller seems to be the best option. However, I also plan to develop (and allow others to develop) "plugins" for this project (i.e. django apps), which should just be easily addable by adding the files to the project's folder. (The additional problem of dynamically including such plugins without modifying the "base" program is outside the scope of the question, but as far as I can tell definitely solvable.) As far as I can tell, that is not possible with pyinstaller. So is my best option to have users just download the whole project and tell them to install Python on their system? -
How To Do Nothing After Call To View
I have a delete button. When pressed the item is removed from a list and the item is deleted. After this I don't want anything to happen, I don't want the page to refresh, yet I need to include a response from my DeleteUploadedFile view. How can I perform the operation without refreshing my page? $(document).on('click','.delete', function () { $("#user_uploaded_file" + this.id).remove(); }); class DeleteUploadedFile(View): def get(self, request, file_id): user_file = get_object_or_404(UserUploadedFile, id=file_id) user_file.delete() # here i dont't want to return a httpresponse, I want to do nothing seeing as the file has been # removed and I dont want a page refresh Thank you. -
DjangoRestFramework again downloading lastest Django
i have python(3.6) and django(2.1.15) on PC .then i am trying to install latest djangorestframework but it install again latest django 3.X.so i want keep my django 2.1.15 and install djangorestframework -
sql syntax in django
I wanna use sql query in djnago. How send parameter to sql query from recieve parameter from function, for example my code is : def products_filter(request, product, selling): all_product = Product.objects.raw("select * from product where product={{product}};") How can I use product and selling in sql query?? -
stop form action from navigating
Im creating a registration page using React, currently i'm using <Form action="https://xxxxx.amazonaws.com/production/accounts/register/" method="post"> This works, but it navigates/redirects me to the django page, is there a way to set it up without the navigation/redirect? I tried using <Form onSubmit={this.onSubmit}> onSubmit = (event) => { event.preventDefault(); fetch('https://xxxxxx.com/production/accounts/register/', { credentials: 'include', method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ username: this.state.username, email: this.state.email, password1: this.state.password1, password2: this.state.password2, }) }) .then((result) => { console.log("success"); }) .catch((error) => { console.error(error); }); } but this doesn't work.