Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html form and Django login system
i want to make simple login system with Django.I want to send a user to a page named 127.0.0.1:8000/login after submitting the form.From then i want to get the post data sent with the request, check if the users exist in the date base and return a html page if he logged in or anothet html page if the user has not logged in.The problem is when i click the submit button of the form, it doesnt make request to /login.It stays at the same page.Any help? <!DOCTYPE html> <html> <body <form action="/login/" method = POST> First name:<br> <input type="text" name="name"><br> <input type = "submit" value = "Submit"> </form> </body> </html> -
Django query across foreign keys to a filtered query set
I have a model set like this: class Category(models.Model): name = models.CharField() class CarModel(models.Model): name = models.CharField() category = models.ForeignKey(Category, on_delete=models.CASCADE) class Car(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel, null=True, on_delete=models.CASCADE) How can I get a query set with all the categories of cars owned by the current user? Thanks! T -
Resource temporarily unavailable using uwsgi + nginx
I've django app host using nignx-uwsgi. Here is my uwsgi configuration: [uwsgi] master = true socket = /var/uwsgi/uwsgi.sock chmod-socket = 666 chdir = /home/ubuntu/test wsgi-file = /home/ubuntu/test/test/wsgi.py virtualenv = /home/ubuntu/virtual vacuum = true enable-threads = true daemonize= /home/ubuntu/uwsgi.log I'm getting error in nignx log 2017/06/16 04:25:42 [error] 26129#0: *1141328 connect() to unix:///var/uwsgi/uwsgi.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.xx, server: and the site shows 502 bad gateway. I have to restart uwsgi to fix it. But the frequency of the error is increasing. Is there anyway to fix this. -
How to make the codes different type using Django and Python
I need some help. I need to make different for for same code writing as per some condition using Django and Python. I am explaining my code and the scenario below. if request.method == 'POST': location_name = request.POST.get('lname') rname = request.POST.get('rname') seat = request.POST.get('seat') projector = request.POST.get('projector') video = request.POST.get('video') num=str(random.randint(100000000000,999999999999)) doc = m.parse("roomlist.xml") root=doc.getElementsByTagName("roomlist") valeurs = doc.getElementsByTagName("roomlist")[0] element = doc.createElement("location") element.setAttribute("name" , location_name) el1 = element.appendChild(doc.createElement("room")) el1.setAttribute("id", num) el2=el1.appendChild(doc.createElement("roomname")) el2.appendChild(doc.createTextNode(rname)) el3=el1.appendChild(doc.createElement("noseats")) el3.appendChild(doc.createTextNode(seat)) el4=el1.appendChild(doc.createElement("projectorscreen")) el4.appendChild(doc.createTextNode(projector)) el5=el1.appendChild(doc.createElement("videoconf")) el5.appendChild(doc.createTextNode(video)) valeurs.appendChild(element) doc.writexml(open("roomlist.xml","w")) return render(request, 'booking/bmr.html', {}) Here this is my form data which are storing into xml format. But I need to modify the above as per the following condition. 1-Vulnerable code: Application uses SQL Query to search for the room(use sql query to search xml data). The user input (room name) is direct without any validation resulting in injection attack. 2-Incorrect solution #1: Escape special SQL characters by hand adding a `\` before any special characters 3-Incorrect solution #2: URL encode paste contents in the request before passing it to the model layer 4-Incorrect solution #3: Remove special SQL characters 5-Correct solution: Use prepared statement and pass arguments to it properly Here I need to modify the code as per the above … -
How to generate token for every user registration and send that token to registered user?
Please help I'm struck at generating tokens and sending token for every registered user. -
Custom Django Inline Model
Now, I have two tables, master table 'questions' and detail table 'answers'.When i used django's tabularinline to display them at the same times. How can i custom the 'answers'? I tried some methods, but all failed -
Multiple Repeat error when submitting a django form containing char field for phone number
I am a beginner in django/python. I have created a charfield in my django model for storing phone number of user. I have provided a regex validator for validating entries made by user but when I submit the form it gives multiple repeat error. I am not sure why this error comes. Any help is appreciated. Here is the model `class Contact(models.Model): account_company_name = models.ForeignKey('Account', on_delete=models.CASCADE, db_column='account_id') name = models.CharField(db_column='Contact name', max_length=120, blank=False, null=False) email = models.EmailField(primary_key=True, db_column='Email', blank=False, null=False) phone = models.CharField(primary_key=True, max_length=10,validators = [RegexValidator(r'\d{10}+|\d{5}([- ]*)\d{6}')],\ db_column='Phone', blank=False, null=False) notes = models.TextField() class Meta: db_table = 'Contact' ` -
Can not display the proper value using Django and Python
I have an issue. I could not fetch and display the value using Django and Python. I am explaining my code below. def viewbook(request): doc = minidom.parse("roomlist.xml") staffs = doc.getElementsByTagName("location") root = [] for staff in staffs: lname=staff.getAttribute("name"); roomname=staff.getElementsByTagName("roomname")[0] seat=staff.getElementsByTagName("noseats")[0] project=staff.getElementsByTagName("projectorscreen")[0] video=staff.getElementsByTagName("videoconf")[0] root.append({'lname':lname,'roomname':roomname,'seat':seat,'project':project,'video':video}) Here I am fetching the data from my .xml sheet and the sheet is given below. <?xml version="1.0" ?><roomlist> <location name="Bangalore"> <room id="1uy92j908u092"> <roomname> Aquarius </roomname> <noseats> 10 </noseats> <projectorscreen>yes</projectorscreen> <videoconf>yes</videoconf> </room> </location> <location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist> Here I am trying to display the values in tabular format and the code is given below. <tr> <th>Location Name</th> <th>Room Name</th> <th>seats</th> <th>Projector screen</th> <th>Video Conference</th> </tr> {% for person in people %} <tr> <td>{{person.lname}}</td> <td>{{person.roomname}}</td> <td>{{person.seat}}</td> <td>{{person.project}}</td> <td>{{person.video}}</td> </tr> But in my case I am getting the below kind of output. Location Name Room Name seats Projector screen Video Conference Bangalore <DOM Element: roomname at 0x7fcc35275440> <DOM Element: noseats at 0x7fcc35275560> <DOM Element: projectorscreen at 0x7fcc35275290> <DOM Element: videoconf at 0x7fcc352757a0> Bhubaneswar <DOM Element: roomname at 0x7fcc35262cf8> <DOM Element: noseats at 0x7fcc374fb6c8> <DOM Element: projectorscreen at 0x7fcc36579128> <DOM Element: videoconf at 0x7fcc352756c8> Here I need to get all proper value from the xml sheet. Please help me to resolve … -
Django checking related model child objects SUM to zero
I'm making a Journal model with several Line objects attached to it like so: class Journal(models.Model): absolute_value = models.DecimalField() class Line(models.Model): invoice = models.ForeignKey(Journal) description = models.CharField(max_length=64) value = models.DecimalField() This is double-entry so every Journal will have: a variable number of Line objects (but least 2, which is easy to validate) Journal.lines.aggregate(SUM(value)) must always equal zero. The integrity of the check and zero-netting-out is paramount. If a Line is ever changed the system for whatever reason needs to be 100% certain that the Journal.lines always nett out to 0. Astute readers will have figured out here that if a Line.value is changed Journal.lines.aggregate(SUM(value)) will become different to zero (hopefully temporarily). Also, the app has no way to know when (or if) all the lines are updated. Basically when a Line.value changes the "balance" checking needs to be suspended until all the Line objects with the same parent Journal have been changed. But at the time of Line.save() the system has no way of know when all sibling Line object have been processed so when to suspend/unsuspend the check. Upon thinking about it, an answer seemed to be that if Line objects could only ever be saved through Journal objects, … -
ValueError: too many values to unpack in Django models
Test.py """ The files serves to test everything within the memepost app. """ from django.test import TestCase from memepost.models import memepost, memepostForm from datetime import date import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class memepostTestCase(TestCase): def setUp(self): memepost.objects.create(title="foo", model_pic="/site_media/media/pic_folder/casual_headshot.jpg", date=date(2017, 05, 14)) memepost.objects.create(title="bar", date=date(2017,05, 1)) def test_memepost_enters_database(self): foo = memepost.objects.get("foo") bar = memepost.objects.get("bar") self.assertEqual(foo.date, "6/15/17") logger.debug("foo date is equal to %s", foo.date) self.assertEqual(bar.model_pic, "no-img.jpg") logger.debug("bar is equal to %s", bar.model_pic) models.py """ models.py This file serves to be scheme for creating memes in my database. """ from __future__ import unicode_literals from django.forms import ModelForm from django.db import models # Create your models here. class memepost(models.Model): title = models.CharField(max_length=140) model_pic = models.ImageField(upload_to='pic_folder/', default='pic_folder/no-img.jpg') date = models.DateTimeField() def __unicode__(self): return self.title class memepostForm(ModelForm): class Meta: model = memepost fields = ["title", "model_pic", "date"] error Okay, so I am getting this warning, but I think the problem has something to do with the title paramater since I call a get function by the title. I hope I was clear. WARNING:py.warnings:/home/ubuntu/workspace/mysiteenv/local/lib/python2.7/site-packages/django/db/models/fields/init.py:1393: RuntimeWarning: DateTimeField memepost.date received a naive datetime (2017-05-01 00:00:00) while time zone support is active. RuntimeWarning) E ====================================================================== ERROR: test_memepost_enters_database (memepost.tests.memepostTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ubuntu/workspace/mysite/memepost/tests.py", line 20, in test_memepost_enters_database foo … -
What kinds of websites are built using Ruby on Rails, Node, and Django? [on hold]
Are certain kinds of websites easier to develop with certain web frameworks? Can any website idea be built with any of the web frameworks? Looking for general pros and cons of each. -
Django ImageField Validation
Hello stack overflow, I'm running into an issue validating the filetype of user submitted files. I'd like to confirm that anything the user uploads is an image type, if the user uploads something different I'd like to throw an error. As far as I can tell, the 'validate_file_extension' method below isn't being called at all. models.py class Post(models.Model): #renames images with a timestamp, avoids diplicate names def get_upload_to(self, filename): filename, file_extension = os.path.splitext(filename) timestamp = 'media/%f' % time.time() return str(timestamp + file_extension) def __str__(self): print(self.pub_date) return str(self.title + " " + self.pub_date.strftime("%Y-%m-%d")) def validate_file_extension(self, value): ext = os.path.splitext(value.name)[1] print("README " + ext + " README") valid_extensions = ['.png', '.gif', 'jpg', '.jpeg'] if not ext in valid_extensions: raise ValidationError(u'File not supported!') title = models.CharField(max_length=250) pub_date = models.DateTimeField() author = models.ForeignKey(User, db_column="user", default=1) image = models.ImageField(upload_to=get_upload_to, validators=[validate_file_extension], blank=True, default="media/defaultBlogImage.png") body = HTMLField() Here's a link to the rest of the source code https://github.com/kevin-reaves/Blog -
Why won't my index.html connect to my index.css file?
My index.html won't connect to my index.css for some reason. I can't see why. Maybe it's the path of files or something. I apologize for such a noob question. My index.css file has a small bit of code just to test out and see if it works. Here's my index.html file: <!DOCTYPE html> <html lang="en"> <head> <title>The Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="index.css"> </head> <body> <div class="container"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="firstName">First Name:</label> <input class="form-control" id="firstName" placeholder="Enter first name" name="firstName"> </div> <div class="form-group"> <label for="">Last Name:</label> <input class="form-control" id="lastName" placeholder="Enter last name" name="lastName"> </div> <div class="checkbox"> <label><input type="checkbox" name="remember">Remember me</label></div></br> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> </body> </html> Here's my index.css file: html { background: chocolate; } -
making a website which get data from another website
i want to build a website which gets data(html) from another website at every 15 minutes. I will work on Django. For doing this, which subjects must i focus? I thought, i can store these datas on my database, but how my website gets data automatically and stores in database. For example, i used pandas library for doing this on my desktop application, but i cant figure how works on website. Actually i tried to setup beautifulsoup on django website, so it didnt work. (i think it is very silly) Is there any easy solution for this, or any suggestion? -
Django View Cache vs. Template Cache
I'm trying to improve my websites Time To First Byte (TTFB) using the Django cache framework. How does the view cache differ from the template cache? If I use the cache_page() decorator on some view foo(), does this include caching the template? If so, does that mean the plain-text HTML is cached or does the template need to be rendered again. I have a page that does not change often. I'd like to cache this page for 24 hours. Do I need to add the cache_page(24*60*60) decorator + wrap my template in a template tag {% cache 86400 %} around my template? Thank You! -
Display attribute of a foreign key in a form in Django
I have 2 models class Task(models.Model): taskid = models.AutoField(primary_key=True,default = increment_booking_number) projectcode = models.ForeignKey('Project', models.DO_NOTHING, db_column='projectid') taskname = models.CharField(max_length=100) taskdescription = models.TextField(max_length=500, blank=True, null=True) and class Project(models.Model): projectid = models.AutoField(primary_key=True,default = increment_project_number) teamcode = models.ForeignKey('Teammember', models.DO_NOTHING, db_column='teamcode', blank=True, null=True) projectname = models.CharField(max_length=40, blank=True, null=True) projectdescription = models.CharField(max_length=255, blank=True, null=True) and in my form I want to display the projectname but it displays "Object object" class TaskForm(forms.ModelForm): class Meta: model = Task fields = ( 'projectcode', 'taskname', 'taskdescription',) I tried something like this: projectname = forms.ModelChoiceField(queryset = Project.objects.all()) but it's not good... Any advice please? -
How do I encode the password for my user registration viewset in Django REST Framework?
I'm trying to add user registration functionality to my Django REST application. Here is my serializer: from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) class Meta: model = User fields = ('url', 'id', 'username', 'password', 'email', 'snippets') Here is my views: from snippets.serializers import UserSerializer from django.contrib.auth.models import User from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = User.objects.all() serializer_class = UserSerializer Right now it's storing the password in plain text. How can I encode the password? I would prefer to continue using the ViewSet classes as they're very clean and convenient. -
making phone number based login friendly and keep phone number unique
Sorry for the non-tech question. I got unexpected request that users of a web (django based) app should be able to use their phone number to login. It was working fine until someone with similar number signed in from a different country but under the same network. That is, the number 078******* exists already and it refused the registration. In fact, the phones are different cos they are in different countries. When country code is added, they do remain unique. However, during sign in, I really want to avoid asking them to include the country code; must like facebook signin. Whats the most sensible way to handle this? -
Django list object sent to AJAX function
I have a python list and I need to pass it to the front end matching list field. I am not sure how to do this. If it . requires AJAX, how can I pass list in form of JSON to the AJAX function? I am using python django framework. I am trying to do this in my view, but not sure how to catch this data on the frontend. Any idea on how I casn convert this data into JSON and handle it on the front end using AJAX. list = ['abc', 'def', 'ghi', 'kjl', 'mno'] return JsonResponse(list, safe=False) -
How to Store Test Conditions in Database
I'm developing an App to control different contracts. The problem is that each contract have a set of conditions that are variable, and based on those conditions, some deductions or penalties are applied. For instance, some contracts have a penalty if the monthly payment is made after the 5th. Others state that the first 3 payments have a unconditional deduction. So, What I need is a way to store those conditions in the database. Whats I was thinking: class Condition(models.Model): field = models.CharField() # Possibly using generic relations to offer all fields from the contract table... CONDITION_TYPE = ( ('E','Equal'), ('G','Greater Than'), ('S','Smaller Than'), ) condition = models.CharField(max_length=1,choices=CONDITION_TYPE) reference_value = models.CharField() Now, this seems a good way to tackle this problem, but can quickly grow in complexity since fields can be Text, Numbers, Booleans and Dates. The thing is that this problem seems to be a common problem, that probably was already solved by people much smarter than me. Problem in... I'm not finding any project or app. Does anybody have any pointers or suggestions to solve this issue, maybe in some way that I not thought about? -
Django form override Floatfield attribute
I'm trying override the "max_value" attribute in the child class without success. What I'm doing wrong? Parent Class class ParentForm(forms.Form): width = forms.FloatField(label='Width (B)', max_value=100, min_value=5) # others fields Child Class class ChildForm(ParentForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['width'].max_value = 50 -
Django Celery delay() always pushing to default 'celery' queue
I'm ripping my hair out with this one. The crux of my issue is that, using the Django CELERY_DEFAULT_QUEUE setting in my settings.py is not forcing my tasks to go to that particular queue that I've set up. It always goes to the default celery queue in my broker. However, if I specify queue=proj:dev in the shared_task decorator, it goes to the correct queue. It behaves as expected. My setup is as follows: Django code on my localhost (for testing and stuff). Executing task .delay()'s via Django's shell (manage.py shell) a remote Redis instance configured as my broker 2 celery workers configured on a remote machine setup and waiting for messages from Redis (On Google App Engine - irrelevant perhaps) NB: For the pieces of code below, I've obscured the project name and used proj as a placeholder. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery, shared_task os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY', force=True) app.autodiscover_tasks() @shared_task def add(x, y): return x + y settings.py ... CELERY_DEFAULT_QUEUE = os.environ.get('CELERY_DEFAULT_QUEUE', 'proj:dev') The idea is that, for right now, I'd like to have different queues for the different environments that my code exists in: dev, staging, prod. Thus, … -
How do you verify an email via javascript or django?
How can I verify that the users email address belongs to them? All of the answers I have found are verification ensuring the email is an actual email, but I want to verify that the email belongs to the user signing up. -
Triple Join in Django
This is the first time I've had a question that I couldn't find an answer to within an hour of searching here, so this is the first time I've had to post: How do I do a triple join in Django? This is a minimal version of what I already have: class A(models.Model): x = models.ForeignKey(X) y = models.ForeignKey(Y) class B(models.Model): y = models.ForeignKey(Y, related_name="Bs") z = models.ForeignKey(Z) value = models.IntegerField(default=0) class C(models.Model): x = models.ForeignKey(X) z = models.ForeignKey(Z) value = models.IntegerField(default=0) def updateA(): as = A.objects.all() for a in as: for b in a.y.Bs: if b.value <= C.objects.get(x=a.x, z=b.z).value: <a.stuff = b.stuff> What I really want is a triple join between tables A, B, and C, where a.x=c.x, a.y=b.y, b.z=c.z, AND b.value <= c.value, though I don't care about c after validating b.value <= c.value. Is there a way in Django to do more of this work in the database? The problem I have is that Django seems to inherently focus on two-way joins, and I don't see how to do a three-way join. Then again, I didn't know any Django or Python 6 weeks ago, so I'm new to this framework and don't know the more advanced tricks. -
How to extend app template from Zinnia?
How do you extend a Django app template from inside Zinnia's base.html? APP_DIRS is set to true but templates can't be found in namespaced app? in Zinnia base.html {% extends "app1/app1.html" %} says TemplateDoesNotExist. but in other apps template is found.