Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '+1' from 'i+1' Error during template rendering
I'm new in python and here I need to increase the {{i}} with 1, so it would like this: 2017-2018 instead of 2017-2017+1. I share my code bellow, pls help me out!! thanks in advance. views.py from django.shortcuts import render from django.http import HttpResponse from mainapp.models import query import datetime def index(request): now = datetime.datetime.now() cdt = now.year if cdt: cdt = range(2017, int(cdt)) return render(request,"mainapp/base.html",{'yy':cdt}) base.html <html> <head><title>{% block title %}AmeyaKrishi Version 2{% endblock %}</title></head> <body> <h2>AmeyaKrishi V2 (testing mode): All University Filter</h2><hr> <p> <form action="getFarmer" method="post"> <select class="form-control" name="season"> <option value="0">-- Select Year --</option> <option value="333">All Data</option> {% for i in yy %} <option value="{{i}}">{{i}} - {{i}}+1</option> {% endfor %} </select> <input type="submit" value="Search >>"> </form> </p> {% block content %} {% endblock %} </body> </html> BROWSER OUTPUT: (on local server) enter image description here -
Doesn't save data django Foreignkey model
I've two model. I would like to save data from ForeignKey model. I'm created a modelform and save with my main foreignkey model. But I got this error ValueError at /c/customer/1/ Cannot assign "'1'": "BillingData.customer" must be a "CustomerData" instance. I created Django model form and hocked up with view. models.py file class CustomerData(models.Model): customer_name = models.CharField(max_length=100) customer_no = models.CharField(max_length=100, default='', blank=True) mobile_number = models.IntegerField() alternative_phone = models.IntegerField(null=True, blank=True) union_name = models.ForeignKey(UnionName, on_delete=models.SET_NULL, null=True) word_name = models.ForeignKey(UnionWordName, on_delete=models.SET_NULL, null=True) full_address = models.CharField(max_length=200, null=True, blank=True) create_date = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return '%s, Mobile: %s' % (self.customer_name, self.mobile_number) def get_absolute_url(self): return reverse('customer_data', kwargs={'pk': self.pk}) class BillingData(models.Model): bill_no = models.CharField(max_length=100, default='', blank=True) customer = models.ForeignKey(CustomerData, on_delete=models.CASCADE) sales_person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) customer_money = models.IntegerField() create_date = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return '%s %s' % (self.customer.customer_name, self.create_date.date()) def get_absolute_url(self): return reverse('customers.views.BillingPage', kwargs={'pk': self.pk}) forms.py file class BillCreateForms(forms.ModelForm): bill_no = forms.CharField(max_length=100) customer = forms.ChoiceField(choices=[(x.id, x.customer_name) for x in CustomerData.objects.all()]) customer_money = forms.IntegerField() def save(self, commit=True): instance = super(BillCreateForms, self).save(commit=False) customer_pk = self.cleaned_data['customer'] instance.customer = CustomerData.objects.get(pk=customer_pk) instance.save(commit) return instance class Meta: model = BillingData fields = ('bill_no', 'customer', 'customer_money',) views.py file class CustomerDataView(FormMixin, generic.DetailView): model = CustomerData form_class = BillCreateForms template_name … -
Translating text in Django without having to do it myself (physically typing into the django.py file)
I have been researching how to translate my Django app into another language for some time now. I still cannot understand 1 thing (below). I have been reading the documentation here: https://docs.djangoproject.com/en/2.2/topics/i18n/translation/#internationalization-in-template-code I am trying to figure out how to get translated text without having to type it myself in the django.po file. #: /path/to/template msgid "English Word" msgstr "" # <-- I have to type this myself for every word? The msgstr has to be type in myself? Is there an easier way to literally translate this and place it in msgstr without actually having to type it in? I am thinking of just creating a python script to hit some API that translates words and then place it in there somehow for me. Just wondering if there is an easier way to do this. -
How to create own Login and registration system in Django without using inbuilt django-auth?
I want to know is it possible to create own django registration , login and logout system without using inbuilt default django-auth system ? -
Unable to POST JSON data from multiple select element with Django REST Framework
I would like to be able to send an AJAX POST request to my API endpoint to create a new instance of my Asset model with multiple Category instances referenced in my Asset model, hence the many-to-many field type in my Asset model. I'm able to successfully POST and create new Asset instances, however my category field won't accept any data at all. The category field remains empty when a new Asset instance is created. I think it has something to do with my CategorySerializer. I'm still learning how to use Django REST Framework so I'd appreciate if I could get some help figuring out how to work with serializers in Django REST Framework. I've already tried modifying the AssetSerializer create method to handle parsing the JSON and validating the data but that hasn't worked. I've also tried other solutions suggested in other posts I've found on StackOverflow but haven't found anything that works for my situation. Here's my serializers.py file: class CategorySerializer(serializers.ModelSerializer): name = serializers.CharField(required=False, read_only=True) class Meta: model = Category fields = ('id', 'name') class AssetSerializer(serializers.ModelSerializer): name = serializers.CharField(allow_null=True) description = serializers.CharField(allow_null=True) manufacturer = serializers.CharField(allow_null=True) uid = serializers.UUIDField(read_only=True, allow_null=True) borrower = BorrowerSerializer(allow_null=True, read_only=True) condition = serializers.ChoiceField(choices=Asset.CONDITION_TYPE, default='g', allow_null=True) … -
Python How to create virtual environment in Django?
I am new to Python and I'm following a tutorial which requires creating a virtual environment while creating a Python project, But I am unable to create one for some reasons, I am using the command - mkvirtualenv djangoenv But it displays - bash: mkvirtualenv: command not found Most recommended using PyCharm but, as I have work on JS as well, I wish to continue using VS Code Following are the steps that I tried - -
Django handle concurrency in POST request and save all requests
I'm building REST API application using Django Rest Framework. Through the post request i'm receiving data and save it with citizen_id and import_id unique_together (see the models.py). Import_id for every saving is calculating via get_current_import_id() function (see views.py) For concurrent requests i'm using "curl1 & curl2" command Probably i don't understand some basics, but what i want is to save every concurrent request (every new request should be with previous import_id + 1). Also i'm using a "current_import_id" value in serializers for create and saving instances. P.S PATCH and GET requests are working with concurrent data. For example two concurrent PATCH requests are randomly saving (sometimes "first" is first, sometimes "first" is second, but it works) POST request example, JSON { "citizen_id": 1, "name": "Foo", } models.py class CitizenInfo(models.Model): citizen_id = models.PositiveIntegerField() import_id = models.PositiveIntegerField() name = models.CharField(max_length=256) class Meta: unique_together = ('import_id', 'citizen_id',) views.py Getting the maximum import_id in database and determine current_import_id def get_current_import(): previous_import_id = CitizenInfo.objects.aggregate( Max('import_id'))['import_id__max'] if not previous_import_id: previous_import_id = 0 current_import_id = previous_import_id + 1 return current_import_id At the moment the result statuses i getting from POST "curl1 & curl2" command are 201 and 500 (sometimes 500 and 201 due to randomness). Any advise, … -
How do Python Django problems and words from the intersection of existing tags be added to the tags of the article?
The main problem is that pctaglist is tags added in the background. After analyzing the content of the article with Jieba participle, the words are intersected with the tag added in the background. If so, add it to the label of this article! I don't know how to add it here. Error with T. tags. add (word), but don't know how to correct it for a while. If you want to realize the stuttering segmentation, how can you add the words that intersect with the existing tags to the tags of the article? Or are there other good ways to do this? Thank you.~ models.py class Tags(models.Model): name = models.CharField(max_length = 36, verbose_name = _(u'标签')) slug = models.SlugField(max_length = 50, verbose_name = _(u'标签url'), default = 'tags') num = models.PositiveIntegerField(verbose_name = _(u'标签排序'), default = 0) def __unicode__(self): return self.name class Meta: verbose_name_plural = u'标签名字' def get_absolute_url(self): return reverse('info:tags', kwargs = {'slug':self.slug}) forms.py class CreateTopicForm(forms.ModelForm): tags = forms.ModelMultipleChoiceField(queryset=Tags.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.RadioSelect(), initial={'headline': 'Initial headline'}) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(CreateTopicForm, self).__init__(*args, **kwargs) class Meta: model = Topic fields = ['title', 'category', 'body', 'tags',] def save(self, commit=True): inst = super(CreateTopicForm, self).save(commit = False) inst.author = self.user if commit: … -
Please point me in the right direction. with forms so confused
I essentially want to understand how to accomplish the following(#1 is the Most Important): 1) I have a ModelForm on my website that has model linked to all the data I would need to make an "order" for eg. The "Choices" for this form however, need to be pulled from another model. How do I accomplish pulling this data and using it in dropdown lists and to get loaded into the "Order" table. 2) How do I set i up so that if someone selects one choice field it filters down until when it reaches the only possible setup it just autofills the rest. (This is probably better done with js but im a bit of a noob so direction would be helpful). Now I believe this is possible using ModelMultipleChoiceField but i have read for 2 days I have a headache and still have no idea how to do this myself and literally all the examples i see are. Hey there lets make the most basic model form ever fullstop good luck with life now!. (sorry I literally had to vent a little). I am fine if you dont want to give me an example or babysit me, but … -
why does <myproject>/accounts/profile/ show the <myproject>/profile/ page
Using django-allauth, after a successful login a user is redirected to http://<myproject>/accounts/profile/... However this URL doesn't exists, but yet it still successfully shows view from http://<myproject>/profile/ settings.py urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), url('album/', include('albums.urls')), url('profile/', include('user_profile.urls')), ] user_profile\urls.py urlpatterns = [ path('', views.profile, name='profile'), ] using show_urls I don't see anything for /accounts/* which would call the view.profile view /accounts/confirm-email/ allauth.account.views.EmailVerificationSentView account_email_verification_sent /accounts/confirm-email/<key>/ allauth.account.views.ConfirmEmailView account_confirm_email /accounts/email/ allauth.account.views.EmailView account_email /accounts/inactive/ allauth.account.views.AccountInactiveView account_inactive /accounts/login/ allauth.account.views.LoginView account_login /accounts/logout/ allauth.account.views.LogoutView account_logout /accounts/password/change/ allauth.account.views.PasswordChangeView account_change_password /accounts/password/reset/ allauth.account.views.PasswordResetView account_reset_password /accounts/password/reset/done/ allauth.account.views.PasswordResetDoneView account_reset_password_done /accounts/password/reset/key/<uidb36>-<key>/ allauth.account.views.PasswordResetFromKeyView account_reset_password_from_key /accounts/password/reset/key/done/ allauth.account.views.PasswordResetFromKeyDoneView account_reset_password_from_key_done /accounts/password/set/ allauth.account.views.PasswordSetView account_set_password /accounts/signup/ allauth.account.views.SignupView account_signup /accounts/social/connections/ allauth.socialaccount.views.ConnectionsView socialaccount_connections /accounts/social/login/cancelled/ allauth.socialaccount.views.LoginCancelledView socialaccount_login_cancelled /accounts/social/login/error/ allauth.socialaccount.views.LoginErrorView socialaccount_login_error /accounts/social/signup/ allauth.socialaccount.views.SignupView socialaccount_signup only the actual /profile/ url... /profile/ user_profile.views.profile profile help me to understand why /accounts/profile/ is showing the /profile/ view... -
ImportError: cannot import name 'OSCAR_MAIN_TEMPLATE_DIR'
So i have been trying to install django-oscar but it gives me this error for some reason when i try to make migrations (via : python manage.py migrate),i am clueless as it works on tutorials of youtube and django-oscar official documentation get_core_apps already removed i know from oscar import OSCAR_MAIN_TEMPLATE_DIR TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', ], }, }, ] ImportError: cannot import name 'OSCAR_MAIN_TEMPLATE_DIR' from 'oscar' (C:\Users\dell\Envs\eshop\lib\site-packages\oscar__init__.py) -
Syntax error at the end of input when executing psycopg2
I am trying to add a COLUMN to certain table using psycopg2, from a Django function to a table in PostgreSQL. The name of the column is define in the views.py file of the Django project. I have been trying with a some similar questions in stack over flow but none have worked for me. View: def parameter_creation(request): if request.method == 'POST': name = request.POST['name'] min_value = request.POST['min_value'] max_value = request.POST['max_valu'] if ParameterModel.objects.filter(name=unidecode(name.upper())).exists(): return JsonResponse('name', safe = False) else: form = New_Parameter_Form(request.POST) if form.is_valid(): info = form.save(commit = False) info.name = unidecode(name.upper()) data_analysis.column_aggregation(name) data_analysis function: def column_aggregation(name_column): cursor.execute("""ALTER TABLE simulated_data ADD COLUMN %s""" % name_column) cursor.commit() Once the code is executed, the output is the next error: cursor.execute("""ALTER TABLE simulated_data ADD COLUMN %s""" % name_column) psycopg2.errors.SyntaxError: syntax error at end of input LINE 1: ALTER TABLE simulated_data ADD COLUMN Eng_temp -
django styling with multiple extended templates with allauth
I'm customizing a handful of the allauth templates, so I've moved them to my templates->account directory, everything works fine there. Project |-- templates |-- base.html |-- account |-- base.html |-- email_confirm.html |-- verification_sent.html The problem is I want to add some styling to each of them. It feels like account/base.html would be the place to add this styling, since it is only specific to the allauth templates, and they extend this template, but I can't figure out how to do that. all I've come up with is.. project/templates/base.html ... <div class="main-container"> {% block format_auth %} {% block content %} {% endblock %} {% endblock %} </div> ... project/templates/account/base.html {% extends "base.html" %} {% block special_format %} <div class="allauth-styling"> {% block content %} {% endblock %} </div> {% endblock %} project/templates/account/confirm_email.html {% extends "account/base.html" %} {% block content %} <h1>{% trans "Verify Your E-mail Address" %}</h1> {% endblock %} but this feels like a hack, as I don't think I should be needing to modify my top level base.html file. -
Can't display images django
How can I display images from django models on tis page datat.ru/shop ? I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" /> But only http://datat.ru/static/media/images/2.png returns image How can I convert src="{{ shop.cover.url }}" to static/media/images/ ??? urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('shop/', views.shop_list, name='shop'), path('post/<int:pk>/', views.post_detail, name='post_detail'), ] models.py from django.conf import settings from django.db import models from django.utils import timezone class Company(models.Model): title = models.TextField() cover = models.ImageField(upload_to='images/') def __str__(self): return self.title shop_list.html {% extends 'blog/base.html' %} {% load staticfiles%} {% block content %} {% for shop in shops %} <div class="container"> <div class="row"> <img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" /> </div> </div> {% endfor %} <!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> --> {% endblock %} -
Django request.GET. Search. Different results, depending on the value
There is a search form. It has a drop-down list. Each item in this list has different meanings. After clicking, a search is performed, ulr looks as follows: http://127.0.0.1:8000/search?wantbuy=kv http://127.0.0.1:8000/search?wantbuy=ls http://127.0.0.1:8000/search?wantbuy=km my views.py: kv = kv.objects.all() ls = ls.objects.all() km = km.objects.all() if 'wantbuy' in request.GET: wantbuy = request.GET['wantbuy'] if wantbuy: queryset_list = km Now, it doesn’t matter what value it 'wantbuy', I get all the objects from 'km'. Tell me how to do it better? As for each url value, display your objects? I want to: http://127.0.0.1:8000/search?wantbuy=kv Shows all objects kv = kv.objects.all() etc. Thank! -
How to create several instances of django-leaflet with for loop?
I want to create several instances of django-leaflet map with for loop and provide different lat and lon for each of them. Just to mention; every sportclub object has a location field which is PointField simply I want to have something like this but this code does not work as it should and it just shows one map with it's mark instead of one map for every object: {% for sportclub in sportclubs %} {% leaflet_map "gis" callback="map_init" %} <script type="text/javascript"> function map_init(map, options) { var lon = "{{ sportclub.location.x }}"; var lat = "{{ sportclub.location.y }}"; map.setView([lat, lon], 12 ); L.marker([lat, lon]).addTo(map); } </script> {% endfor %} -
Minimizing Flagging System DB Cost
I am trying to figure out a way to make a flagging system that does not require a new instance to be entered in the database (Postgres) every time a user flags a video. (extra context below/above the code) The fields I would like to have are 'Description', 'Timestamp' and 'Flag Choice'. So I was wondering if this would work. If I make a Flag model and make 'Flag Choices' (Gore, Excessive Violence, ect.) their own Positive Integer Fields and increment the fields accordingly and then combine the id of the post, the description for why they flagged the post, and the timestamp into ONE FIELD by separating new entries by commas into a TextField (In the User Model instead of the Flag model so I know who flagged whatever post)...Will that one Text Field eventually become too big? IMPORTANT: Every time a flag is reviewed and closed, it is deleted from said field (context below) Context: In the Flag model there will be a post_id field along with Excessive Violence Gore ect. that are Positive Integer fields which are incremented every time someone submits a flag. Then in the User model there will be ONE field which will contain … -
Make many to many fields editable in both object's admin forms
I have a Django model with a many-to-many field relating it to another Django model object. class B(models.Model): name = models.CharField(max_length=100) class A(models.Model): name = models.CharField(max_length=100) models.ManyToManyField(B) If I look on A's admin form I will see the name field and a many-to-many widget listing all the B's. If I look at B's admin form I will see just the name widget. Is there a way to allow both model's admin form to have a many-to-many widget. I'd like to add A's when I'm looking at B, and I'd like to add B's when I'm looking at A. Can this be done? -
I am trying to integrate external javascript file in template in django. I think file is loaded but it is not working properly
CSS files are working properly but there is a problem with javascript files. Even simple alert() is not working. -
How to make Login and register link dissapear after I login
I want login and register link to disappear after I login, and instead logout link should appear after being logged in. How would I achieve that -
Python Django with showing multiple details result in one user id per upload
First of all, i am new to python with only 2 months. I am facing a problem with my project code which is upload multiple file and show the result. My project was a resume parser, in my original source code it's allowed upload one resume per upload and also successful extract the data information from resume and filled in my template result. When i try to upload more than one file per upload with my original source code, it show this error Error .After that i changed my user details from get to filter. Although the error are fixed and also it successfully upload multiple file with once but my extracted result are blank and show none after i change get() to filter() Besides that, i did tried to change my user detail model from foreign key to one to one field but it didn't solve the problem This is my view with changed the user_detail = UserDetails.objects.filter(user=user) from get to filter on line 86 def homepage(request): if request.method == 'POST': user = User.objects.get(id=1) UserDetails.objects.filter(user=user).delete() Competencies.objects.filter(user=user).delete() MeasurableResults.objects.filter(user=user).delete() Resume.objects.filter(user=user).delete() ResumeDetails.objects.filter(resume__user=user).delete() file_form = UploadResumeModelForm(request.POST, request.FILES) files = request.FILES.getlist('resume') if file_form.is_valid(): for file in files: try: user = User.objects.get(id=1) # saving the … -
Get context_type from request
I am looking for build-in solution in django or DRF for getting a context_type from request. I know that django createst a context_type records for each model in the project. Is there a solution that could helps me get context_type on a request basis? I need this for one purpose: I would like to check if the user from request has permisions on this context_type (I had my own role-based permission access) -
Django save multiple foreign keys to database with multiple upload
I am a newbie in Django and I am looking for the best workaround on how to deal with this problem. I have these 3 Models: class Rigs(models.Model): name = models.CharField(max_length=30) featured_img = models.ImageField(upload_to='images/') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Gallery(models.Model): rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE, related_name='galleries') file = models.ImageField(upload_to='images/') def __str__(self): return self.name class Specs(models.Model): cpu = models.CharField(max_length=50) motherboard = models.CharField(max_length=50) rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE) def __str__(self): return self.cpu I am using this library for the multi-uploading of images (https://github.com/Chive/django-multiupload), so basically I structured my Forms similar to what the document states: class SpecsForm(forms.ModelForm): class Meta: model = Specs fields = ('rigs', 'motherboard') class RigForm(forms.ModelForm): class Meta: model = Rigs fields = ('name','featured_img') gallery_image = MultiMediaField( min_num=1, max_num=3, max_file_size=1024*1024*5, media_type='image' ) def save(self, commit=True): instance = super(RigForm, self).save(commit) for each in self.cleaned_data['gallery_image']: Gallery.objects.create(file=each, rigs=instance) return instance As well as my Views: class newrig(CreateView): model = Rigs form_class = RigForm template_name = 'flexrigapp/newrig.html' success_url = '?success' My problem is that I couldn't figure out how to include the SpecsForm on my HTML Form as well as save it on my database with the correct Foreign Key. I have already tried transferring this one on my views with some changes … -
How to pass parameter to get_queryset in Django
I have Django API built in and I have endpoint the return all object. I want the user to provide me with keyword to filter this queryset. What is the best way to do it. and how to do it plz ? is it in get_queryset? if yes can you help me !? -
Is there a way to capture some text in a Django template as a template variable?
Here's a non-working example which illustrates what I'm trying to do. I've imagined some tags that don't really exist: {% capture variable=my_url %}http://baz.bar.foo/bof?a=b{% endcapture %} {{ my_url | urlencode }} If this were a working example, I would want it to produce a URLendcoded version of whatever text was in the "capture" tag, which in this case is a URL.