Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't change main Django project settings file
I was trying to configure the Django Database Settings to use mysql. I followed the instructions provided here I started a Django project within the myproject directory. django-admin.py startproject myproject . I tried to open the main Django project settings file nano ~/myproject/myproject/settings.py And the terminal did not display a DATABASES section at the bottom of this file. Instead I had ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text^T To Spell What do you recommend? I need to change this settings file to use mysql database.I have Ubuntu 14.04. and python 3.4. installed. -
Django - Getting AttributeError 'User' object has no attribute 'cleaned_data' while cleaning form data
I was trying to make a user registration page in Django. everything went fine. but when I submit the form data I get this below error AttributeError 'User' object has no attribute 'cleaned_data' Image of that AttributeError I searched on stackoverflow and found that the object.cleanded_data should be placed after object.is_valid() else one should face the AttributeError. But I placed that after checking is_valid() still getting error. my codes: views.py class UserFormView(View): form_class = UserForm template_name = "music/registration_form.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = user.cleaned_data["username"] password = user.cleaned_data["password"] user.set_password(password) user.username = username user.save() user = authenticate(username= username, password= password) if user is not None: if user.is_active: login(request, user) return redirect("music:index") return render(request, self.template_name, {"form": form}) forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] I cant find where I made mistake. -
Adding fields to table dynamically in django
After reading about database designs, i've decided to go with a single table for all users. my question is how can i create fields for new users to add their data into it? also what's a good approach for retrieving data specific to each user? I appreciate any advise regarding this subject. -
can not connect module django-AB-project
I installed the library itself, added in INSTALLED_APPS = [ 'ab' ] But for some reason I get an error if I'm making a migration: ModuleNotFoundError: No module named 'ab' I use django==1.11 -
How can I calculate time from model object created time?
models.py @python_2_unicode_compatible class UserAuthToken(models.Model): email = models.ForeignKey(UserSubEmail) token = models.CharField(max_length=34, unique=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "AuthToken for %s" % self.email I want to check elapsed time between token's created time and now So if token created before more than 10 minutes, I can recognize this token is invalid. views.py def create_email_confirm_key(request, uid, token): try: user_authtoken = UserAuthToken.objects.get(uid=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user_authtoken = None if not 'user_authtoken is created before more than 10minutes' : This token is valid and do something How can I calculate and check time between the token created and now? -
Send Python Data on Django
I have informations generated by a Python Script and I'd like to recovering this datas on Django. Simplifying: Python Script: extract information from log system Django: Web View - Is how I would like to show this informations to my user. Does Django has any features to it that or I need to create a webservice, because, one I am not familiarized with this Framework, I would send this data on to PHP using WEBService. -
Django SQL query duplicated 2 times
Model.py: class Match(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) class Stat(models.Model): match = models.ForeignKey(Match) team = models.CharField(max_length=100) goals = models.IntegerField(default=0) assists = models.IntegerField(default=0) views.py context_dict = {} match = Match.objects.get(pk=1) home_stat = Stat.objects.get(match=match, team=match.home_team) away_stat = Stat.objects.get(match=match, team=match.away_team) context_dict['home_stat'] = home_stat context_dict['away_stat'] = away_stat return render(request, 'index.html', context_dict) template goals: {{ home_stat.goals }} : {{ away_stat.goals }} assists: {{ home_stat.assists }} : {{ away_stat.assists }} django-debug-toolbar shows two duplicated queries: https://sfault-image.b0.upaiyun.com/220/984/2209840587-5a3e5ccccec87_articlex SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamA''') Duplicated 2 times. F:\myproject\myapp/views.py in index(11) home_stat = Stat.objects.get(match=match, team=match.home_team) SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamB''') Duplicated 2 times. F:\myproject\myapp/views.py in index(12) away_stat = Stat.objects.get(match=match, team=match.away_team) how to fix this? -
Django RegexValidator pattern for ZZ-99-ZZ-9999
Trying to make a regex pattern in pattern ZZ-99-ZZ-9999 (2 capital character-2 numbers-2 capital character-4 numbers) bus_number_regex = RegexValidator(regex=r'^\W{2}-?1?\d{2}-?1?\W{2}-?1?\d{4}$',message="Bus number must be entered in the format: 'ZZ-99-ZZ-9999'"." ZZ must be in Capital.") -
How can I run function asynchronously to make calculation parallelly on Heroku with Django app?
I have to run function 500 times with different arguments on Heroku in my Django app at a specific time. I need to do it in the shortest period of time. I noticed that when I use Heroku Scheduler every task is running parallelly and asynchronously and each of them has own worker. So for example 10 functions ran in this way will calculate results as there would be only 1 ran function. As I have mentioned I need to run 500 function with different arguments. I could create 500 Heroku schedulers and ran it separately but it seems to me that it's not supported by Heroku or maybe I am wrong? If so maybe someone know how it could be solved in another way? -
cant deploy django to ehost shared cpanel
i have a hosting package on ehost.com and i am trying to deploy a django application on it and i am having many problems first was that the django version i used is 2 and the pip version on ehost servers is with python 2.7 which is not compatible with django 2 then when trying to deploy a django 1.11 app which is compatible with python2.7 i followed all the instructions in the ehost django with fast cgi guide and the server doesnt execute the index.fcgi file it just returns the text in the file and the website support concerning these issues are not really helping -
Django ORM - Filter by GenericRelation across multiple models
Filtering on Django GenericRelations has been implemented 4 years ago via https://code.djangoproject.com/ticket/22207 and supports now to filter from the related model: class Issue(models.Model): project_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=False, null=True) project_id = models.PositiveIntegerField(blank=False, null=True) project = GenericForeignKey('project_content_type', 'project_id') class GitlabProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) and then: issues = queryset.filter(generic_project__offers__members__in=[request.user]) We cannot use just project__offers_members - it would fail, as Django does not reversely resolve Generic Foreign Keys. However what happens if we have another project model with the same related_query_name? class JiraProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) I have tried setting the GenericRelation with the same related_query_name on all the different project models (i.e. Gitlab Project, Jira Project, etc.). However that results in Django picking up only the 'first' project model. The generic relation to all subsequent project models are ignored and as a result, issues that have instances set that do not belong to the 'first' project model are ignored and not part of the queryset. I think Django should either support this or issue a warning or error (possibly when executing the makemigrations command), when multiple GenericRelations have the same related_query_name value set. How can one filter efficiently across issues that have … -
Temporary views are not supported in CouchDB
I'm building a web app using Django and couchdb 2.0. The new version of couchdb doesn't support Temporary views. They recommend using Mongo query but I couldn't find any useful documentation. What is the best approach or library to use couchdb 2.0 with Django? -
Access via ForeignKey to the image field of parrent model in QuerrySet [Django]
I have this simplified model.py: class Product(models.Model): name = models.CharField() description = models.CharField() class ProductImage(models.Model): product = models.ForeignKey(Product,) photo = models.ImageField(upload_to="product_images/") is_main = models.BooleanField(default=False) An Product can have many ProductImage, but only ProductImage which has field is_main=True shall be rendered in a template together with all field of Product. The following data set from the views.py: products = Product.objects.all() So now I would want to do something like this in the template: {% for product in products %} <img class="card-img-top" src="{{ product.productimage_set.filter(is_main=True).photo }}" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">{{ product.name }}</h4> <p class="card-text">{{ product.description }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> But obviously that's not possible. Not from the template directly, at least. What is the proper way to get all the fields of Product and its image with attribute is_main=True inside the template? -
Django upload video with automatic thumbnails generation
I want to upload mp4 and mov videos to my django website with automatic thumbnail generation. Thumbnails can be jpg or png that will save in ImageField and video to FileField. thumbnail = models.ImageField() video = models.FileField() I am using Python 3.6.3, Django 1.11.8 and dropzone. Please suggest me how to create a video upload page similar to youtube. Is there any opensource plugin available to achieve this ? -
Django newbie, struggling to understand how to implement a custom queryset
So I'm pretty new to Django, I started playing yesterday and have been playing with the standard polls tutorial. Context I'd like to be able to filter the active questions based on the results of a custom method (in this case it is the Question.is_open() method (fig1 below). The problem as I understand it When I try and access only the active questions using a filter like questions.objects.filter(is_open=true) it fails. If I understand correctly this relies on a queryset exposed via a model manager which can only filter based on records within the sql database. My questions 1) Am I approaching this problem in most pythonic/django/dry way ? Should I be exposing these methods by subclassing the models.Manager and generating a custom queryset ? (that appears to be the consensus online). 2) If I should be using a manager subclass with a custom queryset, i'm not sure what the code would look like. For example, should I be using sql via a cursor.execute (as per the documentation here, which seems very low level) ? Or is there a better, higher level way of achieving this in django itself ? I'd appreciate any insights into how to approach this. Thanks Matt … -
Resolved url function not equal to class based view `as_view()` method?
I have the following test: def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual( found.func, views.HomePageView.as_view() ) gives this error: AssertionError: <function HomePageView at 0x107d65620> != <function HomePageView at 0x107d97400> -
How correctly to set up autocomplete_fields?
Trying to set up autocomplete_fields for ForeingKey in Django admin. I don't understand how correctly to set it up. I read the docs but there is not much information about autocomplete_fields, not enough for me at least. admin.py class AdminSettings(admin.ModelAdmin): filter_horizontal = ('english_word', 'russian_word', 'turkish_word') list_display = ['circassian_word', 'letter'] autocomplete_fields = ('circassian_word',) search_fields = ['circassian_word__circassian'] models.py class Word(models.Model): circassian_word = models.ForeignKey(Circassian, blank=True, null=True, on_delete=models.CASCADE, verbose_name='Адыгэбзэ') letter = models.ForeignKey(Alphabet, null=True, on_delete=models.CASCADE, verbose_name='Буква') audio = models.FileField(upload_to='audio', blank=True, verbose_name='Озвучка') turkish_word = models.ManyToManyField(Turkish, blank=True, verbose_name='Türkçe') english_word = models.ManyToManyField(English, blank=True, verbose_name='English') russian_word = models.ManyToManyField(Russian, blank=True, verbose_name='Русский') Error message Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10d07b9d8> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 410, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'psalale.admin.AdminSettings'>: (admin.E037) The value of 'autocomplete_fields[0]' refers to 'circassian_word__circassian', which is not an attribute of 'psalale.Word'. System check identified 1 issue (0 silenced). -
i am using django forms , how would i create 2 dropdown such that the entry selected in first is not displayed in second
i am working on a Django project , i have a list of hostels to be displayed in 2 drop down , it should be such that the hostel selected in first is not displayed in second , how would i achieve this ? -
Can not install django via Ubuntu bash on windows
happy holidays to you :) I can not install the Django package by the python pip package manager. The installation returns an error that you can see below on the image If you want more pictures to help me, let me know Windows 10 - Ubuntu terminal Thank you, simply -
Django query set based on user subscription plan
So I'm trying to build a web app, the idea is I have data about homes all over the US, and I don't want to show all data to users, user will pay a monthly price (like a plan) based on number of states he selected when he subscribed, So How can I make my models, user models and views so that he can only see data within the states he selected ? and how can I represent these subscription plans as a model in my db ? a small hint can make difference, so please give it if you don't have time to explain with example. Thank you. -
Django Doesn't Send Email Notifications
Merry Christmas to everybody, Working on a contact form and i am not able to receive the emails from Django into my Inbox. This is my function: def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): contact_name = form.cleaned_data['contact_name'] contact_phone = form.cleaned_data['contact_phone'] contact_period = form.cleaned_data['contact_period'] subject = contact_name + " | " + contact_phone + " | " + contact_period content = form.cleaned_data['content'] contact_email = form.cleaned_data['contact_email'] try: send_mail(subject,content,contact_email, ['office@cohen.ro']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "contact.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') These are my server's settings: Secure SSL/TLS Settings (Recommended) Username: office@cohen.ro Password: Use the email account’s password. Incoming Server: mail.cohen.ro IMAP Port: 993 POP3 Port: 995 Outgoing Server: mail.cohen.ro SMTP Port: 465 This is what i have in my Django settings: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'office@cohen.ro' EMAIL_HOST= 'mail.cohen.ro' EMAIL_HOST_USER= 'office@cohen.ro' EMAIl_HOST_PASSWORD='mypass' EMAIL_PORT = 465 EMAIL_USE_TLS = True In my server i can see the message, but does not send the email to my email address so i dont know if someone is asking me something. Thank you! Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: me | 0787877 | 12-13 From: test@test.com … -
about javascript _.each in django template
home-templateviews.jsIt seems that _.each does not work properly because there's no sprint items on page. And I guess it's sprints.models that leads to the problem. I can not figure out if sprints.models is list object. Please help me solve it. Thanks. -
Changing from standard sqlite to postgres database
I'm trying to change from the standard sqlite database to postgresql in my Django project. Here's what I've done so far: Installed postgresql Created a database and a user with privileges for writing to it Changing the database setting in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'workout', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } Then, when I try to migrate, this happens (warning for long error trace): (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying workoutcal.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying sessions.0001_initial... OK Applying workoutcal.0002_auto_20171215_1102... OK Applying workoutcal.0003_auto_20171215_1153...Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: multiple default values specified for column "id" of table "workoutcal_user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Django: ManyToMany field between multiple applications
Not a long ago I have followed model: at the url /catalog1 I have application what looks like catalog with items, it have groups what have ManyToMany field to items (located at /catalog1/group, but all that inside one application. Now: I have another application /catalog2, it different but it should also have same groups, I decide to move groups on one level above (/groups instead /catalog_name/group) and I need to make ManyToMany relations to items in both catalogs. What can you suggest to me? Should I move them to different application called just Group? And how can I make relation to both catalogs? Model from current groups: class Group(models.Model): # fields for group class Item(models.Model): # other fields... groups = models.ManyToManyField(Group, related_name="groups", blank=True) Urlpattern in application: url(r'^(?:(?P<item_id>[\d]+)|(?P<item_name>[\w\d_+\-]+))/$', views.item, name='item'), url(r'^group/(?:(?P<group_id>[\d.]+)|(?P<group_name>[\w\d_+\-]+))/$', views.group, name='group'), Newer urlpattern will be without relation to catalog, so probably if it will be different application (/groups), it will look then: url(r'^(?:(?P<group_id>[\d.]+)|(?P<group_name>[\w\d_+\-]+))/$', views.group, name='group'), -
Media directory in production not working
The media directory is working as expected in my local machine but when i push the code to Heruko or cloud foundry the media is not working. How to rectify this issue? Thanks & Regards, Mohamed naveen