Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter a django ManyToManyField to match all in a list
If I have a ManyToManyField in my Django model, for example: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) How can I filter a queryset of Articles to include only those articles that have publications that exactly match a specific list (or queryset) of Publications? For example, if I wanted only articles that appeared in ALL publications: pubs = Publication.objects.all() Article.objects.filter(publications__exact=pubs) This seems to use an OR condition on pubs rather than AND, and articles that appear in any one pub is included rather than those that appear in ALL of the pubs. -
Django 2.0 + django-allauth: RelatedObjectDoesNotExist at /account/edit/ (User has no profile)
I'm making a Django WebApp that allows registration and login using a form and social authentication through django-allauth. Registration through form is working perfectly. You can check out the whole project on https://github.com/ralfillo/social_django_website When a user is created with allauth (Facebook account), login works but when I want to edit the user's account Django throws this error: RelatedObjectDoesNotExist at /account/edit/ User has no profile. Request Method: GET Request URL: https://development.com:8000/account/edit/ Django Version: 2.0.4 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no profile. On the console: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no profile. The account app models.py looks like this: from django.conf import settings from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return 'Profile for user {}'.format(self.user.username) Part of views.py: from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect #----- from .forms import LoginForm, UserRegistrationForm, UserEditForm, ProfileEditForm from .models import Profile @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Profile updated successfully') else: messages.error(request, 'Error updating your profile') … -
Django adding item to many-to-many relationships
I'm new to django thus the question. I've the following Feed object and an User object which have a many-to-many relationship class Feed(Base): headline = models.CharField(max_length=255) link = models.CharField(max_length=255) summary = models.TextField() reader = models.ManyToManyField(User, through='Bookmark') class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=True, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) The two are related using the Bookmark object. class Bookmark(Base): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) feed = models.ForeignKey(Feed, on_delete=models.CASCADE, null=True) My question is how do I add a bookmark(or rather feed) to the user? Any help appreciated. -
How do I save a form with CreateView
I have a CreateView and inside this CreateView there is a form_valid() function. It gets the user_id and assigns it to the user that's logged in user id. The user is basically creating their own question and user_id is a foreign key. class QuestionCreate(LoginRequiredMixin, CreateView): model = Questions form_class = CreatePost def form_valid(self, form): form.instance.user_id = self.request.user.id return redirect("oauth:profile", username=self.request.user) When I go to the URL of this view, I can see the view and when I try to submit a question it redirects me to the profile. However, the question is not saved in the database. I've tried inserting form.save() below the first line in form_valid and it does get saved in the table correctly, however, I don't get redirected to the profile, instead I get an error that states connection error what am I doing wrong? -
simple search box in django
I'm trying to create a very simple search function which would filter by a key word given into search form. html search form: <form method="get" action="{{ request.get.q }}"> <input type="search" type="text" name="q" placeholder=„search"> <button type="submit">search</button> </form> views.py: def search(request): query = request.GET.get(q) if query: results = Sklep.objects.filter(miasto=query) if results.count(): context_dict['results'] = results else: context_dict['no_results'] = query return render(request, "apka/lista.html", context_dict) div to display results: <div> {% if no_results %} No results returned for <q>{{ no_results }}</q> {% else %} {% for result in results %} {{ result.miasto }} {% endfor %} {% endif %} </div> and finally models.py: from django.db import models class Sklep(models.Model): miasto = models.CharField( max_length=200, ) nazwa = models.CharField( max_length=200, ) adres = models.CharField( max_length=200, ) def __str__(self): return self.miasto +", "+ self.nazwa+", "+self.adres` Template seems to not show any results, neither "no results..." nor any filtered entries. What am I doing wrong? -
ID of dynamically added formset forms in django templates
This may be a silly question, but: When rendering forms in a formset in a django template, one has to render the ID's as well. This I get. When I dynamically create a new form in the formset with JS, I have to again create a hidden ID field. But what value do I give this ID? The template doesn't know what ID's are available. And without a proper ID, the formset wont pass validation back at the server. Any Ideas? -
filter in ascending order in Python/django
I am trying to run a filter in Python/django. All the data is coming from DB. This query currently works but I want to able show it in ascending order of Name first and Description after. Any assistance would be helpful. query = request.GET.get('q') if query: data = Data.objects.filter(Q(name__icontains=query) | Q(description_icontains=query)).distinct() -
How can I add Bootstrap 4 to the library django-summernote?
I need add Bootstrap 4 to django-summernote. It's possible? -
Django runserver on Docker does not respond when opened in the browser
I am just a beginner at this So when I run sudo docker-compose run web python manage.py runserver it shows Starting thirddj_db_1 ... done usr/local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) /usr/local/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Performing system checks... System check identified no issues (0 silenced). April 11, 2018 - 19:15:59 Django version 1.11.12, using settings 'composeexample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. And then when I opened it in my browser, it shows the site cant be reached But when i run docker-compose up it shows web_1 | /usr/local/lib/python3.6/site- packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary- install-from-pypi>. web_1 | """) web_1 | /usr/local/lib/python3.6/site- packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip … -
Django clean: Split chunks of TemporaryFileUploadHandler into lines
During the upload of a file I need to split its contents in lines, count the characters of each line and raise and error if they exceed a certain length. def clean_upload_file(self): the_file = self.cleaned_data.get('upload_file') if the_file: for chunk in upload_file.chunks(): # the file is huge import ipdb; ipdb.set_trace() The the_file is opened in rb+ mode. Its contents are: >>>print(chunk) b' counterproductive\nbishop\nsa raindrop\nsangu' >>>print(the_file.mode) 'rb+' It is obvious that the end of the byte is the beginning of a new line that will continue in the next iteration. >>>print(chunk.splitlines()) [b' counterproductive', b'bishop', b'sa raindrop', b'sangu'] The above method will not help in telling whether the last entry is an entire line or not. On the other hand, \n is not guaranteed to be a line separator for every uploaded file in binary mode. How can I distinguish whether the last entry of the list represents the end of a line or just the first part of it? -
input bootstrap JavaScript and CSS in Django
I have my bootstrap files in the static folder in Django but I think Js is not imported because there are no javascript effects working here is the code i used to import CSS and js : {% load staticfiles %} <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type="text/css"> <script src ="{% static 'js/bootstrap.min.js' %}"></script> everything is perfectly styled but no script works at all, is this the right way to get the JS files into my HTML doc? -
my send email django doesn't work
i'm trying to send email for password_reset. i tried every single way i found to send_email in django: urls.py from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView ) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index, name='index'), url(r'^password_reset/$', PasswordResetView.as_view( template_name='registration/password_reset_form.html'), name='password_reset'), url(r'^password_reset/done/$', PasswordResetDoneView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z] {1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), url(r'^reset/done/$', PasswordResetCompleteView.as_view( template_name='registration/password_reset_complete.html'), name='password_reset_complete'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 1) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' this this works fine but i need but i need it in production. 2) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS= True EMAIl_HOST= 'smtp.gmail.com' EMAIL_PORT= 587 EMAIL_HOST_USER= 'myemail@exmaple.com' EMAIL_HOST_PASSWORD='mypassword' this way returns STARTTLS extension not supported by server. and changing(i see this in other people issues answers): EMAIL_USE_TLS= True to: EMAIL_USE_TLS= False return this error: SMTP AUTH extension not supported by server. 3) AWS_ACCESS_KEY_ID = 'myaccesskeyid' AWS_SECRET_ACCESS_KEY = 'mysecretaccesskey' AWS_SES_REGION_NAME = 'us-east-2' AWS_SES_REGION_ENDPOINT = 'myip.us-east- 2.compute.amazonaws.com' -i tried with ses-aws too and apparently works but the email never arrives 4) python manage.py shell from django.core.mail import send_mail send_mail('test email', 'hello world', to=['test@email.com']) this return: 1 - i use this just to know if the email is coming out please if someone can tell me what i'm doing wrong. I've been trying for several days. -
Django User Authentication Selenium
I am using selenium to test a working application written in Django. The vast majority of the sites function is visible only after succesful user authentication using the standard Django user.auth However, after I login in the selenium FireFox window, my assertions in the test script do not appear to be detecting the changes in the pages seen after login. the test.py file is as follows: from django.test import TestCase from django.contrib.staticfiles.testing import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class FunctionalTests(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def tearDown(self): pass def test_landing_visible(self): self.driver.get('http://localhost:8000') assert "Stat59" in self.driver.title def test_login(self): self.driver.get('http://localhost:8000/accounts/login') username = self.driver.find_element_by_id("id_username") password = self.driver.find_element_by_id("id_password") username.send_keys("simurate_test") password.send_keys("PASSWORD") password.send_keys(Keys.RETURN) #Elements Visible Before Login assert "Account Management" in self.driver.page_source #Elements Visible After Login assert "simurate" in self.driver.page_source if __name__ == '__main__': unittest.main(warnings='ignore') The screen before login (/localhost:8000/accounts/login) appears as such (containing the text "Account Management": Login Screen The screen after login appears as such. This is the last screen shown in the firefox browser brought up by selenium. It clearly shows that the login process was successful and the page contains the text "simurate" Projects Page The results of the test script are: (venv3) dino@naomi:/var/www/htdjango/stat59/simurate$ python tests.py … -
Know in Django Admin is is create or an update
In Django Admin I modify the foreign key by overriding def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "account": kwargs["queryset"] = Account.objects.active_type_as().exclude(id__in=list) return super().formfield_for_foreignkey(db_field, request, **kwargs) This is working when I create the Instance, but I need a different queryset when I update, because I need to take in consideration what is selected. How do I know at this moment, if is create or update ? -
Are there any options to use a custom form in Django Admin and keep fieldsets?
Are there any options to use a custom form in Django Admin and keep fieldsets settings ? -
Django ChoiceField Returns Select a Valid Choice Error in Class Based View
I am pulling my hair out over this...all other SO questions relate to ModelChoiceField and that is not what I need. So I have a lookup table in a SQL database that contains an ID and a keyword. This table is NOT UNIQUE meaning keywords can be duplicated but IDs are still unique. This means I cannot use ModelChoiceField since I want to populate it with unique keywords and using it will result in returning duplicated keywords. Thus, I tried using ChoiceField and instantiating the choices in my class form as so: def unique_values(): return keyword.objects.order_by('keyword').values_list('keyword', 'keyword').distinct() class CustomForm(forms.Form): keywords = forms.ChoiceField(choices=unique_values, widget=Select2MultipleWidget) This works in populating the dropdown list form in my Class Based view. but when I select and submit the form, I get the result: Select a valid choice. ['(*INSERT KEYWORD NAME*)'] is not one of the available choices.. How do I get around this? -
How to add Icons in Django forms
So I wanted to add icons of font-awesome inside the input boxes which are rendered by django, but found no way to do so. The input boxes are provided by the django via {{form.username}} type of fields, and the output is like <input type="text" name="username" id="id_username" required placeholder="Username" maxlength="32" /> I achieved placeholder via the django widgets such as username = forms.CharField( required = True, label = 'Username', max_length = 32, widget=forms.TextInput( attrs={'placeholder':'Username'}, ), ) I would like to know how to place icons there too just like the image shown who's code is shown here <input placeholder="First Name" name="Name" class="name" type="text" required=""> <span class="icon1"><i class="fa fa-user" aria-hidden="true"></i></span> Thanks in advance. -
How do I change how a CharField is displayed?
I have a model defined as such in my models.py file: class Tutor(models.Model): FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Email = models.EmailField(max_length=100) PhoneNumber = models.CharField(max_length=10) RequestedHours = models.DecimalField(max_digits=3, decimal_places=1) def __str__(self): return str(self.FirstName + " " + self.LastName) I want to create a page that displays all of this information in a table that is easy to read quickly. I have managed to do so for the most part, but I have always found 10-digit phone numbers to be more difficult to read without separators. Currently, the display output looks like this: table output of Tutor model And the code for the table looks like this: <div class="table-background"> <table class="table table-striped table-bordered table-hover"> <thead> <tr class="bg-info"> <th colspan="2">Tutor</th> </tr> </thead> <tbody> <tr> <th>First Name</th> <th>Last Name</th> </tr> <tr> <td>{{ tutor.FirstName }}</td> <td>{{ tutor.LastName }}</td> </tr> <tr> <th>Email</th> <th> Phone Number</th> </tr> <tr> <td>{{ tutor.Email }}</td> <td>{{ tutor.PhoneNumber }}</td> </tr> <tr> <th colspan="2">Requested Hours</th> </tr> <tr> <td colspan="2">{{ tutor.RequestedHours }}</td> </tr> </tbody> </table> Is there any way for me to modify the output of the CharField 'PhoneNumber' so that I can get it to display as 000-000-0000? -
Can't override value when saving
I have a Django/Wagtail project. I want to keep the original value of a field (CharField) even when the user tries to enter a new one. I'm trying by doing this: On __init__ I store in self._shorturl the original value of self.shorturl, the one that exists when starting to edit: def __init__(self, *args, **kwargs): super(ArticlePage, self).__init__(*args, **kwargs) self._shorturl = self.shorturl This stores the value correctly, doesn't seem to be the issue. And then on save I do: def save(self, *args, **kwargs): if self._shorturl and len(self._shorturl)>0: self.shorturl = self._shorturl super(ArticlePage, self).save(*args, **kwargs) I expect this to override whatever the user entered with the original value. At the time of execution of save() the values are correct for both variables. However after saving, the new value is saved to the DB instead of keeping (saving again, actually) the original. I'm basically trying to avoid the user to be able to update this particular field if it has a value already. What am I doing wrong? Is there a more elegant way to do this? -
Retrieving HttpRequest in Django Rest Framework View
Django Rest Frame work states "Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition." I am trying to track user data with Django Tracking Analyzer, however one of the requirements is a django.http.HttpRequest instance. Is there a way to override a DRF view .initialize_request to retrieve the original HttpRequest? -
Django: Inline User for different Userprofile
I have my CustomUser model and two differents models (Profile, Client) with OneToOne fields to CustomUser. Depending on the choice of the user in the registration form, one of the models is created. I'm looking for a way to add a link to Customuser in every inline user model. customuser.models: class User(AbstractUser): username = None email = models.EmailField(unique=True) phone = models.CharField( max_length=17) is_trainer = models.BooleanField(default=False) is_client = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone'] objects = UserManager() profile.models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', parent_link=True) .... client.models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client', parent_link=True) .... I try this code at admin.py one of my models: from django.contrib import admin from client.models import Client from customuser.models import User class InlineUser(admin.StackedInline): model = User class ClientAdmin(admin.ModelAdmin): prepopulated_fields = {"slug":("name",)} list_display = ('id','name') list_display_links = ['id'] inlines = [InlineUser] admin.site.register(Client, ClientAdmin) And error is occurred ERRORS: <class 'client.admin.InlineUser'>: (admin.E202) 'customuser.User' has no ForeignKey to 'client.Client'. I tried to find suitable examples, but could not get the desired result. -
How to specify a settings module when using the Django database shell command?
I'm trying to run the Django admin's dbshell command, but I'm having trouble specifying the settings module. If I try to run it without defining any environment variable, I get an ImproperlyConfigured error suggesting I define a DJANGO_SETTINGS_MODULE: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ django-admin dbshell Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute saved_locale = translation.get_language() File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language return _trans.get_language() File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My settings are located in lucy/settings/development.py, which I can import in a shell: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: import lucy.settings.development In [2]: However, if I try to re-run the dbshell … -
Is it possible to use bootstrap themes on a Mezzanine/Cartridge website?
I am a newbie web developer tasked with creating a website for a client in the art industry. I've decided to roll with Mezzanine + Cartridge for the project as it seems like an accessible way to get started. I now have the server up and running with no issues, but obviously can't use the default Mezzanine theme for such a project. I'm finding that theres a highly limited amount of themes available online for Mezzanine, and that there are a lot more Bootstrap themes available floating around. Is there a way I could use the two together? Ie the UI/front end being a Bootstrap theme while still maintaining the functionality of Mezz/Cartridge? If so, how would I go about doing this? Not expecting a step by step guide, but any advice/guidance would be highly appreciated. Like I said, I'm incredibly new to this (first website ever!) so if I'm misunderstanding something, please let me know. Thank you for your time. -
csv file turkish characters not showing
I am importing csv file to django model with below commands: if request.method == 'POST' and request.FILES['csv_file2']: myfile = request.FILES['csv_file2'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) The problem that I am having that I can't see turkish characters. I searched at stackoverflow and I need to add utf-8 encoding while reading the csv file ,I tried several examples that I found but I couldn't make it work anywhere I tried to add encoding in my codes. Where should I add ? -
Why do django queries to hot standby go slower than from master?
I have two servers, running postgres, setup to be master/replicator using hot standby. When I make queries using django on the master server the queries take roughly half the time that the same queries on the replicated server take. The servers are identical except that one is running a read/write database supplying WAL files and the other is running a read only database replicating from the WAL files. If I make the queries on the replicated server to master the queries resolve twice as fast as they do if I make the queries directly to the local database. Why is this?