Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save foreign key in django model by value of other field
I'm dealing with apples and buckets imported from an API. They shall be written into a Django database using the models. The Rest API holds an ID of buckets which isn't the internal one but saved as external_id in the local Bucket Model. The local Apple Model has a field bucket which is a models:ForeignKey(Bucket) field. When retrieving and storing the data I can't find out how to connect those two. Is there a way to simply have Django query for the external_id on the bucket table and then use the resulting row to connect the Foreign Key? a = Apple( 'name' = apple.name 'count' = apple.count 'bucket' = ??? ) a.save() -
Can you write a query to look up a value in another table based on modifying the foreign key in Django?
I'm trying to write a query in Django where I query a value from a table based on both the value of the foreign key and a modification to the foreign key. Consider an example database that stores the names, teams, and records of a team in one table that links to the league's revenue in another: class League(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) revenue = models.IntegerField(max_length=5) class Team(models.Model): name = models.TextField(max_length=20) year = models.ForeignKey(League, max_length=4) record = models.TextField(max_length=10) How would I write a query so that I could create a table that included the name of the team, the year, this year's revenue, and the previous year's revenue? -
inlineformset - incrementing TOTAL_FORMS gives MultiValueDictKeyError
I'm trying achieve a dynamic formset without javascript support. For this, I've added a button at the bottom of the form, <input type="submit" name="add_item" value="+" id="submit-id-add_item"> Now, inside my CreateView, I have tried the following code. def get_context_data(self, **kwargs): context = super(AddInvoice, self).get_context_data(**kwargs) ItemInlineFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=1, can_delete=False, formset=InvoiceItemFormSet) if self.request.method=='POST': if 'add_item' in self.request.POST: cp = self.request.POST.copy() cp['item-TOTAL_FORMS'] = int(cp['item-TOTAL_FORMS'])+ 1 context['item_formset'] = ItemInlineFormSet(cp,prefix='item') else: context['item_formset'] = ItemInlineFormSet(self.request.POST,prefix='item') else: context['item_formset'] = ItemInlineFormSet (prefix='item') return context But, when I click on the add_item button, I get the following error MultiValueDictKeyError at ... 'item-1-item' (my form prefix is item and also have a field named item) I suspect this is because django looks for the next set of form elements to match with TOTAL_FORMS but it can't find anywhere. What I'm missing here? Thanks. -
django facebook OAuth URL blocked error
I have been using social-auth-app-django for over an year for FB auth on my website without issues. Recently this broke due to FB's new enforcement. As of March 2018 Facebook requires you to turn on strict mode for URI redirects and enforce https. Here is what my browser redirects to after attempting facebook login from my public site. (I modified real domain to 'mydomain' and client_id to bogus.) https://www.facebook.com/v2.7/dialog/oauth?client_id=1111111111111111&redirect_uri=https%3A%2F%2Fmydomain.com%2Fcomplete%2Ffacebook%2F%3Fredirect_state%3D2bjl12344J4qrU9TfO5ut0F6FpFypjL&state=2bjlsMf2G4J4qrU9TfO5ut0F6FpFypjL&scope=email%2Cpublic_profile Screenshot below has my FB login settings. I added URI corresponding to above URL into my OAuth whitelist with and without trailing backslash '/' as other posts have suggested. I have been researching this for more than a week to no end and just short of re-writing the entire flow, any help on what could be going wrong will be greatly appreciated! -
Django - How to send list containing datetime over POST
Using Django, I ran into an issue with sending lists over POST in the RequestFactory API: self.factory.post('...', [a,b,c,d], format="json") would not work because: File "/.../python3.6/site-packages/django/test/client.py", line 192, in encode_multipart for (key, value) in data.items(): AttributeError: 'list' object has no attribute 'items' So then I tried to make it a dictionary with the list being nested: self.factory.post('...', {"items": [a,b,c,d]}, format="json") Having this on my class-based view: def post(self, request, format=None): """ We always POST a list of requests. This list will not be checked for performance sake. """ reqdata = list(request.data["items"]) print(request.data) print(request.data["items"]) It only prints the last element in my list: {'a': 'bar', 'b': datetime.datetime(1970, 1, 1, 0, 2, 3), 'c': datetime.datetime(1970, 1, 1, 0, 2, 3), 'd': 10, 'v': 'b'} And what's worse, it's in the form of a str! The whole QueryDict(request.data) looks like: <QueryDict: {'items': ["{'a': 'foo', 'b': datetime.datetime(1970, 1, 1, 0, 2, 3)...", "...", "..."]}> So that means when we get out our items we would get out strings. So I thought... Okay, so let's just load it with the json module right? json.loads(request.data["items"]) # ERROR! File "/home/.../python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line … -
Getting error when i am trying to run djnago localhost on the browser it is saying " 500 Internal Server Error Daphne HTTP processing error Daphne
The following error is shown on the terminal where i have run the django server : System check identified no issues (0 silenced). April 26, 2018 - 05:20:06 Django version 2.0.4, using settings 'chantest.settings' Starting ASGI/Channels version 2.1.1 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 2018-04-26 05:20:07,129 - INFO - server - HTTP/2 support enabled 2018-04-26 05:20:07,131 - INFO - server - Configuring endpoint tcp:port=8000:interface=127.0.0.1 2018-04-26 05:20:07,135 - INFO - server - Listening on TCP address 127.0.0.1:8000 2018-04-26 05:20:20,030 - ERROR - http_protocol - Traceback (most recent call last): File "/home/pradeep/.local/lib/python3.6/site-packages/daphne/http_protocol.py", line 160, in process "server": self.server_addr, File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/internet/defer.py", line 1384, in _inlineCallbacks result = result.throwExceptionIntoGenerator(g) File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/python/failure.py", line 408, in throwExceptionIntoGenerator return g.throw(self.type, self.value, self.tb) File "/home/pradeep/.local/lib/python3.6/site-packages/daphne/server.py", line 186, in create_application application_instance = yield deferToThread(self.application, scope=scope) File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/python/threadpool.py", line 250, in inContext result = inContext.theWork() File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/python/threadpool.py", line 266, in inContext.theWork = lambda: context.call(ctx, func, *args, **kw) File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/python/context.py", line 122, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/home/pradeep/.local/lib/python3.6/site-packages/twisted/python/context.py", line 85, in callWithContext return func(*args,**kw) File "/home/pradeep/.local/lib/python3.6/site-packages/channels/staticfiles.py", line 41, in call return self.application(scope) TypeError: 'RedisChannelLayer' object is not callable [2018/04/26 05:20:20] HTTP GET / 500 [0.10, 127.0.0.1:57846] 2018-04-26 05:20:20,317 - ERROR - http_protocol - Traceback (most … -
Downloading a file using Django
I'm trying to enable the downloading of previously uploaded files in Django, here's the code I'm using so far: def downloadview(request): path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' ) response = HttpResponse() response['Content-Type']='' response['Content-Disposition'] = "attachment; filename='Testname'" response['X-Sendfile']=smart_str(os.path.join(path)) return response The inspiration for this trial comes from this thread but I don't get it working. An empty txt file is downloaded instead of the image that is stored on the server. In this trial code the exact filename and extension is hard coded in the path variable. -
Configuring webhooks for a Django chatbot to Heroku
It's a Telegram messaging bot built as a Django app. I'm attempting to keep this live on Heroku but it is not working. The app itself uses webhooks to receive updates from the Telegram server. When configuring this locally, I did curl -F "url=<ngrok_url>/c817304a3d163ebd58b44dd446eba29572300724098cdbca1/" https://api.telegram.org/bot<bot_token>/setWebhook in order to set the webhook. Using ngrok to tunnel from the public URL to my machine. I believe this is what I'm missing as part of serving my chatbot on Heroku. How would I accomplish the same on a live server? (without ngrok/curl) -
Django not match path with parameter
This must be something very basic, but I can't seem to figure it out. Why is there no match below? Isn't the path matching 2 or 3? Using the URLconf defined in tag.urls, Django tried these URL patterns, in this order: [name='index'] search/(?P<tag>\w+/$ [name='search'] search/(?P<tag>\w+ [name='search'] admin/ The current path, search/ssdf, didn't match any of these. tag/tagdb/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path(r'', views.index, name='index'), path(r'search/(?P<tag>\w+/$', views.search, name='search'), path(r'search/(?P<tag>\w+', views.search, name='search'), ] tag/tag/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path(r'', include('tagdb.urls')), path(r'admin/', admin.site.urls), ] -
ORM ordering vs Model "Meta" ordering - Django 1.11
Small question - what is better way for ordering items: 1) class Table(models.Model): ... class Meta: ordering = ['user'] 2) Table.objects.all().order_by("user") I think 2 one is better cuz first always will return ordered querysets, and if sometimes we don't need order - it will take additional time? Are there any other reasons to use 1 approach, exсept convenience of "not-writing" .order_by("user") every time? -
I need to create a structure that is capable of storing the instances of addresses categorized by that prefix
Django-Python I get this data from my template by POST: <QueryDict: {u'0-dom-fecha-modf': [u'01/04/2018'], u'0-dom-pseudo-loc': [u'pseudoloc0'], u'1-dom-pseudo-loc': [u'pseudoloc1'], u'apellido': [u'apellido'], u'nro_doc': [u'33333333'], u'fec_nac': [u'1400-06-23'], u'1-dom-calle': [u'calle1'], u'1-dom-fecha-modf': [u'08/04/2018'], u'0-dom-nro': [u'nro0'], u'sexo': [u'1'], u'1-dom-localidad': [u'1'], u'0-dom-localidad': [u'3'], u'1-dom-nro': [u'nro0'], u'nombre': [u'emanuel'], u'csrfmiddlewaretoken': [u'CC42dWYUYXyNis9dNoRrJLgHQqU0GYdG'], u'0-dom-calle': [u'calle0']}> I need to create a structure that is capable of storing the instances of addresses categorized by that prefix "varialble"-dom example: domicilios = {'0-dom':{0-dom-calle': 'calle0', '0-dom-localidad:' localidad0','0-dom-nro': 'nro0'}, '1-dom':{1-dom-calle': 'calle1', '1-dom-localidad:' localidad1','1-dom-nro': 'nro1'}, ... } suggestions? PD: And yes... I'm using the Google translator -
Python / Django makemigrations Error
I have been messing around with Python and Django recently, following this tutorial - https://www.codementor.io/jadianes/get-started-with-django-building-recommendation-review-app-du107yb1a I will be altering that app as I go, just to experiment, however I am at a bit of a standstill with 'makemigrations'. When I run python manage.py makemigrations reviews I get a traceback as follows: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 347, in execute django.setup() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\CalPC\AppData\Local\Programs\Python\Python36\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\CalPC\Desktop\review_app\prodreview\reviews\models.py", line 2, in import numpy as np ModuleNotFoundError: No module named 'numpy' Here are my Models from django.db import models import numpy as np class Product(models.Model): name = models.CharField(max_length=200) def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __unicode__(self): return self.name class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, … -
Exclude duplicates from django admin page
My question is the following: can you exclude objects that are duplicated from being displayed on the admin page without DB modification, and if yes, how? Thanks for all the help in advance -
Best way to get around the unique-constraint for many-to-many relationships in Django?
I have a situation where I need to be able to add multiple copies of the same object to a many-to-many relationship. Let's say that the problem is recording the types of furniture someone has. Here are my base models: class Person(models.Model): name = models.CharField(max_length=100) class Furniture(models.Model): furniture_name = models.CharField(max_length=100) #e.g. Chair, Sofa. Lets say I want to record that Sam owns 3 chairs and 2 sofas. But I don't want to make more than one sofa object in the DB. How can I do this with a many-to-many relationship? The traditional many-to-many has a unique-constraint that prevents this. I'm thinking of using a through table, with another field in the unique-constraint (date-purchased, or just a random string). Will that work? Does anyone have a better way of doing this? -
How do I get serializer field value inside serializer
I have this ModelSerializer: class BidSerializer(serializers.ModelSerializer): class Meta: model = Bid fields = '__all__' def validate_amount(self, value): auction = Auction.objects.get(id=self.validated_data['auction']) if auction.price_step % value: raise serializers.ValidationError() But it throws throws "is_valid() should be called" exception. How do I properly access auction field value? -
Django template rendering of EmbeddedDocument
I'm working with django and mongoengine and I'm not sure wich db scheme should I use in order to obtain better template rendering performance. My database has documents of the type of blog posts that are queried by a search engine. The output is a list the posts, but only some data is displayed, such as title, summary and author. It's just like google scholar. My question is if I should save each entry data such as body text as part of the same document or should I make reference to another model that contains data that is never shown. I exemplify the two solutions: Model A: class Article(Document): url = fields.StringField() pub_date = fields.DateTimeField() title = fields.StringField(verbose_name="Title",max_length=255) description = fields.StringField() body = fields.StringField() ... Model B: class ExtraData(Document): body = fields.StringField() ... class Article(Document): url = fields.StringField() pub_date = fields.DateTimeField() title = fields.StringField(verbose_name="Title",max_length=255) description = fields.StringField() extra_data = fields.ReferenceField(ExtraData) ... I ask was because some documents may contain big body texts (as well additional data such as part-of-speech tagging). I imagine that if I use Model A, the rendering process will have to process this additional data that is never shown and so my question is: does django html … -
Django is not calling functions
My django main site urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('ways/', include('ways.urls')), path('admin/', admin.site.urls), app url urlpatterns = [ path('newWay/', views.newWay, name='newWay'), path('waySolved/', views.update_way, name='update_way'), ] project structure But whenever i hit http://localhost:8000/ways/waySolved/ it says Not Found: /ways/waySolved/ but http://localhost:8000/ways/newWay works perfectly. In views i have both functions. -
s3 image thumbnail cache URL goes 'bad' after one pageview django-oscar
I have a django-oscar application which is live on heroku and static files is hosted on aws s3 but For some reason yet unknown to me, a product's thumbnails disappear from view after just a single load of a page (both in Dashboard and Product Detail view) because the template seems to be truncating the URLs. This problem doesn't happen to statics at all. To replicate: Upload an image for a product using the dashboard. The image gets stored in the correct S3 bucket, media path,is accessible by all, and so on. (confirmed with django admin, AWS Console and sorl debug logging) System returns the correct working URL https://s3.amazonaws.com/mybucket/media/cache/XXX/YYY/ZZZ.jpg that works on first page view request. Reload the page. System returns broken URL https://s3.amazonaws.com/mybucket/cache/XXX/YYY/ZZZ.jpg (missing 'media' path) Running python manage.py thumbnail cleanup, python manage.py thumbnail clear, restart gunicorn takes up back to step 2 Am I missing something? Should I be looking at sorl.thumbnail or oscar templates? Some relevant settings and data: Snippet from pip requirements sorl-thumbnail==12.3 boto==2.38.0 django-storages==1.1.8 awscli==1.7.39 Snippet from settings.py THUMBNAIL_DEBUG = True THUMBNAIL_PRESERVE_FORMAT=True OSCAR_IMAGE_FOLDER = 'images/products/' AWS_STORAGE_BUCKET_NAME = 'mybucket' AWS_ACCESS_KEY_ID = 'mykey' AWS_SECRET_ACCESS_KEY = 'mysecret' AWS_S3_CUSTOM_DOMAIN = 's3.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' … -
After entering details i cant redirect to next (display.html) page
urls: from django.conf.urls import url from django.contrib import admin from reg import views urlpatterns = [ url(r'^admin/', admin.site.urls), url('getcontact/', views.GetContactform), url('ValidateData/', views.ValidateData), ] views: from django.shortcuts import render from .forms import Contactform def GetContactform(request): contact=Contactform() return render(request,'contact.html',{'form':contact}) def ValidateData(request): cf=Contactform(request.POST) if cf.is_valid(): inputdata=cleaned_data return render(request,'display.html',{'data':inputdata}) else: return render(request,'contact.html',{'data':contact}) forms: from django import forms class Contactform(forms.Form): name=forms.CharField(required=True) email=forms.EmailField(max_length=20) city=forms.ChoiceField(choices=[('None','---select---'),('Hydeabad','Hyd'),('Vishakapatnam','Vizag')]) mobile=forms.CharField(max_length=10) def clean_name(request): data=self.cleaned_data('name') if len(data)<4: raise forms.ValidationError('Name must contain 4 chractors') return data def clean_email(request): data=self.cleaned_data('email') if not data.endswith('@gmail.com'): raise forms.ValidationError('email must ends with @gmail.com') return data def clean_city(request): data=self.cleaned_data('city') if city=='None': raise forms.ValidationError('choose city') return data def clean_mobile(request): data=self.cleaned_data('mobile') if len(data)<10: raise forms.ValidationError('Mobile no must contain 10 numbers') return data display page: Name:{{data.name}} Email:{{data.email}} City:{{data.city}} Mobile:{{data.mobile}} -
error: update acceptor rejected mysql-3: pods for rc 'pandemonium/mysql-3' took longer than 600 seconds to become available
I am using openshift origin to deploy a django website. When I try to deploy the mysql-ephemeral I get it fails to deploy. This is what the log looks like: --> Scaling mysql-3 to 1 error: update acceptor rejected mysql-3: pods for rc 'myapp/mysql-3' took longer than 600 seconds to become available I can't find any more detailed logs so i have no idea what the problem is. -
Django encryption and decryption
I’m want to encrypt me whole database so I’m using a django router in with I’m encrypting and decrypting the DB so that my APIs are getting slow can someone suggest me better way or some alternatives? -
Django button to start script
I need a simple button to start script in my views.py when clicked. Went thru tones of stuff nowhere found any clue. An example would be best please. Im a newbie after all. -
Python range() implementation in django templates [duplicate]
This question already has an answer here: Numeric for loop in Django templates 15 answers I have some django application, i need to render some html with this block of code: {% for i in review.mark|range %} img src="{% static 'core/img/star-yellow.svg' %}" alt="star"> {% endfor %} Sometimes filter range help me with this (review.mark is only IntegerField in my model). I have mark from 1 to 5, and i want to loop for review.mark times. How can i do this in django templates? -
Django Deployment with nginx - gunicorn from another server
I'm trying to deploy my Django Project through different application server : Apache2, Nginx/gunicorn, ... It works fine with Apache2 or Nginx, but I would like to dissociate these application server with my Django Projet. I would like to get an environment like this : Server 1 (172.30.10.92) : Django Project & wsgi Server 2 (172.30.10.93) : Nginx/gunicorn Why ? Because later I will have some Django applications, but I would like to use just one application server. I think I'm making a mistake with my configuration files syntax. I have in /etc/nginx/sites-available/DatasystemsCORE.conf : server { listen 8000; server_name 172.30.10.92; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root http://172.30.10.92:/var/www/html/; } location / { include proxy_params; proxy_pass http://172.30.10.92/unix:/var/www/html/DatasystemsCORE/dscore.sock; } } server_name : Is it IP adress from Django server or nginx server ? I think it's the first one but I'm not sure. proxy_pass : I think there is an issue in my path Then, I'm executing this command : gunicorn --daemon --workers 3 --bind 172.30.10.92/unix:/var/www/html/DatasystemsCORE/dscore.sock 172.30.10.92:/var/www/html/DatasystemsCORE/DatasystemsCORE.wsgi One more time, I thing there is a syntax problem because I'm getting 502 Bad Request How I can add IP address from a distant Django server there ? … -
Django creation of new user failed
I'm facing some difficulties while trying to create a new user using UserCreationForm in Django. I think that the issue is on the signup HTML page, but I can't really understand what am I doing wrong. When I click submit after filling the required fields nothing happens. I hope you could help me out. Part of signup.html: <div class="container"> <form id="register-form" method="post"> {% csrf_token %} {% for field in form %} {% if field.name == 'first_name' %} <div class="form-group"> <input id="register-first_name" type="text" name="registerFirst" required class="input-material"> <label for="register-first_name" class="label-material">{{ field.label_tag }}</label> </div> {% endif %} {% if field.name == 'last_name' %} <div class="form-group"> <input id="register-last_name" type="text" name="registerLast" required class="input-material"> <label for="register-last_name" class="label-material">{{ field.label_tag }}</label> </div> {% endif %} {% if field.name == 'username' %} <div class="form-group"> <input id="username" type="text" name="username" required class="input-material"> <label for="username" class="label-material">{{ field.label_tag }}</label> </div> {% endif %} {% if field.name == 'email' %} <div class="form-group"> <input id="register-email" type="text" name="registerEmail" required class="input-material"> <label for="register-email" class="label-material">{{ field.label_tag }}</label> </div> {% endif %} {% if field.name == 'password' %} <div class="form-group"> <input id={{ form.name.name }} type="text" name="password" required class="input-material"> <label for={{ form.name.name }} class="label-material">{{ field.label_tag }}</label> </div> {% endif %} {% endfor %} <input id="register" type="submit" value="Register" class="btn btn-primary"> </form> …