Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - multiplication two arrays
I have two arrays sent with ajax from template. One array contains the product id and the second is the quantity. The problem is when I get the price of product per piece from database I must to multiply with the quantity. How i do price_product[ a, b, c,d] * quantity[30,50,40,70] => a*30, b*50 .... This is my current code def price(request): price = request.POST.getlist('price[]') quantity = request.POST.getlist('quantity[]') price_product = list(set(ListProduct.objects.filter(id__in=price).values_list('price_buc', flat=True))) context = { 'data': price_product } return JsonResponse(context) -
ERROR:The SECRET_KEY setting must not be empty. (even though there is a secret key in my settings.py file )
getting django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. this error even though i have a secret key assigned in my settings.py file i have tried changing this code of line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') to os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapshut.settings' i have tried to set environmnet variable set DJANGO_SETTINGS_MODULE=mysite.settings django-admin runserver and when i run the server with that following command i just get django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing se ttings. this error and whenever i run manage.py runserver command im still getting the same error (no secret_key) i dont know what's the reason and why django isnt able to find my secret_key -
Django does not save form model
I'm using Django 1.8 and Python 2.7 job_form.is_valid() is True, but it does not save anything because Django can't detect the changed data. I attach a picture. View code: Python 2.7 str has no attribute iter, only python 3+ but I can't upgrade it. why is not working Django 1.8 with Python 2.7? job_form = JobEditForm(request.POST, instance=job) if job_form.is_valid(): job_form.save() return HttpResponse(status=200) else: return HttpResponse(job_form.errors.as_json(), status=404) -
Django quiz: Save user's choice and include them in a result
I want users to take a series of questions each with different choices to select from. Then, after the last question a page containing results should be displayed that is based on the user's choices (for simplicity let's say the user's score). I am new to Django and I am unsure on how to save the user's choices, so I can work with them. I read some posts about this, but couldn't find a final solution. First of all, will it require a setup/login feature to be able to save user data? Also, will I need some sort of customized UserModel (see code below as an example) and/or a class that contains question_id, answer_id, user_id? My models: class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class UserAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Choice, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) answered = models.BooleanField(default=False) def __str__(self): return str(self.question) + "_" + str(self.answer) class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.IntegerField(default=0) -
Django: Filter data based on expiration date coming within next 1 week and 2 weeks
I have a model class: class Products(models.Model): product = models.Charfield( field specs here . ) expiration_date = modelsDateTimeField ( . field specs here . ) Now I want the users to be able to see all the products which will expire in 1 week or/and 1 month or/and 3 months from today. I have already tried: from django_filters import rest_framework as filters expiration_date_after = filters.DateFilter(field_name='expiration_date', lookup_expr='gte') expiration_date_before = filters.DateFilter(field_name='expiration_date', lookup_expr='lte') with this, I have to pass two parameters in the url: /products/?expiration_date_after=2019-06-06&expiration_date_before=2019-06-12 But I want to pass in the url only 1 or 2 or 3 which will display data for 1 week, 2 weeks and 3 weeks . So if i pass products/1 . it should filters expiration date for next 1 week. and if i pass products/2 . it should filter expiration date for next 1 month. I am new to django.... So please let me know what is best approach to this problem. -
Html not showing the title of the django model
I created a model in django and wanted to show the title of the object I created using the model in my html code. My code for the model is: class Video(models.Model): title = models.CharField(max_length=40, blank=False) def __str__(self): return self.title And my html code is: <body> <header> <div class="container"> <!-- Branding --> <a href="/"><span class="branding">Movies & Other</span></a> <a href="/admin"><span class="adminpanel">Admin panel</span></a> </div> </header> <h1 class="movietitle">{{ video.title }}</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="uploadvideos/videos/yt/yt.mp4" type="video/mp4"> </video> </div> </body> </html>``` I created a object in the Video model in the admin panel but it doesn't show the title of it. -
Django Admin: Restrict staff to update
I had a Blog Model. All new blog post has DRAFT status. In the admin page, admin would be all permissions (CRUD) on the Blog Model. I can solve this by using Django's register method. What I want is is_staff user can view all the Blog Post but can't update Status (Eg. from DRAFT to APPROVE). Is there any way to check the request's group, then allow the user to update or not? Thanks. -
Django Vuejs -- Using Axios
I am trying to use VueJs inside my Django Framework ( Using it as Backend) for Front-End. However, I very new with axios, which I found more easier to use with VuejS Dajngo Front-End. On integrating all other, I didn't see anything coming up -
queryset use 'values' for join ,,... template variables is too long name.. can i change it?
queryset use values and LEFT join auth_user the template variable name is too long Can I change the template name to a shorter one? queryset = Post.objects.values('id','subject','created_by_id','created_by__first_name') I have to use template variable name like this "post.created_by__first_name" It's too long... can i change it? -
Django uploaded file process throws expected str, bytes or os.PathLike object, not TemporaryUploadedFile
I am trying to resize/convert uploaded image before saving: def resize_convert(image_file, size, file_full_name): os.chdir(BASE_DIR + '/convert/') file_name = os.path.splitext(os.path.basename(file_full_name))[0] file_ext = os.path.splitext(os.path.basename(image_file))[1] files = {} for i in size: cmd = ['convert', image_file, '-resize', i, file_name + i + file_ext] subprocess.check_call(cmd, shell=False) webp_cmd = ["cwebp", "-q", "100", file_name + i + file_ext, "-o", file_name + '_' + i + '.webp'] subprocess.check_call(webp_cmd) files[i] = os.getcwd() + '/' + file_name + '_' + i + '.webp' return files so from view I passed all necessary params like this : for pro in product_files: resize_convert(pro.file.name, ["308x412"], pro) then it throws this error expected str, bytes or os.PathLike object, not TemporaryUploadedFile -
How to use use a django variable in html <script> tag?
Like the python variable has a list of values and I want to equate a variable, say var list= python variable inside tag. -
Django Factory Boy Create vs create_batch
I am learning django test and i found django factory boy library very helpfull for writing testcase but one thing i am not getting.. forexample my one of Factory name is BlogFactory so i notice, most of the people use this like this: BlogFactory.create() and some people use it like this.. BlogFactory.create_batch() I am not getting difference between it.. What is different between create and create_batch ? -
Send data from django views to multiple pages
I have a function in my views.py and i want to return the value to multiple pages This is my views.py ```python def index(request): if request.method == 'POST': text = request.POST['input_text'] ResA, ResB = main.main(text) content = {'ResA': ResA, 'ResB': ResB} return render(request, 'index.html', content) return render(request, 'index.html') ``` i want send content from index function to index and example pages and This is my urls.py ```python urlpatterns = [ path('', views.index), path('example', views.index), ] ``` Thanks -
Django render template from model variables
I have a model: class DocumentoPaziente(models.Model): nome = models.CharField(null=True, blank=True, max_length=50) cognome = models.CharField(null=True, blank=True, max_length=50) contenuto = models.CharField(null=True, blank=True, max_length=100000) Variale content: Il Paziente <font color="#000000"><font face="Arial, serif"><font size="3" style="font-size: 12pt"><span lang="zxx"><b>{{ member.cognome }} {{ member.nome }}</b></span></font><font color="#000000"><font face="Arial, serif"><font size="3" style="font-size: 12pt"><span lang="zxx"> abitante [...] In template: {% autoescape off %} {{ member.contenuto }} {% endautoescape %} It render Il Paziente {{ member.cognome }} {{ member.nome }} abitante [...] Expected: Il Paziente Smith John abitante [...] Ty -
how to create a task scheduler in django
I'm working in on school project, I'm supposed to do a task scheduler but i don't know how to start. In fact, we are supposed to take reservations for activities in an institution an with that scheduler set the periods of reservation for one week or month for example at the end of this period, analyse reservation to make a board of activities in institution and make possible a reservation for another week it's not possible to make reservation of the week that the periods of reservation has been pass. Now I have a script to analyse the reservation but I don't know how to make scheduler to run the analyse script. thanks in advance. -
Raising an ValidationError on a specific field within a clean function in django
I have a Django model and I would like to make validation which involved several of the fields. However I would like to show the validation error on a specific field in the admin page and not globally. When raising a validationError in the clean function, it always shows the error in the top portion of the admin page see an example: I though about using Field validators but because my validations are on the model level and not on the field level it isn't helpful (I only get access to the value of the field and no the whole model instance) -
I am trying to implement blog app with django.I created registration form with profile pic upload.But its not submitting data?
I am trying to implement blog app with django.I created registration form with profile pic upload.But after i enter data and choose image and click on submit its not submitting data.Its returns same registration page.Instead of submitting data . #models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='pics') #views.py def register(request): if request.method == "POST": form = Register(request.POST,request.FILES) if form.is_valid(): profile = Profile() email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] Confirm_Password=form.cleaned_data['Confirm_Password'] firstname=form.cleaned_data['Firstname'] user=User.objects.create_user(username=User_name, password=Password,email=email,first_name=firstname) user.save(); profile.image = form.cleaned_data["Image"] profile.save(); return redirect('/') else: form = Register() return render(request,'register.html',{'form': form}) #forms.py class Register(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Username = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) Firstname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=30) Lastname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=40) Confirm_Password = forms.CharField (widget=forms.PasswordInput(attrs=({"class":"inputvalues"}))) Image = forms.ImageField() def clean_Email(self): if validate_email(self.cleaned_data['Email']): raise forms.ValidationError("Email is not in correct format!") elif User.objects.filter(email = self.cleaned_data['Email']) .exists(): raise forms.ValidationError("Email aready exist!") return self.cleaned_data['Email'] def clean_Username(self): if User.objects.filter(username = self.cleaned_data['Username']).exists(): raise forms.ValidationError("Username already exist!") return self.cleaned_data['Username'] def clean_Confirm_Password(self): pas=self.cleaned_data['Password'] cpas = self.cleaned_data['Confirm_Password'] if pas != cpas: raise forms.ValidationError("Password and Confirm Password are not matching!") else: if len(pas) < 8: raise forms.ValidationError("Password should have atleast 8 character") if pas.isdigit(): raise forms.ValidationError("Password should not all numeric") <!-------register.html> {% extends 'layout.html' %} {% block content %} <div class="box"> <h2> … -
"TypeError: 'int' object is not callable" when deleting in Django
I'm stumped... I get "TypeError: 'int' object is not callable" when the view attempts to delete an instance." The exception is thrown on the line "form.instance.delete()" Here's the code: view.py def decorate_letter(request, slug, template_name='letters/letter/decorate_letter.html'): active_flair = Flair.objects.filter(status='active') active_flair_count = active_flair.count() flair_formset_factory = modelformset_factory(LetterFlair, fields=('letter', 'flair', 'x', 'y', 'r', 'placed', 'delete'), form=LetterFlairModelForm, extra=0) # get user & topic user = request.user topic = Topic.objects.get(slug=slug) letter = get_object_or_404(Letter, author_id=user.id, topic_id=topic.id) if request.POST: flair_formset = flair_formset_factory(request.POST or None) for form in flair_formset.forms: if form.has_changed(): if form.is_valid(): form.instance.delete() if form.cleaned_data['delete'] == 1: form.instance.delete() elif form not in flair_formset.deleted_forms: form.save() models.py class Flair(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active') ) type = models.CharField(unique=True, max_length=250, default="default") image = models.ImageField(upload_to="flair") title = models.CharField(max_length=250) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='inactive') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) publish = models.DateTimeField(auto_now=True) class LetterFlair(models.Model): letter = models.ForeignKey(Letter, on_delete=models.CASCADE) flair = models.ForeignKey(Flair, on_delete=models.CASCADE, default=1) x = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) y = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) r = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) placed = models.CharField(default='false', max_length=250) delete = models.IntegerField(default=0) forms.py class LetterFlairModelForm(forms.ModelForm): class Meta: model = LetterFlair fields = ['letter', 'flair', 'x', 'y', 'r', 'placed', 'delete'] What could be causing the exception? -
Why is this condition not working? - if in template
I am trying to prescribe a condition if selected kind of product. I'm trying to prescribe a condition if in template. But I'm doing something wrong. Helps me, please. views.py def product_list(request, category=None, subcategory=None, kind=None): if category: categories = Category.objects.all() category = Category.objects.get(slug=category) subcategories = Subcategory.objects.filter(category=category) products = Product.objects.filter(category=category, available=True) products_quantity = len(Product.objects.filter(category=category, available=True)) kinds = None if subcategory: subcategory = Subcategory.objects.get(slug=subcategory) kinds = Kind.objects.filter(kind=subcategory) products = Product.objects.filter(category=category, subcategory=subcategory, available=True) if kind: kind = Kind.objects.filter(slug=kind) products = Product.objects.filter(category=category, subcategory=subcategory, kind__in=kind, available=True) if products: paginator = Paginator(products, 8) page = request.GET.get('page') products = paginator.get_page(page) context = { 'categories':categories, 'category':category, 'subcategories':subcategories, 'subcategory':subcategory, 'products':products, 'products_quantity':products_quantity, 'kinds':kinds } return render(request, 'shop/product/product_list.html', context) product_list.html # Not works {% if kind %} Hello {% endif %} But if I prescribe such a condition. This work fine {% if category %} Hello {% endif %} How do i set conditions for kind? Thanks! -
Django unable to load model into views
I am trying to import my models into views.py but I am unable to do so. However I am able to register them on the admin site but when I use the same code I used in admin.py to import the models into views.py, I get an error. I am using djongo so I am not sure if that changes anything about how to import them and I cannot seem to find the documentation for it. models.py from djongo import models class Round(models.Model): round_num = models.IntegerField(default=0) admin.py from django.contrib import admin from .models import Round admin.site.register(Round) views.py from .models import Round When I try and run my views.py file I get the following error: ModuleNotFoundError: No module named 'main.models'; 'main' is not a package Also my views, admin, and models file are all in the same directory. I have made the migrations and I can see my Round model in MongoDB. The only thing I cannot do is import it to the view -
How to fix 'Manager isn't available; 'auth.User' has been swapped'
I am setting up a CustomUser to use email as username (eliminating the username). This is the guide I have been following. https://wsvincent.com/django-referencing-the-user-model/ I have been trying to use the get_user_model including AUTH_USER_MODEL = 'core_app.CustomUser' in settings. When i try to register using the registrationcompany function i get an error. settings.py AUTH_USER_MODEL = 'core_app.CustomUser' INSTALLED_APPS = [ 'accounts', 'core_app.apps.CoreAppConfig', ] core_app/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) USERNAME_FIELD = 'email' objects = CustomUserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') core_app/managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Email field is required') email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user accounts/views.py def registercompany(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() new_user = form.save() new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return redirect(reverse('nonprofits:filterview')) else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form_company.html', args) accounts/models.py from django.db import models from django.contrib.auth import get_user_model class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) organisation_name = models.CharField(blank=True, default='', objects = models.Manager() def __str__(self): return self.user.username def create_profile(sender, **kwargs): … -
Are queries using related_name more performant in Django?
Lets say I have the following models set up: class Shop(models.Model): ... class Product(models.Model): shop = models.ForeignKey(Shop, related_name='products') Now lets say we want to query all the products from the shop with label 'demo' whose prices are below $100. There are two ways to do this: shop = Shop.objects.get(label='demo') products = shop.products.filter(price__lte=100) Or shop = Shop.objects.get(label='demo') products = Products.objects.filter(shop=shop, price__lte=100) Is there a difference between these two queries? The first one is using the related_name property. I know foreign keys are indexed, so searching using them should be faster, but is this applicable in our first situation? -
How to combine two filters from two models?
How to combine two filters from two models? Must be work as AND (&) Credit.objects.filter(id__in=Condition.objects.filter(security='Deposit - deposit').values('credit__id').distinct(), bank__id=1)) Credit.objects.filter(id__in=Condition.objects.filter(purpose=3).values('credit__id').distinct(), bank__id=1)) -
<Post: mi post>” needs to have a value for field “id” before this many-to-many relationship can be used
I'm trying to save data in a model that has a m2m relation from django admin, but when I save that error, try changing the relation to foreignkey but it's not what I need, any ideas? models.py class Post(models.Model): titulo = models.CharField(verbose_name="titulo del post", max_length=50) posting = HTMLField(verbose_name="posting",blank=True,null=True) categoria = models.ManyToManyField("posts.Categoria", verbose_name="categorias del post") slug = models.SlugField(verbose_name="slug del post", help_text="identificador unico del post", unique=True) admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): readonly_fields = ('slug',) def save_model(self,request,obj,form,change): if change: formato = "%d%S" es = " " if obj.titulo.find(es) >= 1: obj.slug = obj.titulo.replace(es, "-").lower() + "-" + obj.fecha_creacion.strftime(formato) else: obj.slug = obj.titulo.lower() + "-" + obj.fecha_creacion.strftime(formato) obj.save() -
How to visit a git branch of Django project on Nginx/uWSGI server?
I have successfully built several web sites hosted on an Nginx server using Django, uWSGI and virtualenv. I had never used version control but now I am starting to use Git. I understand how to create, commit and push branches. My question is: how to make different Git branches visible at the web address of the site I'm working on? Do I change the Nginx config file to point somewhere different? I just updated the dev branch of my project, and of course the site does not reflect the changes. How can I tell the server to serve the dev branch or the master branch of the project? I would prefer to avoid a complicated system with different subdomains for different branches — I really just want the simplest thing that will work.