Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
there is no such column as field_name defined
I am using the django edge template for my project, I want to extend the profile model to include my own fields but its giving me an error of field collumn not existing. Can anyone help on how I can add my own fields to this model. -
Sending Email with Django
I am using send_email( ... ) to send email with Django. My settings.py is configured like so EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'info@myemail.com' #DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_FROM = 'info@myemail.com' EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 465 While the django-admin site indicates that the message has been sent, it never makes its way to the inboxes of the recipients. I have tried different values for EMAIL_PORT, such as 587. This site uses the HTTPS protocol, so I thought the EMAIL_BACKEND I set was appropriate for the situation, but in case it didn't apply here, I've also tried EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have checked all of the log files I can find and no error is showing up anywhere. What's more, is that the configuration I'm using in my settings.py and the send_email(...) code I'm using is identical to those on a server that does send mail in such a way that the recipients receive it. What could be the reason why my sent mail does not make its way to the recipient's inbox? -
Django not in other table (Not using id)
I have: Models: class Category(models.Model): description = models.CharField(unique=True, max_length=200) myfield = models.CharField(unique=True, max_length=200) class Car(models.Model): categorys = models.ManyToManyField(Category) myfield = models.CharField(unique=True, max_length=200) I am trying to execute the following query: Car.objects.filter(category__id = c.id ) .exclude(myfield__in = Category.objects.all() .only('myfield') ) .order_by("id") .first() I expected to find a result like this: SELECT ... FROM `myapp_car` INNER JOIN `myapp_car_categorys` ON (`myapp_car`.`id` = `myapp_car_categorys`.`car_id`) WHERE ( ... AND NOT (`myapp_car`.`myfield` IN (SELECT `myapp_category`.`myfield` FROM `myapp_category`))) ORDER BY `myapp_car`.`id` ASC LIMIT 1; But i find: SELECT ... FROM `myapp_car` INNER JOIN `myapp_car_categorys` ON (`myapp_car`.`id` = `myapp_car_categorys`.`car_id`) WHERE ( ... AND NOT (`myapp_car`.`myfield` IN (SELECT `myapp_category`.`id` FROM `myapp_category`))) ORDER BY `myapp_car`.`id` ASC LIMIT 1; I need use myfield in select, not id: (SELECT `myapp_category`.`myfield` FROM `myapp_category`) How would I get this result? -
Django Concurrency Restrict other user to access object
I have created API using Django Rest Framework URL: /get_item/ Here is list of items ids, 1 2 3 4 5 If user A, call get item API, she gets item id 1 and if user again call the get item API, she should get item id 1. If user B. call get item API, she should get item id, 2 as item id 1 is accessed by user A. If user A, complete the item. item id 1 is automatically excluded from the list and when user A call get item API, she should get item id: 3. -
Building a select from two models with optgroup and options
Still learning Django, I have two chained models Category->SubCategory via a ForeignKey and want to print an HTML select like that : <select name="category" id="id_category_list"> <optgroup label="Category 1"> <option value="0">SubCategory 1</option> <option value="1">SubCategory 2</option> </optgroup> <optgroup label="Category 1"> <option value="0">SubCategory 1</option> <option value="1">SubCategory 2</option> </optgroup> </select> As I read, in order to do it, I have to format a list that way : ('Category name 1', ('1', 'SubCategory name 1'), ('2', 'SubCategory name 2'), 'Category name 2', ('3', 'SubCategory name 3'), ) So I tried to code it that way : #Models.py class Category(models.Model): category_name = models.CharField(max_length=200) def __str__(self): return self.category_name class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory_name = models.CharField(max_length=200) def __str__(self): return self.subcategory_name #forms.py class Form(forms.Form): categorychoices = [] categories = Category.objects.all() for obj1 in categories: subcategories = SubCategory.objects.filter(category=obj1.pk) for obj2 in subcategories: categorychoices.append( (obj1.category_name, (obj2.pk, obj2.subcategory_name) ) ) SubCategory = forms.ChoiceField( choices=categorychoices, required=True, label="Category *", #empty_label="«Choose a category»" ) As a beginning, my template is really simple and aims only at displaying my HTML select: #myform.html <form action="#" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> I "played" with ChoiceField as written here, TypedChoiceField and ModelChoiceField but with no luck. I got runserver working … -
Django filter with many fields
I want to filter object and get result if at least one field contains this name. models.py: class Item(BaseModel): name = models.CharField(max_length=255) seller = models.ForeignKey(Company) quantity = models.FloatField(default=0.0) I tried this one but it doesn't work. views.py: search_filter_kw = {} item_name = request.GET.get("searchitemname", '') if item_name != '': search_filter_kw['Q(name__contains) | Q(seller__name__contains)'] = item_name -
Why my Django ModelForm doesn't raise validation error for unique_together constraint?
I have read in Django documentation that the clean() method of ModelForm validates the unique_together constraint on my model, and raises a ValidationError if it is not validated. However my ModelForm doesn't do this. At least it doesn't give an error message in the form, instead I get a Django error and traceback: ValueError at / The Jelentkezes could not be created because the data didn't validate. This is not because I have excluded one of the fields of the unique_together constraint. Other validations of the form work, they give error messages on the form. Please help, thank you! I use Django 1.10 and Python is 3.5. I have created the following models in models.py: from django.db import models class FoglalkozasTipus(models.Model): foglalkozas_tipusa = models.CharField(max_length=255, unique=True) def __str__(self): return '%s' % (self.foglalkozas_tipusa) class Foglalkozas(models.Model): kezdet = models.DateTimeField() veg = models.DateTimeField() foglalkozas_tipusa = models.ForeignKey(FoglalkozasTipus, on_delete=models.CASCADE) class Meta: unique_together = (("kezdet", "veg"),) ordering = ['kezdet', 'veg'] def __str__(self): return '%s-%s %s' % (self.kezdet.strftime("%Y.%m.%d %H:%M"), self.veg.strftime("%H:%M"), self.foglalkozas_tipusa) class Jelentkezes(models.Model): foglalkozas = models.ForeignKey(Foglalkozas, on_delete=models.CASCADE) email = models.EmailField() vezeteknev = models.CharField(max_length=255) keresztnev = models.CharField(max_length=255) class Meta: unique_together = (("foglalkozas", "email"),) def __str__(self): return '%s: %s %s (%s)' % (self.foglalkozas, self.vezeteknev, self.keresztnev, self.email) For model Jelentkezes I … -
simple jQuery code is not executed when rendering django template
I want to hide a table row based on its class. Everything is working fine except the js file is not executed and I cannot hide the table row. What is the problem? html file: {% extends "heaven/home.html" %} {% load staticfiles %} <script src="{% static '/js/hide.js' %}"></script> hide.js $('.cemeteryRow').hide(); hide.js sits in static/js folder. Class=cemeteryRow. -
Wagtail-approach for comments
We have a blog-like wagtail site and would like to add comments to our post types. Each post is a page object. We thought about using django-contrib-comments or implement an own plain django comments app with ajax. But what would be the "all-wagtail-approach" for having a comment functionality on the public wagtail site (only for logged in wagtail users, using ajax)? We're not looking for a complete implementation, we just need some hints or tips for a wagtail-sensible approach. -
Django +Celery +SQS -> boto.exception.SQSError: SQSError: 599 gnutls_handshake()
I have Django app in Production working together with Celery and Amazon SQS. Every day queues are crashing with following error: File "/home/ubuntu/virtualenvs/env/lib/python3.5/site-packages/kombu/async/aws/connection.py", line 269, in _on_list_ready raise self._for_status(response, body) boto.exception.SQSError: SQSError: 599 gnutls_handshake() failed: An unexpected TLS packet was received. How can I solve it? -
Django not receiving GET request from Javascript jQuery function
I am attempting to get some data via Ajax for a web app I am building. When I load the following function I am not seeing a GET request from Django but I do see the first alert pop up. I am new to JS and jQuery so please excuse my ignorance but I cannot seem to figure out what I am doing wrong. function get_file_system(){ alert('in alert'); $.getJSON("ajax/load_file_system/", function (data) { alert('in alert 2'); var top_line = '<p><span class="glyphicon glyphicon-folder-open"></span>"+ data.current_dir +"</p>'; $('#file_system_jumbo').text(top_line).append('<ul class="list-group" id="file_system_list"></ul>'); $.each(data.child_dirs, function(value){ $('#file_system_list').append('<li class="list-group-item"><p><a href="?ajax/load_file_systemnew_dir={{ value.1 }}"><span class="glyphicon glyphicon-folder-close"></span>{{ value.0 }}</a></p></li>') }); $.each(data.child_files, function(value){ $('#file_system_list').append('<li class="list-group-item"><p><a href="ajax/load_file_system?new_dir={{ value.1 }}"><span class="glyphicon glyphicon-folder-close"></span>{{ value.0 }}</a></p></li>') }); }) } get_file_system(); Finally I have this in my urls.py file. url(r'^ajax/load_file_system/$', views.load_file_system, name='load_file_system'), Thanks for the hep. -
Getting "DoesNotExist: Permission matching query does not exist" while using django-groups-manager with django-guardian
I am trying to use django-groups-manager to achieve permissions on hierarchical groups. Basically, just following an example given at django-groups-manager.readthedocs. My virtual env "pip freeze" looks like this: (guard) MacBook-Pro [guard]$ pip freeze awesome-slugify==1.6.5 Django==1.10.4 django-braces==1.10.0 django-groups-manager==0.5.0 django-guardian==1.4.6 django-mptt==0.8.6 jsonfield==1.0.3 psycopg2==2.6.2 regex==2016.11.21 six==1.10.0 Unidecode==0.4.19 My settings.py has the recommended settings like: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'guardian', 'groups_manager', 'tutorial.quickstart' ) GROUPS_MANAGER = { 'AUTH_MODELS_SYNC': True, } I have couple models to play with for permissions assignment like: from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=32, blank=False, unique=True) cost = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('view_product', 'View Product'), ('sell_product', 'Sell Product'), ) def __str__(self): return str(self.name) def __unicode__(self): return str(self.name) Also I have done the relevant makemigrations and migrate to get the tables created for django groups models as well as my own Product model. All the initial fancy group hierarchy creation works. But I get the following error at the assigning permissions - the main objective of mine. >>> from groups_manager.models import Group, GroupType, Member >>> from tutorial.quickstart.models import Product, Budget >>> >>> >>> # Create group types (optional) >>> organization = GroupType.objects.create(label='Organization') >>> division = … -
Django update password made last_name empty
I'm using UserProfileSerializer to validate fields in patch request: password = request.data.get('password', '') if password: if len(password) < 6: return Response(status=status.HTTP_400_BAD_REQUEST) hashed_pass = make_password(password) serializer = UserProfileSerializer(instance=user, data={'last_name': request.data.get('last_name', ''), 'password': hashed_pass, partial=True) else: serializer = UserProfileSerializer(instance=user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() and this is my serializer: class UserProfile(models.Model): class meta: abstract = True password = models.CharField(_('password'), max_length=128, blank=True) last_name = models.CharField(max_length=30, validators=[MinLengthValidator(3)], blank=True) class UserProfileSerializer(ModelSerializer): class Meta: model = UserProfile When i'm updating password, the last_name made empty!! How i prevent it. -
Django CBV return different page based on form data
Using CreateView, I am trying to save and return a url based on the items selected in the form. This is for a workout log site where the second form you are directed to is based on the type of workout you want, based on info entered in the first form. I would like to do this without Javascript: class WorkoutLogCreateView(CreateView): model = Workout_Log template_name = 'workout/workout_log_create.html' fields = ['date_time', 'modality', 'workout_type', 'workout_model'] #something like this: def get_success_url(self): if workout_type = '5 rounds' return reverse('five-rounds-log-create') if workout_type = 'Drop Reps' return reverse('drop-reps-log-create') else return reverse('workout-log-menu') def get_context_data(self, **kwargs): context = super(WorkoutLogCreateView, self).get_context_data(**kwargs) context['action'] = reverse('workout-log-create') return context -
Send verification 6 digits code in user email using django 1.9?
I am trying to use django allauth for user registration and all. But, the scenario for my case is bit different. Let me explain the use case: 1. Use will be allowed to enter his/her email only on the input box. 2. Once the email is entered, the app need to send a 6-digit verification code I didn't see any configuration related to this in django allauth? I am using right app or there exists other which best suits my interests? Thank you in advance. -
Redirect URL, depending up on the patterns in django, Python
My urls.py page is: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<string1>[\w\+]+/|[\w\-]+/|\d{4}-[01]\d-[0-3]\d/|)$', views.single_element), url(r'^(?P<string2>[\w\+]+/[\w\-]+/)$', views.double_element), url(r'^(?P<string3>[\w\+]+/[\w\-]+/\d{4}-[01]\d-[0-3]\d/)$', views.triple_element), ] And when ever I try to open the URL "localhost:8000/" Its working and the first index url is being called. "localhost:8000/sherlock_homes" Its being redirected to single_element view. But when I try this(below) "localhost:8000/sherlock_homes/hollywood+theater/" When I load this above url, I need to be redirected to something like "localhost:8000/hollywood+theater/sherlock_homes/"(for better readability of URLS). I need to interchange the pattern matches in the url. Example: Whenever users enters this url "localhost:8000/2016-12-12/hollywood+theater/". It need to be changed to "localhost:8000/hollywood+theater/2016-12-12/".(for better readability of URLS) How to do that, and which is the better place to do it (In urls.py or in views.py or at template.html)? Thanks in advance. -
Implementing a Voting system in Django
Hello all at Stack Overflow, I'm looking for help in solving a problem in Django (Python base with sqlite database). Part of an assignment I have been given for a course is as follows: implement a table-based voting system in Django using Python in an HTML Template. This is composed of three radio buttons, each of which represents a voting option. This looks as follows: voting item name voting item image radio button voting item name voting item image radio button voting item name voting item image radio button "vote" button with POST command. When the user clicks the "vote button", the code should confirm which option was selected, and update the relevant voting count in the database. Having looked at the documentation, and having constructed an appropriate database and template, I am unclear as to how to best set up the required Django views and database post/retrieval code. What, in your opinion, would be the best way to go about doing so? -
django check if model exist and return that to views.py
I am super new to django and I have the following problem. I have some users in my Model "User" which has an email and a username field. I created a LoginFrom in my forms.py which only accepts an email address and checks if it exist in the User database. Then I want to return to my views.py and retrieve that model and work with it. Very simple but, I cant do this return email_get in my forms.py as it says user already exists. The only way I can get back to views.py is by changing the form email that I got. Something like, email_got="found@gmail.com" return email_got So, how can I return to forms.py by keeping the original form email. Ps, I just want to manually check if user exist in database. Here's my forms.py from django import forms from .models import User class LoginForm(forms.ModelForm): class Meta: model=User fields= ['email'] def isUser(self): email_got = self.cleaned_data.get('email') if User.objects.filter(email=emailAt).count() == 1: user = User.objects.get(email__exact=email_got) print(getattr(user, 'username')) return emailAt And my views.py from django.conf import settings from django.shortcuts import render from django.core.mail import send_mail #for sending mail from .forms import SignUpForm, LoginForm from .models import User def login(request): username = None form=LoginForm(request.POST or … -
OperationalError: (2019, ""Can't initialize character set utf8mb4 (path: C:\\mysql\\\\share\\charsets\\)"")
I configured my Django database setting in settings.py with: 'OPTIONS': {'charset': 'utf8mb4'}, All columns and tables are set to utf8mb4. I want this encoding so I can store emojis. When I start my script on Mac or Linux, it works fine, but on Windows, I get: <module> C:\Users\Josh\Documents\mysite\myproj\scripts\crawler.py 154 __getitem__ C:\Python27\Lib\site-packages\django\db\models\query.py 295 __iter__ C:\Python27\Lib\site-packages\django\db\models\query.py 256 _fetch_all C:\Python27\Lib\site-packages\django\db\models\query.py 1087 __iter__ C:\Python27\Lib\site-packages\django\db\models\query.py 54 execute_sql C:\Python27\Lib\site-packages\django\db\models\sql\compiler.py 833 cursor C:\Python27\Lib\site-packages\django\db\backends\base\base.py 231 _cursor C:\Python27\Lib\site-packages\django\db\backends\base\base.py 204 ensure_connection C:\Python27\Lib\site-packages\django\db\backends\base\base.py 199 __exit__ C:\Python27\Lib\site-packages\django\db\utils.py 94 ensure_connection C:\Python27\Lib\site-packages\django\db\backends\base\base.py 199 connect C:\Python27\Lib\site-packages\django\db\backends\base\base.py 171 get_new_connection C:\Python27\Lib\site-packages\django\db\backends\mysql\base.py 263 Connect c:\users\josh\appdata\local\temp\easy_install-iz3bc1\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\__init__.py 81 __init__ c:\users\josh\appdata\local\temp\easy_install-iz3bc1\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\connections.py 221 set_character_set c:\users\josh\appdata\local\temp\easy_install-iz3bc1\MySQL_python-1.2.5-py2.7-win32.egg.tmp\MySQLdb\connections.py 312 "OperationalError: (2019, ""Can't initialize character set utf8mb4 (path: C:\\mysql\\\\share\\charsets\\)"")" The line of code it throws the exception on is: Object.objects.filter(last_scraped__isnull=True)[0] Versions: Python 2.7 Database: MariaDB 5.5 Windows 7 64-bit -
Django Filter Buttons
I'm using Django-filter in a very standard way. class TaksFilter(django_filters.FilterSet): class Meta: model = Task fields = ['lastUpdated'] But I want to create custom quick filter buttons. Like last 1 day and last 7 days which essentially run this query set. task = Task.objects.filter(lastUpdated__range=["2016-12-09", "2016-12-10"]) Is this something that can be done with django-filter or do I need to create a standard POST or GET response? Thanks! -
Weird namespacing for Django templates -- why?
If you read e.g. the Django tutorial it will explain to you that you should put templates for a 'polls app' into a folder like so: polls/templates/polls/index.html Here, the folder 'polls' is the app folder and it is located inside the 'myproject' folder. They specifically mention the following: Template namespacing Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself. To me it seems like a mistake in the implementation of Django templates. Concretely, it seems that the template loader purposefully disregards information, namely, the 'polls' it gets from the path ./polls/templates. My question is: As far as I can tell one could have made the template loader so that it … -
Django: Passing object from template to views
I want to use the same template to view information about each of my database objects. I would like to be able to click on each element in the list and have it link me to a page with info about it. I'm thinking there's an easier way than making a view for each unique object. I'm listing all of my database objects on my list.html like this: {% for instance in object_info %} <li><a href="object">{{ instance.name }}</a></li> {% endfor %} My views.py has this view: def object_view(request): data = Object.objects.filter(name="") context={ 'object_info':data } return render(request, "object.html", context) Can I pass each {{ instance.name }} to the view and use that as a variable for my filter? -
Django: Can't log in using normal auth
I'm using the normal development server for Django and i am building a simple app. A user should be able to log in and change his email and password. To understand the django system better, I decided to write the views and such myself, only using the contrib.auth library. Now to the problem: Once a user logs in and changes his password, he cannot login again, unless he logs into the standard django admin page before. Here is my code: the views.py def login(request): print("test") if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: return HttpResponseRedirect('/accountManagement/home') else: form = LoginForm() else: HttpResponse("form is not valid") else: form = LoginForm() return render(request, 'accountManagement/login.html', {'form': form}) def home(request): print(request.user.username) if request.user.is_authenticated: passwordForm = ChangePasswordForm() emailForm = ChangeEmailForm() return render(request, 'accountManagement/home.html', {'passwordForm': passwordForm, 'emailForm': emailForm}) else: return HttpResponseRedirect("/accountManagement/") def change_password(request): if request.user.is_authenticated: if request.method == 'POST': passwordForm = ChangePasswordForm(request.POST) if passwordForm.is_valid(): oldPassword = passwordForm.cleaned_data['oldPassword'] newPassword = passwordForm.cleaned_data['newPassword'] newPasswordConfirmation = passwordForm.cleaned_data['newPasswordConfirmation'] if (newPassword == newPasswordConfirmation) and (request.user.check_password(oldPassword)): request.user.set_password(newPassword) request.user.save() return HttpResponseRedirect("/accountManagement/logout") else: return HttpResponse("password change failed") else: return HttpResponse("password form not valid") else: return HttpResponse("request != POST") else: return … -
How to request object.id in form clean data funtion
Have a models: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) variation_1 = models.BooleanField(default=True) variation_2 = models.BooleanField(default=True) variation_3 = models.BooleanField(default=True) class Order(models.Model): buyer = models.ForeignKey(User, related_name='buyer') product = models.ForeignKey(WowRaid) variations_select = models.CharField(max_length=50, choices=VARIATIONS) in forms.py class OrderForm(forms.ModelForm): variations_select = forms.ChoiceField(choices=VARIATIONS) class Meta: model = Order fields = [ 'variations_select' ] i need to create a clean function that will check if variation_1 or variation_2 or variation_3 are availiable in Product. For this a need request Product.id to def clean_variations_select(self): How to do this? def clean_variations_select(self): product = Product.object.get(id = product.id) variations_select = self.cleaned_data.get("variations_select") if variations_select == "Variation_1" and product.variation_1 == False: raise forms.ValidationError("variation_1 was sold already") else: return variations_select product = Product.object.get(id = product.id) - don't work cause Order isn't created to database yet(but in rendering view link to new order creation i have that ../product.id/new_order). -
How to write a raw SQL query in Django QuerySet?
I want to use following SQL query in Django but I was unable to use that after trying directly with raw SQL. The SQL works directly while executing on PostgreeSQL query window but on Django did not work. The SQL is to find immediate lower value before a number 22522. I would like to use that in QuerySet format or in raw SQL. Added SQL query below- SELECT id, name, zip FROM region WHERE zip>=(SELECT max(zip) FROM region WHERE zip<22522) AND zip<=(SELECT min(zip) FROM region WHERE zip>22522) ORDER BY zip ASC LIMIT 1 Here is the code which I tried to use in raw query format. I saw, any other simple SQL query inside the c.execute() print result data correctly. from django.db import connection with connection.cursor() as c: c.execute("SELECT id, name, zip FROM region WHERE zip>=(SELECT max(zip) FROM region WHERE zip<22522) AND zip<=(SELECT min(zip) FROM region WHERE zip>22522) ORDER BY zip ASC LIMIT 1") for row in c.fetchall(): print(row[1])