Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a New Table (Model) and Relating it to auth_user in Django
I am trying to create a new Model to keep track of the current password and the most recent previous password used. I want it to look like this crude example: ID --- CUR_PASS --- PREV_PASS 1 --- 123 --- 321 2 --- 456 --- 654 Is it possible to make the ID the username in my auth_user table? Here is the class I have so far: # class model to store previously used passwords class oldPass(models.Model): # username = models.ForeignKey('something') --> instead of ID? current_pass = models.CharField(max_length=100) prev_pass = models.CharField(max_length=100) class Meta: # meta class to define the table name db_table = "old_pass" I am trying to make it so I can have the ID be the username and when changing the password in auth_user, check back to the old_pass table and compare the values making sure it is neither. If it is either of em, kick back an error. My biggest issues are these: I don't know how to import auth_user so I can assign the username to this new table I don't know how to change the ID to be the username instead of numbers. (Would this be done using ForeignKey?) I want to be able to … -
How to display the site's user friendly name in a template in Django?
I am searching for a way to display my Django-CMS site name in a template. I created a basic Django-CMS site following this guide. The default site is named Example.com and I was able to change this name, from within the admin section, to "My Super Site". Following what, I tried to customize and apply a theme to it, following this guide. It suggests to use {{ request.site.name }} to display the name of the site on a page. However this turns up empty and so does {{ request.site }}. I searched further and found several pages approaching the subject with increasingly complicated propositions the older they were. Recent ones, like this one, suggested that this was not related to django-cms but to django itself and the sites framework. I looked into the documentation, particularly this page and this one which, if I understood properly, indicates that the site middleware, once activated, includes a site object in the request object available in the templates. I checked and the sites framework is enabled ('django.contrib.sites' in INSTALLED_APPS setting, SITE_ID defined and migrate ran). So, I don't understand why {{ request.site }} is empty. To clarify things, I am not looking for the … -
Pull session id of name djnago
Issue im having is i have two aps a login app that gets all the info the apps are working just fine. I am trying to set a session that displays the person name that logged in. But I cant get it to display. When I run the login app by itself not in another app it works. I believe it has something to do with the two apps together. I can pull a name with a for loop as such {% for i in info %} <h1>Hello {{ i.creator.name }}!</h1> {% endfor %} However that just gives me the first name in the list of people registered not the name of the person logged in. Currently {{ request.session.name }} is how I have it now. Which works when single app. Is there a trick to it when going from app to app? Index.html <h1>Hello {{ request.session.name }}!</h1> view.py def index(request): context = { 'info':Myblackbelt.objects.all() } print(Myblackbelt.objects.all()) return render(request, 'blackbeltapp/index.html', context) models from __future__ import unicode_literals from django.db import models from ..logReg.models import User class ProductManager(models.Manager): def add_product(self, postData, user): product = postData.get('product', None) if product is not None and user: Myblackbelt = self.create(product=product, creator=user) class Myblackbelt(models.Model): product = models.CharField(max_length … -
How I can develop a django app for a project with machine learning and data analytics tools?
I am an intermediate in machine learning and data analytics and want to develop an application to demonstrate related work. Is there any tutorial you can help me with? Thanks in advance. -
pyhton flask builtins.ValueError ValueError: operation parameter must be str
This is my code: db = get_db() query = 'UPDATE pages SET title = ?, text = ? WHERE id = ?',[request.form['title'], request.form['text'], page_id] db.execute(query) db.commit() I get an error: builtins.ValueError ValueError: operation parameter must be str I tried this: query = 'UPDATE pages SET title = (?), text = (?) WHERE id = (?)',[request.form['title'], request.form['text'], page_id] Didn't help. What do I do? -
Django - acces image from image field in the template
What I have done: in models.py: class Image(models.Model): img = models.ImageField(blank=True, Null=True) And now I want to acces the image in the template. I tried it, but it didn't work: (myimg is an instance of Image.) <img src="{{ myimg.img }}"> So: How do I acces the image from the template? Another thing: when I used my model like that the images where stored at the projects root. This doesn't seem to be a good idea. Where should they be stored? And how do I store them somewhere else. Some other little questions which deal with that problem: What is MEDIA_URL good for and how does it work? What is MEDIA_ROOT good for and how does it work? Where should files that aren't static (that means files a user or an admin uploads) be stored? -
Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found
Even after mentioning the name='password_reset_done', getting the NoReverseMatch error for 'password_reset_done'. below is the urls.py file of blog application. from django.conf.urls import url from . import views from django.contrib.auth.views import password_reset, password_reset_done urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^login/$', views.user_login, name='user_login'), url(r'^logout/$', views.user_logout, name='user_logout'), url(r'^reset-password/$', password_reset, name='password_reset'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'), url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), url(r'^(?P<tag_slug>[\w-]+)/$', views.post_list, name='post_list_by_tag'), ] Please help!!! -
Storing password in multiple entities - Django
I'm working on Django project and I want to have two different entities in database - (default Django) User and Doctors. I want to have stored password in both entities. def post(self, request, pk): username = Doctor.objects.get(pk=a).email password = Doctor.objects.get(pk=a).password user = User.objects.create_user(username, username, password) user.save() return redirect('ps:index') Atribute in forms.py for DoctorForm: password = forms.CharField(widget=forms.PasswordInput) But this is not working for passwords. I assume that the reason is hashing and salt. How to solve it? Any help would be appreciated. -
Django - prevent users from getting access to same value
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin. I want to keep them separately from each other. Still a newbie so guide me in the right way and appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': res = {'success': False} action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' association = Association.objects.filter(asoc_name=request.user.association) asoc = Association.objects.get(id=association) if action == 'add': Event.objects.create( name=name, location=location, start=start, end=end, allday=allday, description=description, synced=synced, association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] = eid res['data'] = Event.objects.values().get(id=eid) elif action == 'edit': eid = request.POST['eid'] event = Event.objects.get(id=eid) event.name = name event.location = location event.start = start event.end = end event.allday = allday event.description = description event.synced = synced event.save() … -
Unable to make the booleanfield true through submit button in django
I'm a complete novice to django. I want to make the is_hod booleanfield of class retest in models, true when I hit submit in the details page.How can it be possible. details.html <form action="{% url 'retest:accept' retest.id %} " method="post"> {% csrf_token %} <input type="submit" value="Submit" /> </form> urls.py url(r'^retest/(?P<retest_id>[0-9]+)/accept$' , views.accept, name='accept' ) views.py def accept(request, retest_id): retest = get_object_or_404(Retest, pk=retest_id) try: selected_retest = Retest.objects.get(pk=request.POST[retest_id]) except (KeyError, Retest.DoesNotExist): return render(request, 'retest/details.html' , {'retest': retest, 'error_message': "error",}) else: selected_retest.is_hod = True selected_retest.save() return render(request, 'retest/details.html' , {'retest': retest}) -
Django, cannot import name ~~ Error, but i cant find why it is
app1 : title // title.models.py from django.db import models from relationship.models import ContentRelationship from django.contrib.auth.models import User class Title(models.Model): titleText = models.TextField(max_length=160, unique=True) titleRelationship = models.OneToOneField('relationship.ContentRelationship', on_delete=models.CASCADE) def __str__(self): return self.titleText app2 : relationship // relationship.models.py from title.models import Title class ContentRelationship(models.Model): allow_set = models.ManyToManyField('UserRelationship', related_name="wdt_set", symmetrical=False, through="Wdt", blank=True) description = models.TextField(max_length=200, blank=True) def __str__(self): return self.description @receiver(post_save, sender=Title) def create_contentrelationship(sender, instance, created, **kwargs): if created: ContentRelationship.objects.create(Title=instance) @receiver(post_save, sender=Title) def save_contentrelationship(sender, instance, **kwargs): instance.contentrelationship.save() What i want is that if i create Title instance, then ContentRelationship also be created. But on that code, there is File "C:/Dev/TestProject/Test1\title\models.py", line 2, in <module> from relationship.models import ContentRelationship ImportError: cannot import name 'ContentRelationship' I searched and carefully made ForeignKey or ManyToManyField's to argument be 'relationship.ContentRelationship'. In other words, I made it string. But it didn't work. -
Django Clean_Field validation using field value from different Model
I am trying to validate a form field in a ModelForm based on the value of another field in a different model. Here is my ModelForm. CompanyData Model contains an "arr" field that I want to use as the value to validate against (that the "rev_goal" is higher): from django.forms import ModelForm from django import forms from django.core.exceptions import ValidationError from company_data.models import CompanyData from plans.models import Plan class PlanCreateForm(forms.ModelForm): def clean_rev_goal(self): rev_goal = self.cleaned_data['rev_goal'] company_data = self.object.companydata = CompanyData.objects.get **# This is wrong. But how do I get the arr field from CompanyData here so the next line of code works?** if rev_goal < company_data.arr: raise ValidationError("Revenue goal must be greater than current ARR $") return rev_goal class Meta: model = Plan fields = ['plan_name', 'rev_goal', 'months_to_project', 'cpl', 'conv_rate'] And I going about this completely wrong? Or is it possible to access the value of a field of a different model in a ModelForm? Thanks in advance for your help! -
Using django how can I login to my website to verify I own the product via a local client
I have a website I created in django, where you can buy products and one of these products is installed locally onto your machine. How do I first verify you own the product by logging in via the client which checks my database to see if you own the product. Thanks for any help and please ask if further clarification is needed. -
Is in web development future belongs to ASP.net Django and Javascript ?
My Professor told during lecture future belongs to Asp.net, javascript and Django all other languages are going to lost their shares, value in near future. Even PHP has now some years in industry. Now I am confuse as I was about to start learning Javaspring. How much reality is in this statement ? -
By Using python pil, I want to make image centered with text from url and download. How to do it?
I input a text at url, and want to get downloaded image that the text is centered. for example, when I input, http://127.0.0.1:8000/app/hello, then an image is downloaded. That image centers the text 'hello' By using python pil. How to do it? -
Error when trying to write to database Django
I am still learning Python via Django and have been doing most of my methods in views. I have been told that it is better practice to put them in my models under a Manager. I have the following code grabbing the product info and I believe the id to fill my model. but its throwing an error. Any help would be great. Traceback: File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dbhol\Desktop\blackbelttest ver 1\blackbelttest\apps\blackbeltapp\views.py" in create 43. viewsResponse = Myblackbelt.objects.add_product(request.POST) File "C:\Users\dbhol\Desktop\blackbelttest ver 1\blackbelttest\apps\blackbeltapp\models.py" in add_product 7. Myblackbelt = self.create(product = postData['product'], creator=secreteid) File "C:\Users\dbhol\Desktop\DojoAssignments\Python\myenvirnoments\djangoENv\lib\site-packages\django\utils\datastructures.py" in __getitem__ 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /blackbelt/create Exception Value: "u'product'" Html matters <form class="" action="{% url 'blackbelt:create' %}" method="post"> {% csrf_token %} <p>Product: <input type="text" name="product" value=""></p> <input type="submit" name="" value="Create"> </form> view.py that matters def create(request): viewsResponse = Myblackbelt.objects.add_product(request.POST) secreteid= User.objects.get(id=request.session['user_id']) return redirect ('blackbelt:index') Models in full from __future__ import unicode_literals from django.db import models from ..logReg.models import User class ProductManager(models.Manager): def add_product(self, postData): Myblackbelt = self.create(product = postData['product'], creator=secreteid) print 'dog here' def destroy(self, postData): self.get(id=postData).delete() def update(self, postData, … -
Choices VS Charfield in filtering
If database(Django ORM) is based on data which is parsed . And there is a 'city' field, which is often used when filtering data. Is it much better to use Chocies or just Charfield for saving 'city' into the field. Will be filtering much faster? -
Django - fetch data from database to appear in dropdown list
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar by clicking on the mini-calender-plus-icon in the right-top corner: https://gyazo.com/a74a980a1676a5d961efb3a782f15ddb Which will display a form: https://gyazo.com/e9b7cd46fa84c0017226b5743544f364 As you see, Association-dropdown-list won't show any data from database. I only want it to show association-name of the current admins-association. Is there something i'm missing? Looked everywhere for someone with similar issue over long time, with no luck. Still a newbie so appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': form = CalForm(request.user, request.POST) res = {'success': False} action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' asoc_id = form.request.POST['association'] association = Association.objects.get(pk=asoc_id.pk) if action == 'add': Event.objects.create( name=name, location=location, start=start, end=end, allday=allday, description=description, synced=synced, association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] = eid res['data'] = Event.objects.values().get(id=eid) elif action == 'edit': eid = request.POST['eid'] event = Event.objects.get(id=eid) event.name = name event.location = location … -
How to add a temporary field for calculation in django model?
I am developing a GIS based django app in which i am allocating the nearest exam center to a student based on his current location. I have my centre model like this class Center(models.Model): name = models.CharField(max_length=500) city = models.CharField(max_length=100) state = models.CharField(max_length=100) latitude = models.FloatField() longitude = models.FloatField() capicity = models.IntegerField() examid = models.ForeignKey(Exam) class Meta: ordering = ['distance'] I am using a function which accept the user's current location and city and then calculate the distance between the current location and all available centres in the given city. And then sort them by distance. But i don't want to change my centre model and use the distance attribute as a temporary attribute for the existing centre model. -
How to uplaod files in Django?
Im sorry I'm really new to django and I already tried the steps in the documentation. Unfortunately, its not working quite as I would expect. I was hoping that after executing the steps it would save the file to my media folder? If possible I'd also like to use ajax but I can't understand the flow. HTML <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.TextField(max_length=500, blank=True) contact_number = models.CharField(max_length=30, blank=True) profile_picture = models.FileField(null=True,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class UploadForm(forms.ModelForm): class Meta: model = Profile fields = ('profile_picture',) views.py def model_form_upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/home/') I'm trying to save a photo for a user's profile. Pls help me. If there is a way to do this in ajax that would be helpful as well. -
Process several forms on different views using only one save button
I am relative new at Django. However, I didn't find anything related to my question anywhere else.The problem is: I want to show seven different forms at the same page, but I would like to use only one save button. Is there a way to process each of them in different class/function views (let's say, seven different views)? ps(1).: I am aware that I can process all of them at the same view using prefixes. ps(2).: I didn't face this problem before while coding. I am just curious :) -
Create works but get_or_create doesn't . Django 1.8 + Python 3.4
This code works perfectly: for i in m: print(i) event = Event.objects.create(title=titles[i]) # event = Event() event.title = titles[i] event.image_link = images[i] event.city = cities[i] # event.place = placies[i] # event.date = dates[i] event.save() print (Event.objects.all()) But if I change create to get_or_create , it doesn't work at all without any errors or something. Possibly there is something missing in my understanding how get_or_create works? for i in m: print(i) event = Event.objects.get_or_create(title=titles[i]) # event = Event() event.title = titles[i] event.image_link = images[i] event.city = cities[i] # event.place = placies[i] # event.date = dates[i] event.save() print (Event.objects.all()) -
delete email address from invitation if user has signed up
There is a situation that when a user has requested for invitation, he/she will then get to signup the account. When request is accepted by admin then they can signup which i have done. But i have no idea on how to delete the email address from the invitation table once that user has signed up successfully. I am using django allauth package. class CustomSignupForm(forms.Form): def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) def clean(self): email = self.cleaned_data.get('email') if email and settings.INVITE_MODE: try: obj = Invitation.objects.get(email=email) if not obj.request_approved: self.add_error('email', 'Sorry your invitation is still in pending') except Invitation.DoesNotExist: invitation = Invitation.objects.create(email=email) self.add_error('email', 'Sorry at this time you are not invited. But we have added you to our invite list') elif email is None: raise forms.ValidationError('Email field should not be empty') else: return email class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_("e-mail Address")) invite_code = models.UUIDField(default=uuid.uuid4, unique=True) points = models.PositiveIntegerField(default=5) request_approved = models.BooleanField(default=False, verbose_name=_('request accepted')) status = models.BooleanField(default=False) @receiver(post_save, sender=Invitation) def send_email_when_invite_is_accepted_by_admin(sender, instance, *args, **kwargs): request_approved = instance.request_approved if request_approved: subject = "Request Approved" message = "Hello {0}! Your request has been approved. You can now signup".format(instance.email) from_email = None to_email = [instance.email] send_mail(subject, message, from_email, to_email, fail_silently=True) -
Setting up VS Code for Django Development?
I'm having a horrible time writing Django (Python) Code in VS-Code. Since it is considered one of the better IDEs for Django Development I think it must be my fault. E.g. when i type var+Tab in an html template and instead of {{}} I get caused by the html snippet extension. I can not use half of the key shortcuts because they link to weird key combinations, that do not seem to work on my keyboard etc. All in all, it has been an extremely unpleasant experience using vs-code. So far I've been using HTML Snipptes, and Python, Python Extended, Python Magic and various Django Snipptes Extensions. And there never seems to be something like a steady workflow. Is anyone interested in sharing good extensions, frequently used key-shortcuts etc. to make the experience better? -
sqlite3.IntegrityError: NOT NULL constraint failed
I've never dealt with file uploading before this is my first time and I followed the instructions on youtube. Apparently when I added a FileField in my models and tried to migrate, it threw me some exceptions and I don't know how to fix it. I tried to remove the parameters but it still gave me an error. Pls help me (Im using django btw) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.TextField(max_length=500, blank=True) contact_number = models.CharField(max_length=30, blank=True) profile_photo = models.FileField(null=True,blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and then this error came up which I cant understand Running migrations: Applying bartr.0011_profile_profile_photo...Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: bartr_profile.profile_photo