Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inserting data in a DateTimeField() in Django by using datetime-local
Please, I am creating a to-do list app as my first django project. My form is not valid because I am trying to insert DateTimeField in django using datetime-local. I did research, I discovered I need to do a custom model so I parse the datetime-local field. Pls guide me on how to create a custom model field. -
save() and object.create note worked in django
I'm new, trying to save and fail gives an error message, whsts do? p.save() and p=Post.objects.create not worked enter image description here -
Search and filter a list of lists
thanks for your time, I'm new in Python so I got this list of lists: raw-list = [ [((733, 706), (810, 733)), 'Joe'], [((748, 613), (815, 637)), 'Harold'], [((748, 614), (815, 638)), 'Harold'], [((815, 614), (882, 638)), 'Walter'], [((816, 614), (883, 638)), 'Walter'], [((883, 613), (950, 637)), 'Parker'], [((883, 614), (950, 638)), 'Parker'], [((902, 694), (969, 718)), 'Ernesto'], [((950, 613), (1017, 637)), 'Max'], [((950, 614), (1017, 638)), 'Max'] ] I would like to delete all the lists that already have a name that has been mentioned previously to obtain this: filtered_list = [ [((733, 706), (810, 733)), 'Joe'], [((748, 613), (815, 637)), 'Harold'], [((815, 614), (882, 638)), 'Walter'], [((883, 613), (950, 637)), 'Parker'], [((902, 694), (969, 718)), 'Ernesto'], [((950, 614), (1017, 638)), 'Max'] ] How can I achieve that?, Thanks to everyone! -
Time SQL Queries in Django
Is there a way to time sql queries in Django? I know there's such thing in dj debug toolbar but I just need to display time on my web-page. Since I can get a number of queries with: len(connection.queries) Maybe there's a similar way to get the time? -
How to get the current URL within a LoginRequiredMixin,UpdateView (Django template)?
I want to edit a data. For that I have to click on a button from my main page. I would like by clicking on the edit button, send the url to the page edition. And once I finish the changes, I'll want to go back to my main page. Here is the sequence of actions in pictures: --------------------------------------- Here is the view: class A_UpdateView(LoginRequiredMixin,UpdateView): template_name = 'page_form.html' login_url = '/login/' form_class = A_Form model = Team def form_valid(self, form): g_urls = self.request.POST.get('id_path') object = form.save(commit=False) form.instance.last_user = self.request.user.username self.object = form.save() return super().form_valid(form) def get_success_url(self): return reverse('g_urls') Here is the template: <form class="btn-group" id="login_form" method="get" action="{% url 'A_UpdateView' pk=f.pk %}"> <input type="hidden" name="id_path" id="id_path" value = "{{ request.build_absolute_uri }}" > <button class="btn btn-success" id="aaa" name="aa" type="submit"></button> </form> Here is the template to edit: <form method="POST" class="post-form"> {% csrf_token %} <!--{{form.as_p}} --> <table class="table table-bordered table-fit" border="0" > {{ form }} </table> <button type="submit" class="save btn btn-default">OK</button> </form> Thank. -
Ionic To Django POST data auto name change
Hi I am building an application in which my Ionic App need to send a post message to Django Backend. My data at Ionic end during pos seem to be like this // This is the value from ion-select with multiple set true let data = {'selectedId':[1,2,3,4,5,6]} In my django request.POST the data is converted like this <QueryDict : {u'selectedId[]' : [u'1',u'2',u'3',u'4',u'5']}> Why does the key value automatically converted from "selectedId" in Ionic to "selectedId[]" if i try to get the array value in Django by performing request.POST['selectedId[]'] this give me the length of the array 5 request.POST['selectedId'] this give me a MultiValueDictKeyError -
Django saves and updates slow down on partitioned table, but queries are much faster
I have identical tables in Postgres9 and Postgres10, except that the Postgres10 table is partitioned by state. When I make a query like this, it is about 10 times faster on the partitioned table than on the Postgres9 unpartitioned table. hooray! parcels = Parcel.objects.filter(state='15', boundary__intersects=polygon) But when I try to make an update like: for parcel in parcels: do something parcel.save() It is about 100 times slower on the partitioned table than on the Postgres9 version. Is this a common issue with partitions or with Postgres10? -
Uploading image into media directory in a form just by changing the field
i need when i just change the file field ajax send it to the save function in view and upload my image , if you have any better solution i waiting to hear of you tnx index.html <form action="{% url 'home:save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img" id="img"/><br/> <input type="submit" name="submit" value="Upload" /> </form> views.py def save(request): myfile = request.FILES['img'] fs = FileSystemStorage() filename = fs.save('easd09dasd.jpg', myfile) return HttpResponse('saved') js.js <script> $(function () { $('#img').change(function () { var file_data = $("#img").prop("files")[0]; var form_data = new FormData(); form_data.append("file", file_data); $.ajax({ type: 'POST', cache: false, contentType: 'multipart/form-data', url:{% url 'home:save' %}, data : form_data, enctype: 'multipart/form-data', processData: false, datatype:'json', }) }) }) </script> -
How do i integrate Django with Dialogflow?
I am new to Django and Dialogflow. I need to build a chatbot and need to code some backend logic in python and i don't know how to integrate them together. Any tutorials or links would help. Thank You -
Django debug toolbar - java error cannot find djdt
in console I am seeing the error below for debug toolbar: ReferenceError: Can't find variable: djdt Global Code — toolbar.js:306 I have everything setup as per https://django-debug-toolbar.readthedocs.io/en/latest/installation.html It did work but all of sudden no longer is and I'm pretty sure I didn't do anything to turn it off. anyone else come across this one? Thanks settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'api.apps.ApiConfig', ... 'storages', 'imagekit', 'django_celery_results', 'debug_toolbar', 'simple_history', 'crispy_forms', 'rest_framework', ) MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'simple_history.middleware.HistoryRequestMiddleware', ] INTERNAL_IPS = ('127.0.0.1') def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { 'JQUERY_URL':'', "SHOW_TOOLBAR_CALLBACK" : show_toolbar, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns -
filling django forms based on choice with models data as initial data
Need help regarding adding model class fields as initial data to our forms data. models.py class SourceCode(models.Model): source_description = models.CharField(max_length=80,unique=True) source_urls = ArrayField(ArrayField(models.TextField(blank=True),),blank=True,null=True) source_results = JSONField(blank=True,null=True) def __str__(self): return self.source_description forms.py class SourceForm(forms.Form): source_description = forms.ModelChoiceField(queryset=SourceCode.objects.all(),required=True) source_form_urls = forms.CharField(widget=forms.Textarea(attrs={'placeholder':'Enter URLS Here'})) I had created Source1 object & added https://stackoverflow.com value in source_urls field. Here's how it looks like: As soon as i select Source1 from forms.ModelChoiceField, i want it to show the source_urls field data of source_urls based on object selected by user. -
Django delete row from table of third level foreign key
I want to delete a row from model or table where I have the foreign_key value of the row to be deleted and the value of first level table row. For example, I have models say A, B, C where B is referring to A, C is referring to B. A id a b c 1 x y 100 2 y z 200 . . . . B id b_col a_id c_col 1 q 1 300 2 r 2 400 . . . . C id c_col b_id c_col 1 i 1 500 2 j 2 600 . . . . So here i have model C column c_col value which is 600 and model A column 'c' value=200 so want to remove row from model C where c_col=200. One way is, a = A.object.filter(c=200) b = B.object.filter(a_id=a.id) c = C.object.filter(b_id=b.id).delete() Is there any better way to do this in one single query instead of 3. -
Django queryset annotate calculated values from another model
Please help with the following: I have 4 models in a hierarchy: analysis, books, category and publisher. In my app you analyze books. The books belong to categories where you can view the average analysis rating of all the books in the category. This average rating (that I call avg-catg-rating) is not stored in the dB, it’s calculated in the view. Here’s my question: how do I get the average category rating for each category that the publisher has onto a single publisher view? In other words, how do I annotate the avg-catg-rating onto each category so I can display all of them on the publisher’s page? So do I iterate using the category somehow like this question? If yes, please give a tip on how because I'm not really sure how to go about it. I also tried groupby as suggested by this chap, but I could only get the count of book instances, I couldn't accurately annotate the avg-catg-rating. To clarify: Models.py: class Analysis: #a bunch of fields for analysis book = models.ForeignKey class Book: #a bunch of fields category = models.ForeignKey class Category: #a bunch of fields publisher = models.ForeignKey publisher/views.py: class ViewPublisher: def get_context_data(self, **kwargs): category_qs … -
Django 1.11: export queryset to csv using classes
I am having trouble exporting the results of a Django query to csv using a subclass of my query class as suggested here. https://stackoverflow.com/a/29678525/3973597 I end up with a Page not found (404) error. Here is the relevant code... views.py class QueryResultsView(ListView): template_name = 'query/query_results.html' model = StDetail context_object_name = "object_list" def get_queryset(self): form_input = self.request.GET filters = {"person_name": form_input.get('name'), "city": form_input.get('city'), } # delete keys that are None filters = {k: v for k, v in filters.items() if v is not ''} self.detail_data = get_list_or_404(self.model, **filters) return(self.detail_data) def get_context_data(self, **kwargs): context = super(QueryResultsView, self).get_context_data(**kwargs) context['query_results'] = self.get_queryset() return(context) class QueryResultsCsvView(QueryResultsView): # Subclass of above view, to produce a csv file template_name = 'query/QueryResults.csv' content_type = 'text/csv' urls.py app_name = QueryConfig.name urlpatterns = [ ... url(r'^query', QueryFormView.as_view(), name='person-query'), url(r'^results', QueryResultsView.as_view(), name='query-results'), url(r'^results/csv/$', QueryResultsCsvView.as_view(), name='query-results-csv'), ] query_results.html ... <a href="{% url 'query:query-results-csv' %}">Download Results</a> ... QueryResults.csv Date, City, Name, Sex {% for object in object_list %} {{object.date}},{{object.city}},{{object.name}},{{object.sex}} {% endfor %} The query works without any problems. However, when I click on the Download Results link I get a Page not found (404) error. Can somebody tell me what I'm missing? -
Django userCreationForm modify username in view
I am facing a problem with my Django application requirement. I have a signup form extending userCreationForm class and adding some extra fields to it. On my form in template (signup.html) I have email, password & zip only, no user name and I am suppose to set username at the server similar as user email+some hash. I have tried doing it in form class with clean_field, init, and clean. But nothing works. Every-time it's calling form_invalid method on the view. I fixed the form in form_invalid and called 'return self.form_valid', still no luck. I can't set the username on client end. Can one help me to figure out this. I have wasted three days already. Let me know if I am missing any information here. -
Problems with the schemes using multi-tenants and multilanguages in Django
1239/5000 Good day. I have built a system multi languages and simultaneously with multi-tenants with PostgreSQL database all this based on django. This system is with 12 languages (English, Portuguese, Spanish, Russian, Hindu, Arabic, German, Japanese, Chinese, Traditional, Simplified Chinese and Dutch). At the moment of entering the main page, from there anyone can change the language, when you click on the register, the person can be Arabic and I imagine that the person at the time of registering and entering the name of their work environment does with your native language. Thanks to the multi-tenants, this is added to the database. But if you write in your native language, this does not allow you to add a database and it throws me an error: ['Invalid string used for the schema name.']. I'm looking at some pages based on multi-tenants and I see the page "slack.com", when you register some environment as for example in Arabic language in the url is out as "w1544194703-qdg796900.slack .com". I do not know how that page really works, but that would be the idea that I can do. I would like to know some validation or example. Any answer in well taken, thank you … -
Generate urls automaticlly in django
I want to create an automatic RESP API for any Django project. At first, i can find all models in django project like this: from django.apps import apps for app in apps.get_app_configs(): for model in app.get_models(): ### do something with model here At second, I want to create an url, for example if the model name is lender, i want to create url /lender/, if borrower then /borrower/ etc. But i can't find a way to do this. Can anyone help me? -
Return values of custom authentication in Django REST Framework
I'm trying to write my basic custom authentication for Django REST Framework. I have the following auth backend: class JoeAuth(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_FORWARDED_USER') if not username: return try: user = User.objects.get(krb_name=username, active=True).name except User.DoesNotExist: raise PermissionDenied('Unauthorized user') return (user, None) Accompanied with a view: @api_view() def hello(request): return Response(data='hello') And of course enabled in settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'helloworld.auth.JoeAuth', ) } Now, if a request comes in and does not specify the HTTP_X_FORWARDED_USER header, the authenticate() function returns None. According so DRF docs: To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise. In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method. A None means authentication failed and should ideally return 401 or 403. However, in practice this doesn't seem to be the case. A request without the HTTP_X_FORWARDED_USER is simply allowed and 200 is returned: $ http http://127.0.0.1:8000/ HTTP_X_FORWARDED_USER:joe HTTP/1.1 200 OK "hello" $ http http://127.0.0.1:8000/ HTTP/1.1 200 OK "hello" Am I misunderstanding the documentation in the sense that a None is considered a successful … -
Login validate with encrypted password in PHP
this is my first question in Stack Overflow and I hope you can help me. I have a PostgreSQL database, which have many users. Users' passwords are encrypted in this format: sha1$678ae$0dd4b5a9588be91a931d1ef1f7e7053477c1478e This encryption was done with Django (although I don't know if you can encrypt it directly in database). What I'm trying to do is make a PHP application that can use and validate these users, with those encrypted passwords. How could I do it? Thanks in advance and sorry for my bad english. Cheers. PS: I'm using PHP 7. -
Why am I unable to access foreign key information in django templates.
I'm working on a django app that needs to create XML files to respond to requests. I've go my models setup like this: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Color(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', unique=True, max_length=255) # Field name made lowercase. class Meta: managed = False db_table = 'Data_Colors' def __str__(self): return "Color: [" + self.id.__str__() + ", " + self.name + "] " class Company(models.Model): orders = models.ManyToManyField('Order', through='OrderCompany') id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Data_Companies' def __str__(self): return "Company:[" + self.orders.__str__() + ", " + self.id.__str__() … -
is there any way to create unique id's to particular field in django model
class Product(models.Model): name=models.CharField(max_length=128) category=models.ForeignKey('Category',on_delete=models.CASCADE) rate=models.IntegerField() peices=models.IntegerField(default=True) def __str__(self): return self.name class Category(models.Model): name=models.CharField(max_length=128) def __str__(self): return self.name here in the product model if i assign 100 integers to peices every piece should have a unique id for eg: levis is a product and if i add 100 to the pieces section of this model so that i could get 100 different unique id's i tried a lot googling it but its of no use anykind of help is appreciated -
Using Postgres Shell to createuser
I am following a tutorial from the book Mele, Antonio. Django 2 by Example: Build powerful and reliable Python web applications from scratch (Kindle Locations 1917-1918). Packt Publishing. Kindle Edition. I'm at this part: > Adding full-text search to your blog > Installing PostgreSQL I'm on Windows 10 and I installed Postgres fine. The instructions say to type in the postgres shell: su postgres createuser -dP blog I guess I'm trying to create a user called 'blog' that will have a password and be allowed to create databases? When I do that I get: Server [localhost]: su postgres Database [postgres]: createuser -dP blog Port [5432]: Username [postgres]: psql: warning: extra command-line argument "postgres" ignored psql: warning: extra command-line argument "-d" ignored psql: warning: extra command-line argument "createuser" ignored psql: warning: extra command-line argument "-dP" ignored psql: warning: extra command-line argument "blog" ignored psql: warning: extra command-line argument "-p" ignored psql: warning: extra command-line argument "5432" ignored psql: could not translate host name "su" to address: Unknown host Press any key to continue . . . I'm not sure what to do or what exactly is going on? The instruction is pretty unclear -
Why .WMV files have mime type 'video/x-ms-asf' instead of 'video/x-ms-wmv'?
I need to accept only MP4 videos and WMV videos in a Django web app I am building. For that, I am checking the mime type of the file once it hits the server. As far as I understand, MP4 files have 'video/mp4' mime type, which is exactly what I am receiving on my web app. The problem comes with the WMV files, which according to every site I found (e.g.: this and that) should have 'video/x-ms-wmv' as the mime type. When I get this files on the server and I inspect them using python-magic I get 'video/x-ms-asf' as its mime type. I have converted some youtube videos to WMV videos using different online converters but the result is always the same. So actually, I do not know what am I doing wrong here. Maybe I have a problem of concets, where WMV videos can also have 'video/x-ms-asf' mime type, and not only 'video/x-ms-wmv' Maybe python-magic is not reading the mime type correctly, which I think would be hardly the case. Any help is deeply appreciated. As a side note, I am using python-magic instead of django's file.content_type because the second is not reliable. Just change the file's extension to … -
error:Manager isn't available; 'auth.User' has been swapped for 'Log.CUstomUser' in Django
when User want Register my website show this error: Manager isn't available; 'auth.User' has been swapped for 'Log.CUstomUser' i use import AbstractUser in my model i work with Django freamwork python Model: from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser , from django.db import models # Create your models here. class CustomUser(AbstractUser): country = models.CharField(max_length=200) number = models.IntegerField(default=1) age = models.IntegerField(default=1) View: from __future__ import unicode_literals from .forms import Register from django.shortcuts import render , render_to_response from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def Home(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save() return HttpResponse("Greate") else: form = Register() return render_to_response('home.html' , {'form':form}) Forms: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser from django.contrib.auth import get_user_model from django.contrib.auth.models import User class Register(UserCreationForm): email = forms.EmailField(required = True) number = forms.IntegerField() age = forms.IntegerField() class meta: model = User field = ( 'number', 'age', 'username', 'firstname', 'lastname', 'email', 'password1', 'password2' ) please fix my error -
How to call conditional statements on template tags with no arguments django
I'm trying to display html content based on what a template tag function returns. template.html {% load custom_tags %} {% if return_something == True %} # display something {% endif %} custom_tags.py from my_app.models import MyModel @register.simple_tag() def return_something(): if MyModel.objects.filter(active=True).exists() return True else: return False How do I do this? Thank you!