Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When is Django REST Framework CURSOR pagination expired?
When using CURSOR pagination in Django REST Framework, It uses cursor query parameter like ?cursor=xxxxxxx(Maybe it is a database cursor ID?) and I assume that the cursor will be expired after a while so that it comes to be not available anymore. Is my assumption is right? if so, when is it expired? -
How can I create a subclass using django?
Hello I am using django with a postgre database and in my database I have 5 columns and on of them is called : "data" and in the data there is : |data | |{"name":"Peter","city":"New York"}| |{"name":"Denis","city":"Paris"}| |{"name":"Jennifer","city":"San Francisco"}| |{"name":"Kim","city":"Berlin"}| And I would like to extract this column and create a subtable by the name of dataExtract for instance such as : |name|city| |Peter|New York| |Denis|Paris| |Jennifer|San Francisco| |Kim|Berlin| Could you help me please ? Thank you very much ! -
"Could not parse reminder error" - django
Then jsevent triggered , it forwards link parameter to data-url attribute of a button and when user click that button it redirects to django backend view but there is a problem with parsing line of JS $('#btn_del').attr('data-url',{% url 'event_delete' + event.id + %}); is there any chance to combine that syntax ? Thank you , have a nice days. JS: eventClick: function(event, jsEvent, view) { $('#modalTitle').html(event.id); $('#btn_del').attr('data-url',`{% url 'event_delete' ` + event.id + `%}`); $('#calendarEditModal').modal(); console.log(event.id); } Html button that redirects to django <button id="btn_upd" type="button" class="btn btn-primary js-delete-events" data-url=""> <span class="glyphicon glyphicon-pencil"></span> Edit </button> Result should be like this format event.pk is going to be our parameter numeric value , it's ok. <button type="button" class="btn btn-primary js-delete-events" data-url="{% url 'event_delete' event.pk %}"> <span class="glyphicon glyphicon-plus"></span> button </button> -
ManyToMany relationship between Category and Product in Ecommerce
I am developing a eCommerce using Django and relationship between Product and Category Models is Many-to-many. That is, one product can belong to several category. In the product list page there is a sidebar showing the category list as well as the product list under each category. We use get_absolute_url method of Product to link to the url of each product detail page. The problem is that in the product detail page (template), I do not know how to get the category name to this product, because this product may belong to several categories. I want to use the category of this product to make a breadcrumb. Product model class AbstractProduct(models.Model): ... categories = models.ManyToManyField( 'catalogue.Category', through='ProductCategory', verbose_name=_("Categories")) ... def get_absolute_url(self): return reverse('catalogue:detail', kwargs={'product_slug': self.slug, 'pk': self.id}) Product list template (prod.model is the model number of product) <a href="{{ prod.get_absolute_url }}" class="nav-link text-muted mb-2">{{ prod.model }}</a> -
Django - How to render html and return a json at the same time
I have a view which populate a json object, and then, at the end of the same view I would render an html page, but also return the final json. probably this is not relevant but the json would be for example something like this: { "embedToken": "dasfgjasdàgjasdàgasdàgèe-AveryLongToken", "embedUrl": "https://app.powerbi.com/let's_go_to_the_lake", "reportId": "e615-sfash-9746" } the line I'm not able to fix (tried all day with all alternatives methods) is the following: return render(request, "home.html", jsn) my url.py is simple as follow: urlpatterns = [ path('', HomePageView, name='home'), ] I currently get the following error: context must be a dict rather than str. But I encountered all different kinds of errors on the way without succeding to reach the desired result(rendering the html and returning the json at the same time). So my doubt is that I'm taking the wrong approach at the basics, should I change road? I would like to try to convert the json into a dictionary , and then maybee convert it back in a json in javascript -
Keep Form Data after TemplateResponse
Is There any way to keep the input data by user after submitting form ( Django / Python / HTML ) I the input data one by one in dictionary then use TemplateResponse in the view to return dictionary , in HTML i use {{dict}} but it is not the optimum way Part of View if(request.GET.get('mybtn')): if str(request.GET.get('tech'))=="2G": dic={} dic['productname']=str(request.GET.get('productname')) # After calculation get price and should be returned dic['price']="50" return TemplateResponse(request,'cell.html',dic) Part of HTML <input style="width: 80%;" type="text" name="productname" required value={{productname}}> <label for="price">{{price}}</label> however , it is expected to return the price only and not the product name also as in the real case there are a lot of inputs and selections -
Why does localization work incorrectly at Django 1.11?
I translate the names of the application into Russian. But I do not understand why some applications are translated, while others are not. Here is an example. It's not work #: donation/apps.py:9 msgid "Donation" msgstr "Донат" It's work #: reputation/apps.py:9 msgid "Reputation" msgstr "Репутация" donation/apps from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class DonationConfig(AppConfig): name = 'donation' verbose_name = _('Donation') reputation/apps from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class ReputationConfig(AppConfig): name = 'reputation' verbose_name = _('Reputation') settings # Internationalization LANGUAGE_CODE = 'ru' USE_I18N = True USE_L10N = False LANGUAGES = ( ## Customize this ('ru', gettext('Russian')), ) LOCALE_PATHS = ( path('locale'), ) -
The key "(User_id) = (51)" already exists
ERROR: repetitive record violates the singular constraint "user_otherinfo_user_id_key" DETAIL: The key "(user_id) = (52)" already exists. models.py class OtherInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone = models.CharField(max_length=11,verbose_name="phone number") location = models.CharField(max_length=50,verbose_name="location") profile_image = models.FileField(blank = True,null = True,verbose_name="image") class Meta: verbose_name_plural = 'Diğer Bilgiler' @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: OtherInfo.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.otherinfo.save() forms.py class LoginForm(forms.Form): username = forms.CharField(label = "Username") password = forms.CharField(label = "Parola",widget = forms.PasswordInput) class RegisterForm(forms.ModelForm): password1 = forms.CharField(max_length=100, label='Parola',widget=forms.PasswordInput()) password2 = forms.CharField(max_length=100, label='Parola again', widget=forms.PasswordInput()) phone_number = forms.CharField(required=False, max_length=11, label='Phone Number') location = forms.CharField(required=False, max_length=50, label='Location') profile_image = forms.FileField(required=False, label="Image") class Meta: model = User fields = [ 'first_name', 'last_name', 'email', 'username', 'password1', 'password2', 'phone_number', 'location', 'profile_image', ] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match!") return password2 class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileForm(forms.ModelForm): class Meta: model = OtherInfo fields = ('phone', 'location', 'profile_image') views.py @login_required @transaction.atomic def updateprofile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.otherinfo) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, _('Profiliniz başarıyla güncellendi!')) return redirect('/kullanici/profil/') else: messages.error(request, _('Lütfen aşağıdaki hatayı … -
How to serve static and templates individually for every site in Wagtail CMS multisite
I'm trying to create multisite Wagtail project using included Django Sites framework. I could not find in Wagtail documentation how to serve templates and statics for each site individually. Could anyone help me with advise or a link to some tutorial? Thanks. -
Nginx + django return 404 when first configurated
When I visit "localhost/media/media.png" it returns 404 but the file already exists in the folder. How can I solve the problem? I am learning Python and I want to build a website with nginx, uwsgi and django so I read the official tutorial on https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html?highlight=django to configurate the my web server. But I got into trouble when I "Configure nginx for your site". The tutorial doesn't seem to work on my computer. python version: 2.7.15rc1 nginx version: 1.14.0(Ubuntu) django version: 1.11.20 # cs_community_site_nginx.conf upstream django { server 127.0.0.1:8001; } server { listen 8000; server_name 10.**.**.231; # charset utf-8; client_max_body_size 75M; location /media { alias /mnt/c/Users/duyu0/Documents/starfire/cs_community/cs_community_server/cs_community_site/media; } location /static { alias /mnt/c/Users/duyu0/Documents/starfire/cs_community/cs_community_server/cs_community_site/static; } location / { uwsgi_pass django; include /mnt/c/Users/duyu0/Documents/starfire/cs_community/cs_community_server/cs_community_site/uwsgi_params; } } -
How to relate two different django models into on many to many field form another one?
I'm trying to find a solution to the following problem with django models: The app would add products to a shopping cart. The problem is that those products come from different models, and no matter where they come from, I'd like to use one ManyToManyField to incorporate them. Suppouse I've two different kind of products from two different models: Class ListOfProducts1(models.Model): name= CharField() price= IntegerField() Class ListOfProducts2(models.Model): name=CharField() price=IntegerField() The following model would be used for get the quantity and the product added(and then related to one particular order). Here is the problem. Look to the field itemsadded, where I want to relate this field to ListOfProducts 1 and 2. I'd put both of them into the same field, but I've already know this is not possible. Just for better understanding of the problem here you have: Class ProductsOrdered(models.Model): itemsadded= OneToOneField(ListOfProducts1 and ListOfProducts2,on_delete=models.CASCADE) Quantity = IntegerField() Then the Order's model: Class Orders(models.Model): cart= ManyToManyField(ProductsOrdered) -
Run django shell in context of systemd service
I need to run Django shell in context of Django application systemd service. The Django application is managed by systemd. In development environment secrets are set as environment variables right in service unit file as follows: [Service] Environment=SECRET_KEY=wow_such_secret_so_key Occasionally, I need to run Django commands that alter some data in database. In this case I need to provide database password as well. If my command uses some external API, I also need to provide credentials for that. At the moment I have to run these commands as follows: DB_PWD=very_secret API_CREDS=so_password python manage.py custom_django_command Is there a way to run Django shell so that it can access environment variables, but without explicitly specifying them? -
[Pybel][Openbabel]IndexError: list index out of range
I'm working on a web app django, when I install openbabel and try to import pybel i've got an error I install openbabel like this: sudo apt-get install python-openbabel I also tried : apt-get install openbabel libopenbabel-dev swig Then I did : pip install openbabel after that, I've tried to import pybel (after importing openbabel) This is actuall result : >>> import pybel Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/etudiant/QuChemPedIA/QuChemPedIAProject/venv/lib/python3.5/site-packages/pybel.py", line 94, in <module> descs = _getpluginnames("descriptors") File "/home/etudiant/QuChemPedIA/QuChemPedIAProject/venv/lib/python3.5/site-packages/pybel.py", line 84, in _getpluginnames return [x.split()[0] for x in plugins] File "/home/etudiant/QuChemPedIA/QuChemPedIAProject/venv/lib/python3.5/site-packages/pybel.py", line 84, in <listcomp> return [x.split()[0] for x in plugins] IndexError: list index out of range Any help please? -
Django, pagination shows only one page
I am trying to do the pagination of the index page to show the latest entries in the database, the problem is that when trying to do the pagination, it only shows me the 4 first objects and nothing else, even though it renders the page numbers correctly, in my case i have 15 entries in db so it renders Page 1 of 5 and that is correct because each page should contain 4 entries as in paginator = Paginator(car_list, 4), when it type at url ?page=2 it still renders the same page over and over. #view def index(request): car_list = Car.objects.all().order_by('-created') car_types = CarCategory.objects.all() paginator = Paginator(car_list, 4) page = request.POST.get('page', 'Default') cars = paginator.get_page(page) context = {'cars': cars, 'car_types': car_types} return render(request, 'index/index.html', context) And in my case if is_paginated seems to be false because it does not render the buttons, but when it remove that part then it renders the button but still the problem of showing only one page persists. #html {% if is_paginated %} <div class="pagination h3"> {% if cars.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ cars.previous_page_number }}">Previous</a> {% endif %} {% for num in cars.paginator.page_range %} {% if cars.number … -
Django Forms - How to Save multiple inputs(type=radio) with the same "name" attribute?
I'm currently working on a survey app. I am using django forms, however I find myself with the following problem: If I only have one question there is no problem in saving the answers, but if there are several questions there is a problem because the template is rendered in the following way: {% for item in items %} <div class="options"> <input type="radio" name="answer" id="a{{ forloop.counter }}" value="A" /> <label for="a{{ forloop.counter }}">Agree</label> </div> <div class="options"> <input type="radio" name="answer" id="b{{ forloop.counter }}" value="D" /> <label for="b{{ forloop.counter }}">disagree</label> </div> So for example if I render 5 questions, the inputs of those 5 questions will have the same attribute name, so I can only choose one radiobutton, which logically is an error because I should be able to choose 5 (because they are 5 questions). I could change the name of each group of radiobuttons according to the question to which I allude, and with that each group of radiobuttons would have different names, however if I do this I could not save them because according to my forms.py: class SurveyForm(forms.ModelForm): class Meta: model = Survey fields = ('answer' , ) Then to the being the names of the radiobuttons different … -
How to send data from html (Django backend) to js (Vue frontend)
I'm developing a webpage. I have a login form in this webpage. I'm using Django for back-end and VueJS for front-end. To submit the form with Django, the requirement of Django is the CSRF Token. I currently can show the CSRF Token to HTML using {{ csrf_token }}. Because I am using VueJS, I also use Vuetify to style the front-end. The CSRF Token is not visible to VueJS because VueJS doesn't recognize {{ csrf_token }} but HTML does. After researching on the internet I found something. I tried using v-bind to give the CSRF Token from HTML to VueJS but unfurtunately the value of the v-bind is undefined. But if I go to my sourcecode (Ctrl+U), I can see that CSRF Toekn does work but VueJS does not recognize it. Example: <div id="LoginApp"> <WJLogin v-bind:csrf="8cl33zQ8pYXXEMVCoSsqIzaFgQkLh6WYXqsQMN4z9X4oGkSGN8Thz922jQ19aG4B" v-bind:hello="world"> </WJLogin> </div> When I use v-bind from VueJS to VueJS this works but from HTML to VueJS doesn't work This is login.html <div id="LoginApp"> <WJLogin :csrf="{{csrf_token}}" :hello="world"> </WJLogin> </div> This is WJLogin.vue export default { props: { csrf: String, hello: { type: String, default: "defaultValue" }, }, I expect the value of CSRF Token is accesable to VueJS. -
Method for optionally nested models in Django
I am creating a simple internal asset tracking app for my company. Currently we do this through excel (terrible). I'm breaking this down to: Asset/Item - The tool, hardware, part etc. Site - The overall location it's at: Facility A, Site Location B Bin - A sublocation an asset is located, this could be a building, a toolbox, a crate. The Bin is causing me problems because an Item can be location at a Site without a Bin, or a Bin can be located inside another Bin, I am not yet sure the best way to structure this database. I have tried having multiple foreign keys but that gets messy or atleast feels so. I have also tried using the alternatives to Django's GenericForeign Keys as listed here I have used them before with subtly different apps but the self referencing is confusing me. In the end I want to be able to gather a list of items at a site and then have indented lines for each toolbox and the items inside, is there a good method for setting up the models so this can happen? -
How to render all instances of a form class in Django
I am tracking multiple measurement values for each user, the values are input by the user. But the user gets a suggestion as to what measurement he should do on a specific day. Each kind of measurement is an instance of a class-based model (Measurement). I am tracking them for each user in a separate class-based model (MeasurementTracking) and another class-based model (Day) holds the information as to what measurement will be suggested to the user. Now how can I return a list of all suggested measurements for a specific day to my template? I've been researching quite a while and couldn't figure out what the best approach would be. (looked into formsets etc.) models.py : class Measurement(models.Model): def __str__(self): return self.title title = models.CharField(max_length=100) unit = models.CharField(max_length=100, blank=True) track = models.ManyToManyField(Profile, through='MeasurementTracking') #Tracking who measured what, when and with which result via: class MeasurementTracking(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) measurement = models.ForeignKey(Measurement, on_delete=models.CASCADE) value = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) #CMS model measured on a specific program day class Day(models.Model): def __str__(self): return str(self.program_id) + ' Day ' + str(self.day_num) day_num = models.IntegerField(verbose_name='Day number in a given week') program_id = models.ForeignKey('Program', on_delete=models.SET_NULL, null=True, blank=True, related_name='program_id') program_measurement = models.ManyToManyField(Measurement, blank=True) In another … -
How do I turn an existing python app into a django web app?
I want to turn an exisiting python programm into a web application powered by django. The program expects an input file, analyzes it and outputs the evaluation. Right now it is initiliazed through command line input. I need a web app where you can upload the file, then the programm (which should be implemented into the django framework) analyzes this file and outputs the evaluation to the website. How do I make my program compatible wth the MVC Template of Django (How should I best approach this project)? How do I make the website use my program? Thank you -
What are the possible attacks for a site which takes markdown input
I am developing a Django app, which has a form field., accepts markdown text as a input., what are the possible attacks like XSS i need to prevent., -
Angular 6 web application integration with Django server
I am developing a new web application using Angular 6 with Django as my backend server. Please share me the resources on how to proceed further and what is the best way to implement. -
Database Routing by URL parameter
I'm developing on a Django Project with several Databases. In an App I need to switch the database connectivity from a Development-Database to Test-DB or Production-DB, based on a request from the user. (DB Architecture is set and not changeable!) I Tried my luck also with this old Guide here Does not work. Within the DB Router I have no access to the threading.locals. I tried it also to set up a custom db router. Over a session variable, I tried to set the Connection string. To read the users Session in the dbRouter, I need the exact Session key, or I have to loop throw all Sessions. The way over object.using('DB_CONNECTION) is a not acceptable solution… To many dependencies. I want to set a connection globally for a logged in User without giving the DB connection to each models function…. Please give me some imput how to solve this issue. I should be able to return the dbConnection in a db Router based on a session value... def db_for_read|write|*(): from django.contrib.sessions.backends.db import SessionStore session = SessionStore(session_key='WhyINeedHereAKey_SessionKeyCouldBeUserId') return session['app.dbConnection'] -
How to fix extra fields bug in TabularInline admin django?
My TabularInline form in Django admin is showing fields in a wrong way. Only title is duplicated in grey and get_url link is poorly located. Well the code is really simple and I am not able to debug it by myself. I have tried setting fields and exclude fields to not display title_cs and get_url fields with no success, these fields are rendered over original ones. class InfographicInLine(admin.TabularInline): model = Infographic extra = 0 # list_display = ( # 'title_cs', 'get_url', 'show_on_frontpage', 'author', # 'image_tag') list_editable = (None,) exclude = ('title_cs', 'get_url') fields = ( 'title_en', 'author', 'keywords_cs',) class InfographicAdmin(ActiveFlagModelAdmin): list_display = ( 'title_cs', 'title_en', 'get_url', 'section', 'show_on_frontpage', 'author', 'created_date', 'last_modified', 'image_tag') list_editable = ('title_en', 'show_on_frontpage') list_filter = ('section', 'created_date', 'last_modified', 'author') fields = ( 'title_cs', 'title_en', 'section', 'infographic_url_cs', 'infographic_url_en', ('thumbnail_cs', 'image_tag'), 'thumbnail_en', 'author', 'keywords_cs', 'keywords_en') search_fields = ('title_cs', 'title_en', 'description_cs', 'description_en',) exclude = ('slug', 'embed_code_cs', 'embed_code_en') # prepopulated_fields = {'slug': ('title_cs',)} readonly_fields = ('image_tag',) def image_tag(self, obj): if obj.thumbnail_cs: return mark_safe('<img height="75" width="105" src="/media/%s" />' % obj.thumbnail_cs) else: return "" def get_url(self, obj): if obj: return mark_safe('<a href="' + settings.STARFOS_BASE_URL + obj.get_absolute_url() + '" >' + 'Ukázat na stránce' + '</a>') else: return None register(Infographic, InfographicAdmin) @admin.register(Section) class SectionAdmin(ActiveFlagModelAdmin): … -
2 different forms working with the same cookie
I have user model(django user model) and two forms for login and user create. I want to tell step by step. Login as "Raşit". (username=Raşit,password=123) This information was saved in the cookie. I'm opening the user creation page. The cookie is here. I don't want this cookie on the user create page. forms.py class LoginForm(forms.Form): username=forms.CharField(widget=forms.TextInput(attrs={'id':'LoginUserName'})) password=forms.CharField(widget=forms.PasswordInput(attrs={'id':'LoginPassword'})) class UserCreateForm(forms.ModelForm): class Meta: model = User fields = ["username","password","first_name","last_name","email"] widgets = { 'username':forms.TextInput(attrs={'id':'UserCreateName'}), 'password':forms.PasswordInput(attrs={'id':'UserCreatePw'}), 'first_name':forms.TextInput(), 'last_name':forms.TextInput(), 'email':forms.TextInput(), } -
How to create a view function for a URL that is not a part of any app?
I have a Django project called "Reports". The projects will have three apps: "Report_1", "Report_2" and "Report_3". I want to have a home page where the user could choose a report and respective app will be launched. Therefore, I would write the project's urls.py like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Report_1.urls')), path('', include('Report_2.urls')), path('', include('Report_3.urls')), ] and then create urls.py for each app. However, such home page would be one level above the apps, so where do I write a view function for it? Or is this approach broken by design and I should try something else?