Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultiValueDictKeyError at /login/ "'id'"
i have a wrong that"MultiValueDictKeyError at /login/ "'id'"" i only want to write a simple login web,input the 'id' and 'password' in the web and turn on another web. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> login </title> <form> ID: <input type="text" name="id"> PW: <input type="password" name="pw"> </form> <form action="/login/" method="get"> <input type="submit" value="Submit"> </form> </head> <body> </body> </html> and i want to get the id and pw to use it here from django.http import HttpResponse from Cs.models import Admin,Course,Selection,Students from django.shortcuts import render def login_form(request): return render(request,'login.html') #login in def login(request): id = request.GET['id'] pw = request.GET['pw'] if Admin.objects.get(user_id='xid',user_pw='xpw'): return render(request, 'login_successful.html') -
Creating profile model on instance creation
According to Extending the existing User model¶ These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a user model. As such, they aren’t auto created when a user is created, but a django.db.models.signals.post_save could be used to create or update related models as appropriate. But how can I use post_save to pass the necessary arguments to MyCustomeModel.objects.create? Taking the example of the official document: models.py from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) from . import signals signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Employee @receiver(post_save, sender=User) def create_fellow_on_user_create(sender, instance, created, **kwargs): if created: Employee.objects.create(user=instance, **kwargs) An error happened when I tried to create a user by User.objects.create(username='username1', password='passwd') TypeError: 'signal' is an invalid keyword argument for this function when using Employee.objects.create(username='username1', password='passwd'), a similar error happened: TypeError: 'username' is an invalid keyword argument for this function -
Requiring first_name and last_name in Django User model
In django.contrib.auth.models.User, both first_name and last_name fields have blank=True. How can I make them blank=False, null=False in my own model? Here is my implementation, which basically follows the instructions of Extending the existing User model: models.py class Fellow(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) first_name = models.CharField( _("first_name"), max_length=30, ) last_name = models.CharField( _("last_name"), max_length=30, ) # other fields omitted from . import signals signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Fellow @receiver(post_save, sender=User) def create_fellow_on_user_create(sender, instance, created, **kwargs): if created: Fellow.objects.create(user=instance) However, I got an error when testing in python manage.py shell: >>> f = Fellow.objects.create(username='username', password='passwd') Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/query.py", line 392, in create obj = self.model(**kwargs) File "/Users/sunqingyao/Envs/django_tutorial/lib/python3.6/site-packages/django/db/models/base.py", line 571, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'username' is an invalid keyword argument for this function -
Ubuntu - Crontab executes command, but nothing happens
I have set up cron to execute the following command for django-cron (django 1.10.5, python 3.5, anaconda 4.2.0) in ubuntu 16.04: PATH=/user/project/projectname/website * * * * * ./manage.py runcrons "app.crons.RunCronJob" Here is my file tree, which is located directly under the highest level of the remote site (/): |-- user | |-- project | | |-- projectname | | | |-- website | | | | |-- file.txt | | | | |-- manage.py | | | | |-- app (a django app) | | | | | |-- crons.py RunCronJob is a cronjob within crons.py that appends a line to file.txt under /website. When I enter the /website directory and manually do ./manage.py runcrons "app.crons.RunCronJob", it works just fine. However, when the cronjob I have set up is run, it does not append anything to my text file. I have verified that the cron task is running every minute with both grep cron /var/log/syslog a mailing service, but the data I receive doesn't seem to tell me anything useful about why it isn't working. (Note for python: I have added os.chdir(os.path.dirname(sys.argv[0])) to the top of my crons.py to ensure that the text file gets written to in the correct … -
Why isn't my Django view finding my uploaded image from ImageField?
Im learning the Django framework and created an image upload section for editing blog posts. The upload part is working and the images get sent to a directory on my project. The problem is that when I load the page with the blog post it is unable to locate the uploaded image. My Model: # Create your models here. class Post(models.Model): #field for the author author = models.ForeignKey('auth.User') #field for post title title = models.CharField(max_length=200) #field for body text text = models.TextField() #save created and published date created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) #field to reference images saved in static files image = models.ImageField(upload_to='images/', default='images/None/no-img.jpg') def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title My View: # View to create a new post def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.image = form.cleaned_data['image'] post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) My images get uploaded to an images/images/myfile.jpg directory like so: my_blog |-->views.py |-->models.py |-->templates images |-->images |--> my_file.jpg My Template which extends from base.html: {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.image != … -
Django REST API connection issues
I am new-ish to using Django, so this may be an easy thing for someone...I hope so! I have built a Django REST API by following the tutorial found here: http://www.django-rest-framework.org/. When I run the server, I am able to use the Browsable API and navigate through the API, such as specifically this link: http://127.0.0.1:8000/snippets/. I am also able to access this URL through Postman GET request and retrieve the associated Snippets. Now, here is my problem: I have created a React Native application where I am fetching data from this URL (my python server is running). I console.log the response from this, and I continually get an error of: Error: Network Error at createError (createError.js:15) at XMLHttpRequest.handleError (xhr.js:87) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:478) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:324) at XMLHttpRequest.js:418 at RCTDeviceEventEmitter.emit (EventEmitter.js:179) at MessageQueue.__callFunction (MessageQueue.js:236) at MessageQueue.js:108 at guard (MessageQueue.js:46) I can refresh the link in the browser or Postman and have no issues, but in the fetch...I am unable to have any success, and am only getting back the vague error message above. I thought it might have to be with a CSRF, or CORS...but I have both of those set-up ok in Django (and the error message … -
python manage.py runserver: django.db.utils.OperationalError
I cloned a git django website project which includes php and sql. I am running Python 2.7 on Windows 10. After running python manage.py runserver to test local changes to my files I receive the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "user" I have not yet been able to start the Django runserver to checkout the changes. I am new to Python and Django and would appreciate any help! -
How to use captured value from URL to select JSON data in Django
Let's assume that I have GET request with URL domain/search/?value=123 and data in JSON: [ { "id": 1, "value": 123, "value2": 123123 }, { "id": 2, "value": 1, "value2": 214 } ] I would like to get data where value = 123. In this case: [ { "id": 1, "value": 123, "value2": 123123 } ] I have found information how to capture parameters from URL in this post. I wonder what I should do now to find best solution. Thanks in advance. -
Is there a way to define a remote template path for Django CMS
For the final stages of a Django CMS site we were able to serve the static files from remote: Simply by changing the setting.py's STATIC URL variable from: STATIC_URL = '/static/' to: STATIC_URL = 'https://hosting-****.firebaseapp.com' Is there a way to change the path of the templates html files as well? We want to be able to quickly change both css and templates as QA tests the site. -
Heroku free SSL for paid dynos not working on "old" app
I have a django app created before the announcement of free SSL Dynos on Heroku. I followed throught the tutorial here > heroku certs:auto:enable Enabling Automatic Certificate Management... done === Your certificate will now be managed by Heroku. Check the status by running > heroku certs:auto === Automatic Certificate Management is enabled on codetiger Domain Status ──────────────── ─────── www.site.com Failing site.com Failing === Some domains are failing validation, please verify that your DNS matches: heroku domains When I run the heroku domains command, it shows me the following === codetiger Heroku Domain codetiger.herokuapp.com === codetiger Custom Domains Domain Name DNS Target ──────────────── ────────────────────────────── www.site.com www.site.com.herokudns.com site.com site.com.herokudns.com And the Type Hostname Value TTL (seconds) CNAME www.site.com www.site.com.herokudns.com 43200 CNAME *.site.com site.com.herokudns.com. 1800 Even after doing all that, when I run heroku certs:info I only see site has no SSL certificates What can I do for it to work? -
using variable in one app in template of another app django
I have a simple project containing two apps. How can i use a variable from app A into template of app B. project-> app A-> templates-> app B-> templates-> django 1.10. -
Django Apache DocumentRoot?
What directory must the DocumentRoot in Apache be set to run a Django app is it the static directory but that does not work? Thanks to all for the help in advance. -
Deploying Django Channels to Elastic Beanstalk Python3.4 environment
I have spent the past few days implementing Channels into my Django app in order to use Channel's websocket support. My Django project is written in Python 3.4 and I am using Daphne and Channel's redis backend. I have been able to get everything functioning locally by wrapping Supervisord in a Python2 virtualenv and using it to run scripts that start Daphne/Redis/workers inside a Python3 virtualenv, but have had no success deploying to our Elastic Beanstalk (Python 3.4) environment. Is there any way to set up my EB deployment configs to run Supervisor in a Python2 virtualenv, like I can locally? If not, how can I go about getting Daphne, redis, and my workers up and running on EB deploy? I am willing to switch process managers if necessary, but have found Supervisor's syntax to be easier to understand/implement than Circus, and am not aware of any other viable alternatives. With this configuration, I am able to successfully deploy to my EB environment and ssh into it, but Supervisor fails to start every process, and if I try to start Supervisor manually to check on the processes supervisorctl status gives me FATAL "Exited too quickly (process log may have details) … -
Can someone help me customize the admin site in django 1.11
can someone help me customize the admin site in Django , I´m using django 1.11. I´ve already try edit the main base_site.html file at virtualenv/lib/python3/contrib but it doesnt work also I´ve tried to create inside my templates dir a new folder called "admin" and inside paste the same "base_site.html" but it doesnt work either. Here is a ss to my settings.py. THANKS enter image description here -
Django plus Celery/RabbitMQ with threading for C socket module
We have a Django webapp that uses Celery 4.x to run tasks asynchronously. The main tasks require the Django/Celery code to perform network communication operations with 20-100 other servers. Each request we send to these other servers is identical, ie the user sends a command to Django which then tells Celery to send the exact same command to each of the 20-100 other servers. The problem is that with the basic configuration of Celery, if we have say 4 workers then Celery will communicate with only 4 servers at time. To fix this problem, we tried using Celery with gevent. However, gevent uses coroutines rather then full threads, and for our network operations we are using our own python module that was written in C. In other words we are NOT using the python socket or request modules that can be monkey patched. So, what we would like to do is the following. For sake of argument, let's say our C communication module is called "cnet". If we have 20 other servers that we must communicate with, we would have a Celery task function that does something like this: # This uses our cnet module (written in C) to connect … -
Matplotlib Runtime Error: main thread not in main loop
I am not trying to thread any processes, but keep running into this error all over my Django site. I have seen a few other people ask this question but they are all attempting to use multiple threads. This is on Django 1.11, Python 3.6, Matplotlib 2.0.0. I also will note that this issue occurs on my mac, but not on my live Heroku server. I am using Pyplot to create some visualizations of models instances the users make, and get this about half the time I try to run it: Exception Type: RuntimeError Exception Value: main thread is not in main loop The last line of my code that runs is simply the plt.figure() call Trace: File "/Users/Mark/Desktop/Professional/FSC/water/WATER/hydrograph/views.py" in processData 397. hydroFigure = plt.figure() File "/Users/Mark/Desktop/Professional/FSC/water/WATER/ENV/lib/python3.6/site- packages/matplotlib/pyplot.py" in figure 535. **kwargs) File "/Users/Mark/Desktop/Professional/FSC/water/WATER/ENV/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py" in new_figure_manager 81. return new_figure_manager_given_figure(num, figure) File "/Users/Mark/Desktop/Professional/FSC/water/WATER/ENV/lib/python3.6/site-packages/matplotlib/backends/backend_tkagg.py" in new_figure_manager_given_figure 98. icon_img = Tk.PhotoImage(file=icon_fname) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py" in __init__ 3539. Image.__init__(self, 'photo', name, cnf, master, **kw) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py" in __init__ 3495. self.tk.call(('image', 'create', imgtype, name,) + options) Exception Type: RuntimeError at /hydrograph/ Exception Value: main thread is not in main loop Any ideas on what I can do? -
Django not overriding admin views
I have the correct file structure and names as stated in the documentation: https://docs.djangoproject.com/en/1.11/topics/auth/default/#all-authentication-views login (app) --templates --login.html (this one works) --password_reset_form.html --password_reset_confirm.html --password_reset_done.html --password_reset_email.html --password_reset_complete.html --password_reset_subject.txt However it does not seem to be picking up the templates. Rather I am getting the jet templates exposing my backed to the users. the only workaround I found is to manually replace each template with class based views. But That is not working for the emails :-( Here is my apps list if it helps. INSTALLED_APPS = [ 'jet.dashboard', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'social_django', 'server_common', 'homepage', 'login', ] Thanks for your help in advance. -
Inserting more data in metadata in Django Rest Framework
How can I insert more information to a view response using DRF? I'm using the ModelSerializer to get the data from a Model I've created and its default response is a json object in the following format: { links: { "first": ..., "last": ..., "next": ..., "previous": ... }, data: [], meta: {"pagination": {"page": i, "pages": n, "count": n2} } I'd like to insert more data into meta, but I don't want to change the default response of metadata. I'd like to change the response to only one of my views. I got confused in the guide in the metadata section and I could only find in the serializer section something that changes the serializer.data and not the metadata itself. -
Django Session Variables Not Transferring Between Views
View1 is setting session variable chosen_date_year, but View2 is unable to access this variable, returning KeyError (i.e. not in sessions). I believe this has something to do with session keys changing so that View2 is accessing an incorrect session because this problem is only affecting some users, not all. View1 snippet def View1(request, **kwargs): from myforms import myform if request.method == 'GET': form = myform(request.GET) if form.is_valid(): chosen_date_year = form.cleaned_data.get('chosen_date_year') #e.g. 2017 (int) request.session['chosen_date_year'] = chosen_date_year request.session.modified = True request.session.save() *** foo code *** return render(request, "View1.html", context) View2 snippet def View2(request, **kwargs): chosen_date_year = request.session['chosen_date_year'] # results in KeyError *** foo code *** return render(request, "View2.html", context) Any idea why some users' session variables persisting between views but not others? I've had users delete their cookies but that did not help. Thank you. -
How to render localized datetimes in Django in custom admin fields?
How do you render datetimes outside of Django templates, so that they still take into account localization? I have a few custom ModelAdmin fields that show or incorporate a datetime. When you render these in a Django template, Django automatically handles converting the timezone-aware UTC datetime into the local equivalent. However, all my custom fields show the datetime in the correct format, but in UTC time, not the timezone I specify in my Django settings. This is what I'm currently using to convert a datetime to a string so that it uses Django's date format: def render_time(dt): from django.template.defaultfilters import time as _time return _time(dt) How do I modify this so that it also localizes the time's timezone? -
Microsoft Graph binary photo to file in Django
Ok, I am connecting my Django app to Microsoft Graph API to get my user photo. The problem is that I cant find how to transform the 64base not encoded binary data to a file I can use. I have been reading and searching for about 2 hours, with no luck. Thanks for your help. -
django queryset - classify and filter by value
I have model with two attributes: class Fruit(models.Model) name = models.CharField(max_length=30) days_left_to_consumption = models.IntegerField() that gives me database objects: {"name":"apple", "days_left_to_consumption": 2}, {"name":"apple", "days_left_to_consumption": 3}, {"name":"pineaple", "days_left_to_consumption": 2}, {"name":"pineaple", "days_left_to_consumption": 1} I want to create queryset to classify results by "name" attribute (every diffrent fruit name occurs only one time) but get for every diffrient fruit object with the higher value of "days_left_to_consumption". The result I want to get from the upper example is: {"name":"apple", "days_left_to_consumption": 3}, {"name":"pineaple", "days_left_to_consumption": 2} Do you have any idea? -
create instance of a model automatically based on instance of another model in django
i want to create 4 instances of tyres and 1 instance of engine when i create instance of car model here is my model code class Car(models.Model): company=models.CharField(max_length=25) car_model = models.CharField(max_length = 25) year = models.IntegerField() class Engine(models.Model): car=models.OneToOneField(Car) engine_type=models.CharField(max_length = 15) no_cylinders=models.IntegerField() state=models.CharField(max_length = 15) class Tyre(models.Model): car=models.ForeignKey(Car) tyre_material=models.CharField(max_length = 15) position=models.CharField(max_length = 10) #ex front right back left state=models.CharField(max_length = 15) and the form for car class car_form(forms.ModelForm): class Meta: model = Car fields = ( 'comapany', 'car_model', 'year' ) def save(self, commit=True): obj=car_form.save() obj.company = self.cleaned_data['comapany'] obj.car_model = self.cleaned_data['car_model'] obj.year = self.cleaned_data['year'] if commit: obj.save() return obj and here is my view def car_create(request): if request.method =='POST': form = car_form(request.POST) if form.is_valid(): form.save() return redirect("/") else : return render(request, 'agency/car_form.html', {'form': form}) else: form = car_form() args = {'form': form} return render(request, 'agency/car_form.html', args) what should i change in my code iam just a self learning beginner so excuse me for my question thanks in advance -
Customizing Serializers in Django Rest Framework
I am creating an App when I would like the JSON response to be organized when it is received, rather than receiving and organizing. Currently, I have a ListSerializer type of serializer which would give me response something like [ { "Title": "ABCD", "Content": "Article Stuff", "Category": "News" }, { "Title": "EFGH", "Content": "Article Stuff", "Category": "Jokes" }, { "Title": "QWER", "Content": "Article Stuff", "Category": "News" }, ] And I would like it to be something like:- { "News": [ { "Title": "ABCD", "Content": "Article Stuff", "Category": "News" }, { "Title": "QWER", "Content": "Article Stuff", "Category": "News" } ], "Jokes": [ { "Title": "EFGH", "Content": "Article Stuff", "Category": "Jokes" } ] } I have just used the default model serializer till now. I know how I would do this if I created the JSON myself from the SQL result sets, but would be better if I could write a serializer that can do it. Also, I plan to do a bit of pagination for each category as well after this. But that shouldn't be much of an issue, just would need to put checks where we pull the data from the DB for articles of a particular category, I guess. -
Duplicate results in nativescript get request
I have a django back-end and nativescript on mobile side, I am trying to fill tab view with data but I encountered a problem that when i request an endpoint with parameter date on rest-client it returns results without any problem. But when I try to get events via get request on nativescript it returns duplicated events. I could not figure out what went wrong. I would appreciate if you could help me about that. This is a screenshot of my rest-client. It returns only 2 item but in my get request results returns 6 items which is duplicated by 3 for each item. event-list.service.ts load(dateVar) { let headers = new Headers(); headers.append("Authorization", "Token " + this.tokenVal); return this.http.get(Config.apiUrl + "events/?date=" + dateVar, { headers: headers }) .map(res => res.json()) .map(data => { console.log(" length full: "+JSON.stringify(data)); // prints: {"count":6,"next":null,"previous":null...... let dataList = []; data.results.forEach((data) => { dataList.push(new Event(data.id, data.created_date, data.title, data.descr, data.image, data.is_active, data.event_date, data.creator)); }); return dataList; }) .catch(this.handleErrors); } event-list.component.ts public getEvents(dateVar){ this.isLoading = true; this._dataItems = new ObservableArray<Event>(); //empty _dataItems this._dataItemService.load(dateVar) .subscribe(_items =>{ _items.forEach((object) => { this._dataItems.push(object); }); this.isLoading = false; }); } ngOnInit() { this.getEvents('today'); //this is how i call it on init } events.html …