Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Could not parse the remainder: '{{ ' from '{{ ' Template variable inside a variable
I'm trying to put call a variable using another variable in django. More specifically line 12. How would this be done as obviously an error has occurred when I tried to do this. <h2>Stage {{ forloop.counter }} - {{ career_stage.title }}</h2> <p>{{ career_stage.description }}</p> <hr> <form method="post"> {% with stage="stage{{ forloop.counter }}" %} {% csrf_token %} {% for written_question in career_stage.text_questions.all %} <h3>Question - {{ forloop.counter }}</h3> <p>{{ written_question.text }}</p> <p>Your Answer</p> {{ stage_forms.{{ stage }}.question{{ forloop.counter }} }} <hr> {% endfor %} </form> Stage_forms is a son object, containing multiple forms. The {{ stage }} part gets the variable required for the tab that is currently active. question{{ forloop.counter }} Will get the current question for the for loop. Error Could not parse the remainder: '{{ stage' from 'stage_forms.{{ stage' -
Is there any way to use any user-defined Python method in the Case-When query of Django ORM?
I have defined a class along with its necessary methods, which is as following. class Location(models.Model): latitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True) longitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True) @staticmethod def prepare_location_hotlink(latitude=None, longitude=None): returm mark_safe(s="<a class='inline-link' href='https://maps.google.com/maps?z=17&q={lat},{lng}' target='_blank'>{lat}, {lng}</a>".format(lat=latitude, lng=longitude)) @classmethod def retrieve_location_data(cls): annotated_case_query = { "location": Case( When(Q(location__isnull=False, longitude__isnull=False), then=cls.prepare_location_hotlink(latitude=F("latitude"), longitude=F("longitude")) ), default=Value("Not Available"), output_field=CharField() ) } return [loc for loc in cls.objects.annotate(**annotated_case_query).values_list("location", flat=True)] Here, in the retrieve_location_data method, I have tried to use a user-defined (prepare_location_hotlink) Python method in Case query to retrieve all of the location data as hotlinked. It seems not working in the above way. But I need to use the user-defined python method in the Case query anyway, as it retrieves and prepares data much faster. I already researched and read the Django documentation, but unfortunately, I could not find any solution for this case. Is there any proper and accurate way on how to use any user-defined Python method in the Case query of Django ORM? -
how to i get models id from onclick
Hi i am new to django and trying to build a zomato like site.i want to poplulate a restaurants menu on click on the restaurant button.i have Business model where all restaurants data is saved and menu model where menu of a restaurants is saved with restaurant name as a foreign key , i have populated the restaurants to the home.html, how do i populate menu of specific restaurants into store.html after click on a specific restaurant hope i'm asking the right question here is my code models.py class Business(models.Model): bname=models.CharField(max_length=200,null=False) specialities=models.CharField(max_length=200,null=True) location=models.CharField(max_length=200,null=False) # image=models.ImageField(null=True,blank=True) def __str__(self): return self.bname @property def imageURL(self): try: url=self.image.url except: url= '' return url class Menu(models.Model): business=models.ForeignKey(Business,on_delete=models.CASCADE,blank=True,null=False) dish_name=models.CharField(max_length=200,null=False) price=models.IntegerField(null=False) def __str__(self): return self.dish_name views.py def home(request): businesses= Business.objects.all() context={'businesses':businesses} return render(request,"foodapp/home.html",context) def store(request): menus=Menu.objects.get.all() context={'menus':menus} return render(request,"foodapp/store.html",context) home.html {% for business in businesses %} <div class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{% static 'images/assets/placeholder.png' %}" alt=""> <hr> <h6><strong>{{business.bname}}</strong></h6> <hr> <h6>{{business.specialities}}</h6> <h6>{{business.location}} &nbsp;&nbsp; <button data-product={{business.id}} data-action="add" class="btn btn-outline-secondary add- btn update-cart"> <a href="{% url 'store' %}"> View</a></button> </h6> {% endfor %} store.html {% block content %} <div class="row"> <div class="container"> {% for menus in menu %} <div style="margin-top: 20px;" class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{% … -
Getting pytest.mark.django_db error when trying to use parametrize
I am trying to run the following tests: # @pytest.mark.django_db def create_single_shift_record() -> Response: data = createShiftData() return client.post(reverse(revLink.shifts_single), data, format='json') @pytest.mark.django_db @pytest.mark.parametrize( 'dbName, createApi', [ (Shifts, create_single_shift_record()), # Other tests from other DB's here ] ) def test_create_single_record(dbName, createApi): res = createApi assert res.status_code == status.HTTP_201_CREATED assert dbName.objects.count() == 1 And get the error: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Even when I add @pytest.mark.django_db above the first function (shown as commented out) I still get the error Any idea if I would be able to get this to work, or another way of doing it? -
Django REST + React + Social Auth (Twitter)
I am working on an academic project. The project must have DRF as back end and react as front end. What I try to achieve here is have a react SPA containing a "Login with Twitter" button. User gets to authorize app with twitter then he lands on a home page with a message like "Hello user: ". And then I have to build it further but for now I am stuck here. I followed this tutorial and managed to create the back end API. There is a second part but no matter how hard I tried I couldn't make it work with twitter. Any help will be greatly apreciated -
What are the best ways to make your website faster such that it loads up faster and consumes less data in django
Currently I am working on a django website. I had two queries about speeding up my website. I have a products page in which I display products. Currently when I tested it with 15 pics each sizing around 8-10mb the page took too much time to load. What should be the appropriate size of the image such that it follows the above conditions and also the image quality does not get very bad. 2)I am having a page where all the products are displayed of all categories and its view look like below qs = Product.objects.select_related('category').order_by(*sorting) types = [ (k, list(vs)) for k, vs in groupby(qs, attrgetter('category')) ] I wanted to know will having different pages for different categories will help to load the site faster by filtering the products such as p=Product.objects.filter() . Or filtering would take the same time as to show all products in one single page? -
Why jquery.each(function() {} ) does not iterate through the loop at the first time?
I defined a dropbox selector which after selecting a country gives me a list of cities as checkboxs. I am using jquery and ajax to preview it and select it as follow. This is the mytemplate.html(which almost does what I expect): <div> <div id="preview-items"> </div> </div> <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: '/ajax/ajax_load_cities', data: { 'countries': countryId // add the country id to the GET parameters }, dataType: 'json', success: function (data) { // `data` is the return of the `load_cities` view function $('#preview-items').html(''); for (var i in data.tags) { $('#preview-items').append(` <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="` + data.tags[i][0] + `"> <span> ` + data.tags[i][1] + ` </span> </label><br />` ).find(':checkbox').change(function(e) { var cities_array = $(":checkbox:checked").map( function() { return $(this).next().html(); }).get(); $("#preview-items").html(cities_array.join(', ')); } } }); }); </script> and in django view.py: def load_cities(request): .... data = { 'tags': list(cities) } return JsonResponse(data) The problem is that, it does not keep the selected cities after changing the country selectors. after googling, I found that cookies are a good choice. I added the following code right after $("#id_country").change(function () { … -
ValueError at /category/leather/all/ Field 'id' expected a number but got 'leather'
This is my views.py. def category(request,type): prods=Product.objects.filter(category=type) context = { 'categories':Category.objects.all(), 'prods' : prods, } return render(request,"category.html",context) This is my models.py for reference class Category(models.Model): type=models.CharField(max_length=30) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) What is happening is that when I pass leather(or any other category) as type parameter in url it gives me the error.What I am wanting to do is that if I pass leather then the products should filter by leather category which I am not able to make happen. If I pass an id corresponding to the category then it works fine. I wanted to know a way so that the type can be read properly and then filter accordingly. -
Why does my python POST request return the following error: Invalid URL: No host supplied?
The question may seem a little silly, so I'll dig deeper. I have two EC2 instances of AWS running, one of them is Django and the other is Express, both with SSL certificate. I require Django to make a POST request to send a file to Express (following the instructions of: https://requests.readthedocs.io/en/master/user/quickstart/#post-a-multipart-encoded-file) now this whole process works well in my local environment, but it is not working in production, I already tried several options: Configured nginx to set host with proxy_set_header passed headers in the post request (https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers) I wonder if there is something in the ec2 instances that i am ignoring -
How to pass a set of objects in between two views?
I'm building a quiz app in which I'm storing questions in the database by creating a model class. I am retrieving a random question set for each user from the database and then rendering them on an HTML page. The problem is after logging a user in, a random set of questions appears but that random set is lost after refreshing the page. How do I solve this One thing that I thought was retrieving the object set in another view....say after logging a user in and passing it as a dictionary to another view. But I can't find the syntax or any function (if it exists). Please help. I'm using django 3.1 and MySQL as my database. My views.py looks like this: from django.shortcuts import render, redirect from .models import * from .forms import UserForm from django.contrib.auth.forms import AuthenticationForm import random from django.contrib.auth import login, logout, authenticate # Create your views here. def home(request): return render(request, 'testapp/home.html') def loginuser(request): #form = UserForm() if request.method == 'GET': form = AuthenticationForm() return render(request, 'testapp/login.html', {'form':form}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'testapp/login.html', {'form':AuthenticationForm(), 'error':'Username or password incorrect'}) else: login(request, user) return redirect('paper') def paper(request): #objects … -
Use authentication in templates and vue.js together
I have mature Django application that is built with Django-templates for the frontend. Now I want to rewrite part of the application to Vue.js (user's dashboard). That is, I want use the Django-Rest-Framework for the backend and Vue.js for the frontend, but not use Django templates at all. Is it possible to somehow combine the authentication that is used in Django templates in the frontend, written in Vue.js? That is, so that the frontend, written in Vue.js, receives information whether the user is authenticated or not. -
How the change the underlying model for a form in a view?
I have a small Django-app were I want to manage two stock portfolios. I created two tables (SecuritiesSVR and SecuritiesAHT) with the same structure (based on an abstract model). In the url I added an argument 'ptf' : portfolio/str:ptf/change_position I also created a form to update the tables: class SecuritiesUpdateForm(forms.ModelForm): class Meta: model = model is dependent on parameter in url fields = ['opinions', 'remarks'] Now i'm searching for a way to change the underlying model for the form depending on the parameter in the url: def change_position(request, ptf, symbol): if ptf == 'aht': Securities = SecuritiesAHT if ptf == 'svr': Securities = SecuritiesSVR security = Securities.objects.get(pk=symbol) if request.method == 'POST': u_form = SecuritiesUpdateForm(request.POST, request.FILES, instance=security) if u_form.is_valid(): u_form.save() messages.success(request, f'Security has been updated!') return redirect('portfolio:portfolios', ptf=ptf) else: u_form = SecuritiesUpdateForm(instance=security) context = { 'u_form': u_form, 'ptf': ptf } return render(request, 'portfolio/change_position.html', context) Is there a possibility to set in the view the model that the form needs to use? -
GET Request Django Rest Framwork: Not able to access static folder
I am developing a Django Web Application (https://github.com/yashshah14093/SHOP-PY/tree/master/Shop-py/WebApp). I have added images in the img folder of static files. But When I make a GET Request, I got an error mentioned below. Please help me to resolve this issue. -
Scrapy/Django - PyCharm debugger - can't import model
I have a spider that scrapes websites based on Django model Domain. I created a custom configuration for scrapy to be able to use PyCharm Debugger. The problem is that when I run spider using Debugger, it raises this error: from core.models import Domain ModuleNotFoundError: No module named 'core.models' But when I run it this way: scrapy crawl domain_spider it works correctly. import os import sys from datetime import timedelta import django import scrapy from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from scrapy.spiders import Spider DJANGO_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(DJANGO_DIR) print(DJANGO_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'mspiders.settings' django.setup() from core.models import Domain from django.db.models import Q from django.utils.timezone import now class DomainSpider(Spider): name = 'domain_spider' custom_settings = { 'USER_AGENT': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", 'LOG_FILE': 'logs/domain_spider.log', 'CONCURRENT_REQUESTS': 100, 'DOWNLOAD_TIMEOUT': 20, 'DNS_TIMEOUT': 20, 'RETRY_TIMES': 2, 'LOG_LEVEL': 'INFO', } def start_requests(self): The sys.path.append(DJANGO_DIR) line prints this: '/home/milano/PycharmProjects/spiders/mspiders' which is a correct Django project directory This is a configuration: This is very weird since I use such a configuration often without any problems. -
Django model last modification datetime, how to exclude the influence of some fields?
I use DateTimeField with auto_now=True to store last update datetime: updated_at = models.DateTimeField(auto_now=True) I want to update this datetime for all changes in model exclude some fields. Example model: class MyModel(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() updated_at = models.DateTimeField(auto_now=True) So, i need updated_at field to be updated if something changes in the model, but except changes in field2. Is there a solution to do it with auto_now? Or i need to do it manually, for example, by overriding save() method or etc? I will be grateful for any suggestions how to solve it! -
Configure Pycharm Pro for Django
I just got the Pycharm's Pro Student License. I have looked up on the internet on how to configure the settings, however apart from syntax highlighting, nothing much has changed. For example in terminal people just type commands without - python mange.py ..... And the small run button starts the server. None of this work on my pycharm. Can you please tell me how to get those things working. And if I have a previously build django project what setting do I need to change while opening it. -
domain restriction does not doing anything
Hello I have a simple form where I want to save information. I added the domain restriction in my forms but it still saves emails with other email domains. I am new to django maybe it is an easy task, thanks. models.py from django.db import models class WPGroup(models.Model): name=models.CharField(max_length=128,blank=False) number=models.PositiveIntegerField(blank=False) bolum=models.CharField(max_length=128,blank=False) mail=models.EmailField(max_length=128,blank=False) def __str__(self): return self.name forms.py from django import forms from .models import WPGroup class WPGroupForm(forms.ModelForm): class Meta: model=WPGroup fields=['name','number','bolum','mail'] def clean_email(self): email = self.cleaned_data['mail'] if "@itu.edu.tr" not in email: raise forms.ValidationError("You must include @itu.edu.tr") return email views.py class WPGroupView(generic.CreateView): template_name='wp.html' form=WPGroupForm model=WPGroup fields=['name','mail','bolum','number'] success_url='success/' -
535, b'5.7.8 Username and Password not accepted with G Suite and Django
I'm trying to send email from my G Suite account. I have enabled 2FA and generated an app password that I'm using in my django project. My settings.py file looks like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = os.getenv("EMAIL_USER") EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.getenv("EMAIL_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASSWORD") I have set the EMAIL_HOST_PASSWORD as the 16 character generated app password. Why is it still failing? (There is no way to allow "less secure apps" with G Suite if I got 2FA enabled - I'm just redirected to creating an app password, which is what I have done) I just keep getting (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 29sm2220422ljv.72 - gsmtp') What setting am I missing? -
Django query for the top 5
I have this two model: class State(models.Model): name = models.CharField("State",max_length=255) class Breakdowns(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE,verbose_name="State") date = models.DateField(blank=True,null=True,verbose_name="Date") ... ... ... ... As you can see i can have 1 State with severeal breakdows. How can i show the top 5 state's with more breakdowns ? -
No user link in auth section of Django admin
I am trying to implement a custom user model, but under the auth section of the Django admin website my model is not showing up. I found an answer at the link below to the overall problem, but when trying to implement it myself I still do not see the users in the auth section of the Django admin. No “Users” link in “Auth” section of Django admin site what am I doing wrong here ? models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm model = CustomUser list_display = ( "email", "username", ) fieldsets = ( (None, {"fields": ("email", "password")}), ("Permissions", {"fields": ("is_admin", "groups", "user_permissions")}), ) admin.site.register(CustomUser, CustomUserAdmin) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ("email", "username") class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ("email", "username") -
Importing scipy stats makes django time out on AWS elastic benastalk
I have a moderately complex api in Elastic Beanstalk. It uses celery and django. It's driving me crazy that just trying to import scipy stats makes django not be able to return anything. I've checked the instance and there is available memory and cpu. I singed out scipy by elimination, as python won't even return an error. I am running version 3.6 of python, scipy version 1.5.2 . I have a rather long list of libraries installed. Even when not using scipy (just importing it) the script will just not return anything. Commenting the import makes everything work fine. I have tried importing the library on a new development with the same characteristics and it seems to work. Any ideas as to what might be causing this behavior? -- Edit -- It looks like adding the full list of requirements makes the new development have the same problem (even though it is just a default django app that does nothing but show an index.html file). So I am adding the list of libraries. I am guessing one of them is having problems with scipy. aiocontextvars==0.2.2 amqp==2.5.2 asgiref==3.2.4 attrs==19.3.0 awscli==1.18.28 awsebcli==3.17.1 bcrypt==3.1.7 billiard==3.6.3.0 blessed==1.17.2 boto3==1.12.16 botocore==1.14.0 botometer==1.5 cached-property==1.5.1 celery==4.4.2 cement==2.8.2 certifi==2020.4.5.1 … -
ERROR: Could not find a version that satisfies the requirement request (from versions: none)
I am trying to install request package on windows 10 terminal using pip install request. But I am getting this error ERROR: Could not find a version that satisfies the requirement request (from versions: none) ERROR: No matching distribution found for request Where I am going wrong -
django.db.utils.IntegrityError: null value in column "state" violates not-null constraint DETAIL:
In my models.py I have state = enum.EnumField(CertificateStatus, verbose_name=_('State')) When I try to submit my Modelform I get the following error. django.db.utils.IntegrityError: null value in column "state" violates not-null constraint DETAIL: Failing row contains (8, 2020-08-24 13:10:23.007867+00, 2020-08-24 13:10:23.007887+00, user/5/certificates/CvCandidat_C00370440_8045152_01_e5xylKe.docx, 1, , 2020-08-24, 5, null, null). -
Generic detail view --userprofile link with post author
I am trying to view post author profile page from blog detail page and for that #views.py class UserProfileView(DetailView): model = Userinfo template_name = "accounts/userinfo.html" def get_context_data(self, *args, **kwargs): context = super(UserProfileView, self).get_context_data(*args,**kwargs) context['author_page'] = get_object_or_404(Userinfo, user=self.kwargs.get('username')) return context and the url has to something like http://127.0.0.1:8000/profile/test2/ path('profile/<str:username>/', UserProfileView.as_view(), name='user_profile'), postdetail page <a href="{% url 'user_profile' username=post.author.username %}">{{ post.author.username }}</a> and model.py class Userinfo(models.Model): user = models.OneToOneField(accountUser, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) bio = models.TextField(max_length=800) def __str__(self): return self.user.username -
matching django url with views using a model slug
my problem is that I can not establish a reverse match, most likely doing something wrong with my url definition (?). Ultimately what I am trying to do is the following: User selects 2 location points which the 'new_pointview' view, saves into a DB. I also define a unique slug which contains location information and save it to the DB via the save() within the model. Then the user should be redirected to a url (pointview view) which uses the slug I created in the previous step i.e /pointview/slug. Here is the code: models.py class Points(models.Model): starting_point_longitude = models.FloatField(null=True) starting_point_latitude = models.FloatField(null=True) ending_point_longitude = models.FloatField(null=True) ending_point_latitude = models.FloatField(null=True) url = models.SlugField(max_length=250, null=True, unique=True, blank=False) def save(self, *args, **kwargs): self.url = 'start_lon-{0}-start_lat-{1}-end_lon-{2}-end_lat-' \ '{3}'.format(self.starting_point_longitude, self.starting_point_latitude, self.ending_point_longitude, self.ending_point_latitude) super(Points, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('pointview', kwargs={'url': self.url}) views.py def pointview(request, url): point = get_object_or_404(Points, url=url) content = {'starting_point_longitude': point.starting_point_longitude, 'starting_point_latitude': point.starting_point_latitude, 'ending_point_longitude': point.ending_point_longitude, 'ending_point_latitude': point.ending_point_latitude} return render(request, 'points.html', {'user_bundle': content}) def new_pointview(request): Points.objects.create( starting_point_longitude=request.POST['starting_point_longitude'], starting_point_latitude=request.POST['starting_point_latitude'], ending_point_longitude=request.POST['ending_point_longitude'], ending_point_latitude=request.POST['ending_point_latitude'], ) points_filtered = Points.objects.filter( starting_point_longitude=request.POST[ 'starting_point_longitude']).filter( starting_point_latitude=request.POST[ 'starting_point_latitude']) unique_url = points_filtered.values()[0]['url'] return redirect('/pointview/{0}/'.format(unique_url)) urls.py urlpatterns = [ path(r'^pointview/(?P<url>[-\w]+)/$', views.pointview, name='pointview'), path('^new_pointview/', views.new_pointview, name='new_pointview'), ] The error: The current path, pointview/start_lon-738949.9146592747-start_lat--153698.8751025315-end_lon-759997.8063993475-end_lat--168467.65638300427/, didn't match any of URL …