Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error saving data to database
i'm using Django-models for saving data to database? but i have a problem, a new record has a incorrect id's (i need saving some records in "for") i have a error: IntegrityError: (1062, u"Duplicate entry '46' for key 'PRIMARY'") Views: def post(self, request, *args, **kwargs): if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE'] and request.is_ajax(): data = request.POST project = feedback.models.Project() subject = Subjects() SUBJECTS = json.loads(data['subjects']) project.project_name = data['project_name'] project.project_domain = data['project_domain'] project.required_group_id = 3 #TODO project.project_id_teamwork = data['teamwork_id'] project.email_support = data['support_email'] project.slack_channel_name = data['slack_channel_name'] project.id = 'NULL' for i in range(len(SUBJECTS)): subject.name = SUBJECTS[i] subject.id_task_list_teamwork = data['teamwork_task_list_id'] i = i + 1 subject.project_id = 3 # TODO subject.save() -
Django-jet admin- add button for each row each row
I want to create a button that deletes the selected row in the table (1 button per row) admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from import_export.admin import ImportExportMixin from .models import Applicant class ApplicantAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('Name', 'DOB', 'PhoneNumber', 'Address', 'Batch', 'created_at', 'updated_at',) list_filter = ('Name', 'Address', 'Batch', 'created_at', 'updated_at',) list_per_page = 10 # actions = [transferdata, ] # Register the admin class with the associated model admin.site.register(Applicant, ApplicantAdmin) models.py from django.db import models from django.utils import timezone class Applicant(models.Model): id = models.CharField(max_length=10).primary_key Name = models.CharField(max_length=50) DOB = models.CharField(max_length=10) PhoneNumber = models.CharField(max_length=20) Address = models.CharField(max_length=200) Batch = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.Name I already know django-jet that provides this facility a drop-down menu, but for the whole table (i.e. not for the each row) -
Serialization of parent model including child models
I have models - Commodity, Clother and child models, as Acessories, Outwear, etc.: class Clother(models.Model): commodity = models.ForeignKey(Commodity) class Acessories(models.Model): clother = models.ForeignKey(Clother) class Outwear(models.Model): clother = models.ForeignKey(Clother) How can I serialize parent model Commodity to call all vertical dependencies. I suppose to query Commodity id and get all Clother attributes and Acessories or Outwear attributes. Thanks! -
Template is not rendering form
forms.py class password_reset(forms.Form): password1 = forms.PasswordInput(attrs={'palceholder':' type password'}) password2 = forms.PasswordInput(attrs={'placeholder':'type password again'}) def clean(self): data = self.cleaned_data password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 != password2: raise forms.ValidationError('Password Mismatch') return data views.py def password_resetView(request): if request.method == 'POST': form = password_reset(request.POST) if form.is_valid(): password = form.cleaned_data['password1'] obj = User.objects.get(username = request.user) obj.set_password(password) obj.save() form.save() else: form = password_reset() return render(request,'password_reset.html',{'form':form}) template <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> so i cant able to render form in template.. no error showing, its rendering to the respective html but doesnt render the form. -
how to concatenate if template django with variable js
I would like to know if it is possible to concatenate django template, I made many attempts but none succeeded. as below <script> function seeDetail(researcher_id) { let convert_int_researcher_id = parseInt(researcher_id) $('#detailRearcher').empty(); let element= ` <br> <h2> Detalhes do pesquisador selecionado </h2> <div class="panel panel-default" id="panel"> <div class="panel-body"> <div class="col-lg-6 col-md-6 col-xs-6"> <h2>Artigos</h2> {%for show_list_article in show_list_articles %} {% for article in show_list_article%} {% if article.researcher_id `+ researcher_id+`%} {{article.researcher}} <div class="row"> {{article.title}} </div> {% endif %} {% endfor %} {% endfor %} </div> <div class="col-lg-6 col-md-6 col-xs-6"> <h2>Projetos</h2> {%for show_list_projeto in show_list_projetos %} {% for project in show_list_projeto%} <div class="row"> {{project.title}} </div> {% endfor %} {% endfor %} </div> </div> </div> `; $('#detailRearcher').append(element) } but when I do this this error happens django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '`+' from '`+' if anyone can help me and explain why I will be totally grateful. Yes I saw it in the console.log and this is actually a string type value and I tried to convert it, but the same error occurs. -
How to check and store particular time-period in Django?
I have to store restaurants in my table in Django model. Each restaurant has its opening and closing time. How should I store these in Django? Then I have to check if a particular restaurant is open or not with respect to the current time a user search for available restaurants. How to store two times and compare it with the current time. -
Easiest way to manually build a DB in Django
I am building a small API and I would like to manually build a short database of products, to display them in my view. What would be the simplest way to populate this database? Should I create a file, if so in which format and in which directory should I put it? Or should I use the Python shell? Thanks! -
Django REST API - add POST field to Swagger docs
I've been trying without success to see if I can modify the auto-generated Swagger doc. for a Django API to allow post parameters to be sent. Here's an example: class AllModelSummary(MultipleModelAPIView): """ This route will also accept a csv list of filter parameters: ?types=standard,biodbcore,policy. If this parameter is not specified then it will return all types. ?search=term will search for term on name, description and doi fields. """ filter_backends = (SearchFilter,) search_fields = ('name', 'description', 'doi') flat = True permission_classes = (HasAPIAccess, ) pagination_class = PaginationWithLicence def get_queryList(self): types = self.request.query_params.get('types', None) query_list = () if types: for t in types.split(','): if t == 'policy': query_list = query_list + ((Policy.objects.all().order_by('pk'), PolicySerializerMiniList),) elif t == 'standard': query_list = query_list + ((Standard.objects.all().order_by('pk'), StandardSerializerMiniList),) elif t == 'biodbcore': query_list = query_list + ((BioDBCore.objects.all().order_by('pk'), BioDBCoreSerializerMiniList),) else: query_list = ( (Policy.objects.all().order_by('pk'), PolicySerializerMiniList), (Standard.objects.all().order_by('pk'), StandardSerializerMiniList), (BioDBCore.objects.all().order_by('pk'), BioDBCoreSerializerMiniList), ) return query_list At localhost:8000/api I will see 'page' and 'search' input boxes for this particular route, but nothing for 'types'. Is there any means of modifying this to add the additional field to the Swagger page? I've not had any luck with the documentation. -
FutureWarning: `TemplateForHostMiddleware` is deprecated. Please upgrade to the template loader
I am building a mezzanine website. I installed mezzanine by typing pip install mezzanine this installed django 1.9 (IIRC) along with mezzanine. I then installed cartridge, which upgraded django to version 1.10.8. Now when I run runserver at the command line, I get the following warning at the command line: /path/to/env/lib/python3.5/site-packages/django/core/handlers/base.py:58: FutureWarning: TemplateForHostMiddleware` is deprecated. Please upgrade to the template loader. How do I resolve this warning - as the warning is not very clear (i.e. upgrade which template loader and also, what does it mean to upgrade the template loader?) -
Safe to use asyncio in Django?
I have a small Django app that is highly dependent on other services. In one situation, the client makes one request to our app, and the Django app makes 3 or 4 requests to another server, aggregates the data, and saves it. This is a slow process as I need to make these calls synchronously although there is no requirement for the requests to be made sequentially. Given the above, this particular set of calls seem like a good candidate for async programming and the asyncio package is provided with newer Python versions. I’ve implemented what I have described using loop.run_until_complete and hooked it into a view and it seems to work fine, as well as provide a significant performance increase. However, I am worried that I am missing something in the magic. Doing multiple google searches on whether this is a good idea in Django has given me a mixed bag of answers and I’m still unclear on the negatives of doing so. I realize this could all be done by JavaScript client in a well supported manner, I’m just trying to reduce complexity on that side, and am more interested in the implications of doing this running Django … -
Django, invalid literal for int() with base 10: 'user'
queryset (views) def coin_profile(request, user, coin): test = Transaction.objects.filter(user = user, coin = coin) model field class Transaction(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) Returns this error. That means that the queryset is expecting an integer when I use user = user, but why? And how can I pass my user names to this query? -
Button as both submission and calling a function
I have a Django query where in would take month as input and display pdf file with the query data. element = request.GET.get('q') query=employeeModel.objects.filter(month__contains = element,username = request.user).values_list() this is template of that query <h1>Employee PaySlip Generation</h1> <h5>Hello {{request.user}}</h5> <form method="GET" action=""> <span><input type="text" name='q' placeholder="Search: Month" value="{{ request.GET.get }}"/></span> <span><input class="btn btn-primary btn-sm" type="submit" value="Search" > </form> I dont understand how to and what to do so, button would not only submit typed value to the query but also call pdf_generate function. -
Array of Object Model
I'm beginner with Django and I have problem to register model array of object from another class Example: class Trigger(models.Model): id = models.IntegerField() name = models.TextField() description = models.TextField() class Host(models.Model): id = models.IntegerField() triggers = [] # <--- Array of Trigger instances here How can I rewrite empty bracets to django model? -
Django: How display a different image according to my function in views.py
I would like to display an image in function of my views. For Example if I have value in my database "100" for a user, my website show me a specific Image if the value is not "100" it shows me another Image. I wrote a simple code with "print" but I do not know how replace "print" with an image and then display it on my page. this my views.py def Test(request): if request.user.is_authenticated: try: name = coach.objects.get(user=request.user) except coach.DoesNotExist: name = coach(user=request.user) objs = Lesson.objects.all().filter(mycoach = name) args = {'objs': objs} if name.monday=="100": print("Monday") else: print("Not Monday") messages.add_message(request, messages.INFO, 'Welcome to your profile') return render(request, 'test.html', args) else: return render(request, 'home.html') -
What is the meaning of the expression A('pk') in Django
I'm trying to setup a LinkColumn and I've seen in the examples that a the args parameter has usually the form args=[A('pk')]. I'm wondering what is the meaning of the A(). -
How to find good database indices automatically in Django?
This feature would be really useful, and not that hard to implement, so it must already exist, but I can't find it: Can I tell Django to keep track of the way I use my database and recommend indices based on the way it's used? Something like "Table A should have an index on columns B and C, because those get used most frequently". In most cases it is easy enough to remember what queries you are using the most, but if I miss a single type of query then that will result in a large slowdown and it will take me a lot of testing to find out. There ought to be a way to automate this, since Django is already able to log all database accesses anyway. -
How to use form.cleaned_data django
After form.is_valid(), we get form.cleaned_data. How can i use this cleaned data on the next page. For example, after the form page is processed we redirect the customer to next page, where I want to use the cleaned_data's info like name, contact, address..etc fields to be shown in next page. def ind(request): if request.method == 'POST': form = form_name(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, 'app_one/abc.html', {'data': form.cleaned_data}) # form.save(commit=True) # return render(request,'app_one/index.html') else: form=form_name() return render(request,'app_one/index.html',{'form':form) -
can\t view django 2.0 admin page
I've just been porting to Python3 from 2 and upgrading Django from 1.7 to 2.0 (massive changes I know). I'm using Heroku to host the app. When I run heroku local or just run the app locally with manage.py runserver the app loads but navigating to the /admin page comes up with the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:5000/admin Using the URLconf defined in loowatt.urls, Django tried these URL patterns, in this order: write/ admin/ ^$ [name='index'] The current path, admin, didn't match any of these. My new app.urls.py looks like this: 1 from django.contrib import admin 2 from django.urls import include, path 3 4 from . import views 5 6 urlpatterns = [ 7 path('write/', views.write), 8 path('admin/', admin.site.urls), 9 path('', include('units.urls')), 10 ] And my settings have all the correct middleware, context processors,for the admin settings 21 INSTALLED_APPS = [ 22 'django.contrib.admin', 23 'django.contrib.auth', 24 'django.contrib.contenttypes', 25 'django.contrib.sessions', 26 'django.contrib.messages', 27 'units.apps.UnitsConfig', 28 # Disable Django's own staticfiles handling in favour of WhiteNoise, for 29 # greater consistency between gunicorn and `./manage.py runserver`. See: 30 # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 31 # 'whitenoise.runserver_nostatic', 32 'django.contrib.staticfiles', 33 'import_export', 34 'rangefilter', 35 ] 37 MIDDLEWARE_CLASSES = [ 38 … -
How to call scrapy spider inside django view using spider.CrawlerRunner() or CrawlerProcess()
After going to all the links in Stack Overflow as well as other git etc. too, I am unable to solve my error. Basically, I want to scrap instagram by giving specific hashtag i.e. User will give a hashtag from Django UI and Django function will send that hashtag to scrapy spider for crawling using scrapy.spider.spider.CrawlProcess() Hope for the help ! Following is my code: django/models.py from django.db import models class InstaAccountDetails(models.Model): website = models.URLField() post_id = models.PositiveIntegerField() shortcode = models.CharField(max_length=200) caption = models.CharField(max_length=500) display_url = models.ImageField() loc_id = models.PositiveIntegerField() loc_name = models.CharField(max_length=200) loc_lat = models.IntegerField() loc_lon = models.IntegerField() owner_id = models.PositiveIntegerField() owner_name = models.CharField(max_length=200) taken_at_timestamp = models.DateField() def __str__(self): return self.owner_name django/views.py from django.shortcuts import render, redirect from django.http import JsonResponse from scrapy.crawler import CrawlerProcess, CrawlerRunner from scrapy.utils.project import get_project_settings from instagram_scrapy.instagram_scrapy.spiders.instaCrawler import InstagramSpider def home(request): return render(request, 'instagram_link_app/homePage.html') def get_insta_details(request): field_value = request.GET.get('value_holder') print("request value ::::::::::::::: ",field_value) try: if field_value: return JsonResponse({"msg:" "Hii"}) process = CrawlerProcess(get_project_settings()) process.crawl(InstagramSpider(hashtag=field_value)) process.start() #the script will block here until the crawling is finished print(process) data['process'] = process return JsonResponse(data) else: return JsonResponse({'message': 'None'}) except Exception as e: return JsonResponse({'message': str(e)}) scrapy/settings.py import os import sys import django BOT_NAME = 'instagram_scrapy' SPIDER_MODULES = ['instagram_scrapy.spiders'] … -
Calculate distance by coordinates Elasticsearch DSL
I'm need calculate distance between some points. I foud, how filter by coordinates: MyIndex.search().filter('geo_distance', distance='1500m', location={"lat":"22.492", "lon":"32.356"}) but, I want to add calculate distance for each object, and result save in the distance field. How make this? The field distance is absence in model, it should add in each object with calculated distance. Similarity to an annotate by Django. Thanks -
Active connection to a TCP server from Django
I have a Django app, which needs to communicate with TCP server running on an embedded device. Can I create a client from Django running any custom management command, and reuse this connection each time when I need to communicate with the embedded server. Is there any existing stack/package to handle similar scenarios from python, Reusing the socket connection for each URL request without closing the connection. -
Is there any doc about File downloads in Django2?
I am using django2 for my web project and here is the doc about file upload https://docs.djangoproject.com/en/2.0/topics/http/file-uploads/ However,i want to download file on my website when i click a button or a link can anyone help offer some docs about this? -
django - How to open raw_id_fields - links in a popup?
I am using django-grappelli and I have two models Content its related pendant ContentContainer, which shall be edited via django's admin interface through a popup from a model ContentContainerAdmin. class Content(models.Model): text = models.TextField() class ContentContainer(models.Model): content = models.ForeignKey(Content) class ContentAdmin(admin.ModelAdmin): pass class ContentContainerAdmin(admin.ModelAdmin): raw_id_fields = ('mastercontent', ) fieldsets = ( (None, { "fields": ('mastercontent', ) }), ) Now the add-Link on the magnifying glass is already opened via popup, but the change-Link should do this also. Is there already nifty option for that? My google research did not approve itself. -
Result of a query filter to List Python
I did a query filter and the result returned is in a tuple form. I want it to be in a list. project_work = Project.objects.filter(title = topic).values() lip = [] for con in project_work: lip.append(con) And this is the output: [{'id': 24, 'title': 'A mobile-based distress calls management system for security departments in tertiary institutions', 'reg_num_id': '2014/15634', 'supervisor': 'Mr. Jeff', 'platform': 'MA', 'year': '2018'}] But i want a list like this: [A mobile-based distress calls management system for security departments in tertiary institutions', '2014/15634',....] -
Why am I getting ModuleNotFoundError: No module named 'django_cassandra_engine' when it is already instaled?
I am trying to create a django app using this tutorial. In settings.py, under INSTALLED_APPS, I have written: INSTALLED_APPS = [ 'django_cassandra_engine', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] And in Databases, I have this: DATABASES = { 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'db', 'TEST_NAME': 'test_db', 'HOST': 'localhost', 'PORT': '8160', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 } } } } When I try to create an app appy, I get this: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/anuj/Django Test Projects/newenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/anuj/Django Test Projects/newenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/anuj/Django Test Projects/newenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anuj/Django Test Projects/newenv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/anuj/Django Test Projects/newenv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/anuj/Django Test Projects/newenv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_cassandra_engine' But when I did pip3 install django_cassandra_engine in a separate terminal window, it says that requirement is already satisfied : Requirement already satisfied: django_cassandra_engine in /usr/local/lib/python3.6/dist-packages (1.2.2) …