Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CreateView works fine, UpdateView leads to 405 "page not working"
I'm learning class based views in Django, my CreateView loads the form correctly and when submit is clicked it redirects to the detail page of the new object created; UpdateView does the same but when submit is clicked it gets me an error 405. It seems a common problem, I found different solutions on similar questions here but none is working for me. I'm stuck from a couple of days so any hint is really appreciated. Since I'm learning I would like to have some explanation about why this occours rather than some code I have to copy/paste. Thanks all. #my urls.py app_name = 'articles' urlpatterns = [ path('', ArticleListView.as_view(), name='article-list'), path('create/', ArticleCreateView.as_view(), name='article-create'), path('<int:id>/update', ArticleUpdateView.as_view(), name='article-update'), path('<int:id>/', ArticleDetailView.as_view(), name='article-detail') #models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.CharField(max_length=255) def get_absolute_url(self): return reverse("articles:article-detail", kwargs={"id": self.id}) # relevant part of views.py class ArticleCreateView(CreateView): template_name = 'blog/article_create.html' form_class = ArticleForm queryset = Article.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) class ArticleUpdateView(UpdateView): template_name = 'blog/article_create.html' form_class = ArticleForm queryset = Article.objects.all() def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Article, id=id_) def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) <form action="." method="POST"> {% csrf_token %} {{form.as_p }} <input type="submit" value="Save" /> </form> -
django filter by nested foreign key
Souupose I have two models like below: class ProductType(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', related_name='children', bland=True, null=True) class Product(models.Model): name = models.CharField(max_length=50) product_type = models.ForeignKey(ProductType) Now I have ProductType hierarchy like this: Electronics->MobilePhone->Samsung->[galaxy, s10, s8] Electronics->MobilePhone->Apple->[Iphone, Ipad, Ipod] Now how can I filter Product model to get all the Products where ProductType=MobilePhones ? -
how to refelct the variable used in making an instance from an object in its name?
I have this model in django: class Level(Model): level = CharField(...) I build some instances from this model: [Level.objects.create(level='Grade {}'.format(i)) for i in range(1, 13)] as a result, I have 12 instances. For example: grade_11 = Level.objects.get(level='Grade 11') What I want to do is that I build all grade_1 to grade_12 in one line. I know it is called introspection or reflection in python but I do not know how to it. I tried this but it was not successful: ['grade_{}'.format(i) = ProgramLevel.objects.get(program_level='Grade {}'.format(i)) for i in range(1, 13)] -
How do you know what status code to test for?
I am learning Django from a book which doesn't really explain the status codes very well when testing, i understand that a successful/accepted request gives a status code of 200, but i cant get my head around how you would know which one to expect when testing? For example: def test_post_update_view(self): response = self.client.post(reverse('post_edit', args='1'), { 'title': 'Updated title', 'body': 'Updated text', }) self.assertEqual(response.status_code, 302) def test_post_delete_view(self): response = self.client.get(reverse('post_delete', args='1')) self.assertEqual(response.status_code, 200) i am following along making a blog website from the book testing the different views, but when testing the UpdateView test we checked for a 302 but on the DeleteView we checked for a 200, why do we not expect a 302 with the DeleteView? -
How to inspect db in django2.1 with postgresql?
hi when i run python3 manage.py inspectdb it will return following error # The error was: sequence index must be integer, not 'slice' same python3 manage.py inspectdb working on sqlite when i use postgresql it will return error # Unable to inspect table 'zip_code' # The error was: sequence index must be integer, not 'slice' -
Fonts not working after using DO Spaces for Django project
I've followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-object-storage-with-django Everything works except for fonts used in .css files (they are actually loaded by a browser) and some images. Settings are as in tutorial: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' But when I change the settings back to this, fonts are working: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Note it's not in production. I'm running it on localhost. -
How to add more fields in the django admin panel's "add user" section?
I am using Django 2.2 for building a private project.I am learning django advanced things like customizing admin panel, customizing user model and many more things. I have created my own user model with extra fields including Profile Picture, Mobile Number etc. In the admin-panel of django there is button named "Add User" and "add User" only contains UserName,Password and Password Confirmation Field.I want to add First Name, Last Name, Email, Mobile Number there. http://127.0.0.1:8000/admin/accounts/user/ Here there is a button named "Add user" and there is only Username,Password and confirm password.I want to add more fields there. And I want to add another button named "Create Admin" which can create Admin Is there any proper ways to do that? -
making ajax button with django-secretballot and intercooler.js
I'm making a vote up button using django-secretballot and django-likes and i want to use intercooler.js to make the ajax call and don't reload the whole page. The problem is when i click on the vote button the element contain the ( vote_total ) disappear and nothing happen but if i reload the page the vote happen image 1 : the button without click image 2 : the button after i click image 3 : the button after i reload the page this is "likes.html" template on django-likes app {% load i18n %} {% load static %} {% if import_js %} <script type="text/javascript" src="{% static 'likes/includes/likes.js' %}"></script> <script src="{% static 'intercoolerjs/js/jquery.js' %}"></script> <script src="{% static 'intercoolerjs/js/intercooler.min.js' %}"></script> {% endif %} {% if likes_enabled %} {% if can_vote %} <a class="liker vote rounded" ic-get-from="{% url 'like' content_type content_obj.id 1 %}" ic-target="#wrapper" ic-select-from-response="#wrapper" rel="nofollow"> <svg width="10" height="9" viewBox="0 0 9 8" xmlns="http://www.w3.org/2000/svg" class="upvoteIcon_f942d"><path d="M9 8H0l4.5-8L9 8z" fill-rule="evenodd"></path></svg> <span id="wrapper" class="number" style="display: inline-block"> <div id="target"> {{content_obj.vote_total }} </div> </span> </a> {% else %} <a class="vote liked rounded"> <svg width="10" height="9" viewBox="0 0 9 8" xmlns="http://www.w3.org/2000/svg" class="upvoteIcon_f942d"><path d="M9 8H0l4.5-8L9 8z" fill-rule="evenodd"></path></svg> <span class="number"> {{content_obj.vote_total }} </span> </a> {% endif %} {% endif %} Note … -
django template iterated list: how create unique overlay-popup for each item?
In django easy to generate an iterated list of titles from context received by template: {% for instance in object_list %} <li>{{instance.international_title}} </li> {% endfor %} And in css easy to create a popup overlay: #overlay { height:300px; width:300px; margin:0 auto; position:relative; z-index:10; display:none; border:5px solid #cccccc; border-radius:10px; } <div align="center"> <a href="#overlay"> Click Title for Detail</a> </div> <div id="overlay"> <p> Here is the text giving more detail<p> </div> Would like to be able to associate a unique text with each unique title {{instance.international_short_description}} for the purposes of the overlay popup. However do not see how to do this. Is it necessary to somehow create a series of css classes: #overlay1, #overlay2 with custom href to each one? Is it possible to use a single class and then pass a variable to it to then select the correct text? Have not been able to find examples. -
How to enable user self signup in django admin?
I am using Django admin for creating a simple user management portal. Is it possible for users to sign up using their email on Django admin? Currently someone has to login to the admin interface and then create a user. I tried searching for examples, but all the results are that regular user signup, without django admin -
Django(Python) registration doesnt work correctly
I am trying to write right registration for my online store with confirmation via mail. Registration passes once a time, but after I click on "Register", the same registration page is loaded, so activation proccess doesnt starting. But a new user is wrote into the database with such data (and this does not work every time), but I cannot enter the site with same data. This is my first site with registration, so it’s hard to find whats wrong. Thanks for help. Attach the code: models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default = True, db_index = True, verbose_name = 'Activated?') send_messages = models.BooleanField(default = True, verbose_name = 'Agreement for promotion messages') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py: from django.contrib.auth import password_validation from django.core.exceptions import ValidationError from django import forms from .models import AdvUser from .models import user_registrated class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required = True, label = 'Email') password1 = forms.CharField( label = 'Password', widget = forms.PasswordInput, help_text = password_validation.password_validators_help_text_html() ) password2 = forms.CharField( label = 'Reenter password', widget = forms.PasswordInput, help_text = 'Reenter your password' ) def clean_password1(self): password1 … -
one to many django add Authors to book
I have a bookstore, I want to add several Authors to add a new book .how can I do this?my code just accept one Authors class Authors(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Book(models.Model): title = models.CharField(max_length=200) topic = models.CharField(max_length=200) author = models.ForeignKey(Authors, on_delete = models.DO_NOTHING) -
How to answer interpreter question using python for django
I am trying to create a program that will create a superuser in Django. Ishould use python manage.py createsuperuser and then it asks the username that you want and ... . So I want my python program to answer it itself using the variables that it has. My program doesn't work when the question pops out. My program so far : import subprocess email = 'email@gmail.com' username = 'username' password = 'password' response = _subprocess.Popen.communicate('python manage.py createsuperuser') if 'no such table: auth_user' in response or 'python manage.py migrate' in response : print('you need to migrate the database first') else : subprocess.Popen.communicate(input='username') _subprocess.Popen.communicate(input='password') _subprocess.Popen.communicate(input='tsp5majidi@gmail.com') -
Can't figure out NoReverseMatch error in Django
I've written a small web application and when I want to load the page I get Reverse for 'form_view' with arguments '('',)' not found. 1 pattern(s) tried: ['form/view/(?P[0-9]+)$'] The application was working fine. I can't figure out what went wrong. I checked for typos and naming mistakes. I didn't find anything. I can't figure out if there's something wrong with the url pattern or not. The error started after I updated the database with a new entry. Models.py class Form(models.Model): name = models.CharField(max_length = 200) publish_date = models.DateField() book_length = models.IntegerField() first_publish = models.BooleanField() def __str__(self): return self.name def get_absolute_url(self): return reverse('form_edit', kwargs={'pk': self.pk}) urls.py urlpatterns = [ path('', views.FormList.as_view(), name='form_list'), path('view/<int:pk>', views.FormView.as_view(), name='form_view'), path('new', views.FormCreate.as_view(), name='form_new'), path('edit/<int:pk>', views.FormUpdate.as_view(), name='form_update'), path('delete/<int:pk>', views.FormDelete.as_view(), name='from_delete'), ] views.py class FormList(ListView): model = Form class FormView(DetailView): model = Form class FormCreate(CreateView): model = Form fields = ['name', 'publish_date', 'book_length', 'first_publish'] success_url = reverse_lazy('book_list') class FormUpdate(UpdateView): model = Form fields = ['name', 'publish_date', 'book_length', 'first_publish'] success_url = reverse_lazy('book_list') class FormDelete(DeleteView): model = Form success_url = reverse_lazy('book_list') form_list.html - one of the templates where the traceback tells me I have the error at <td><a href="{% url "form_view" form.id %}">view</a></td> <h1>Books</h1> <table border="1"> <thead> <tr> <th>Name</th> <th>Publish … -
How to save an image in a directory named on the User?
I am using Django2.2 and I am currently learning Django. I have created a model where I have to post an image of a certain thing and that model is connected with a User. I want to save the image on a directory named on that certain user I have a custom User Model where I created a field called Profile Photo and that profile photo is saved to a directory named on that User.But then I created another application called 'Product' and there I created many fields including an image field.I am trying to save that image on that directory named on that specific User. def user_directory_path(instance, filename): return 'media/%s/%s' % (instance.username, filename) class Products(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=1000) image = models.ImageField(upload_to = user_directory_path) product_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title When I try to save a Product and error occurs. 'Products' object has no attribute 'username' Is there any successful ways to do it. -
django restframework search_filter search content with space
data likes [ {"data": {"line": "10", "no": "10"} }, # I want to get this one {"data": {"line": "11", "no": "10"} } ] Use search_filter filter data field, search "line": "10", In the backend, search term will be split by space, and return two record above. # rest_framework.filters.SearchFilter#filter_queryset search_terms = {list} <class 'list'>: ['"line":', '"10"'] 0 = {str} '"line":' 1 = {str} '"10"' I want to search them as a whole word, How to do that? -
How Can i remove App Name from django Admin Panel?
Actually i want to remove app names from django admin panel how can i achieve this?? -
How can i Add captcha to my Html form using Django
I have already made a website with Django but unable to add captcha with Django and link it with html template -
After setup nginx assets folder not found (Django)
I was trying to set up Nginx + gunicorn + Django in a ubuntu private server by following this link Here is my /etc/nginx/sites-available file server { listen 80; server_name 192.168.0.157; location = /favicon.ico { access_log off; log_not_found off; } location /assets/ { root /home/isho/ishoErp/production; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Here is my settings.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets') ] I have a assets folder. everything works fine but assets file not found. what I'm doing wrong? -
How to set globally-accessible context variables in django template tags?
There is a template tag which returns a random element from the list. I also need to save all the elements that were in the list and the one that had been picked in context, and later depict that information in django-debug-toolbar panel. from django import template import random register = template.Library() @register.simple_tag(takes_context=True, name='pickrandomelementtag') def pickrandomelementtag(context, list_of_random_elements): context.dicts[0]["key18"] = "value19" return random.choice(list_of_random_elements) So I test setting the variables functionality with given line: context.dicts[0]["key18"] = "value19" I am able to access the {{key18}} within the template, but my aim is set this variable in a manner that it would be accessible later on (globally?) from django-debug-toolbar panel. That's where i'm stuck. Here is my django-debug-toolbar panels.py file: from debug_toolbar.panels import Panel from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.template.response import SimpleTemplateResponse class RandomPanel(Panel): name = "RandomPanel;" has_content = True template = 'panels/randompanel.html' def title(self): return _('Random Panel') def generate_stats(self, request, response): print('that is where I need to access key18') self.record_stats( { "request": request } ) How would I access context variable key18 in generate_stats method of RandomPanel class object? Or maybe context is a wrong place to set custom cariables within template tags and you'd advise other … -
How to set 'DJANGO_SETTINGS_MODULE' based on mysite.settings from a different directory
I have a Django project which works good. My manage.py and mysite folder (the one that includes the following: __init__.py settings.py urls.py views.py wsgi.py ) and a bunch of django app folders are located in the following directory E:\mydjangoproject In order to use the django setting of this project in a script, I used to use the following code at the beginning of that script: os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' which always works fine since the python script file which I was running was also located in the directory E:\mydjangoproject and it locates the mysite folder as a module and its settings perfectly. My question is what if I am trying to run that exact python script from another directory say E:\mydjangoproject\SubFolder 1\SubFolder 2\ and still want the os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' Off course when I try this I get the error ModuleNotFoundError: No module named 'mysite'. How can I pass the right path of the django settings to the script? -
Django rest hyperlinks for foreign key
Im trying to connect 2 objects using hyperlinks. I have a Company object and a 'Client' object, a company has multiple clients, so the models.py looks like this: models.py: class Company(models.Model): name = models.CharField(max_length=200) lookup_field = 'id' def __str__(self): return self.name def get_absolute_url(self): return reverse('common_app:company-detail', kwargs={'id': self.id}) class Meta: ordering = ['-id'] class Client(models.Model): image = models.ImageField() name = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, default=None) verified = models.BooleanField(default=False) def __str__(self): return self.name serializers: class CompanySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="common_app:company-detail") read_only = ('id', ) class Meta: model = Company fields = '__all__' class ClientSerializer(serializers.HyperlinkedModelSerializer): company = serializers.HyperlinkedRelatedField(read_only=True, view_name='common_app:company-detail') read_only = ('id', ) lookup_field = 'id' class Meta: model = Client lookup_field = 'id' fields = ('url', 'name', 'company') views.py: class CompanyViewSet(BaseModelViewSet): serializer_class = CompanySerializer queryset = Company.objects.all() lookup_field = "id" class ClientViewSet(BaseModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() lookup_field = "id" urls.py: app_name = 'common_app' router = DefaultRouter() router.register('client', ClientViewSet, basename='client') router.register('company', CompanyViewSet, basename='company') for url in router.urls: print(url.__dict__) urlpatterns = [ path('api/', include(router.urls)), ] I cant understand what is going wrong (i tried to put the lookup_field everywhere) but i get: E django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "client-detail". You may have failed to include … -
Saving / accessing fields from Class methods (Django)
Appologies for the beginner question and/or stupidity - I'm learning as I go.... I'm trying to pass a user entered url of a PubMed article to access the metadata for that article. I'm using the following code, but I cannot access anything form the save method in he 'Entry' model. For example in my html form I can display {{entry.date_added }} in a form but not {{ entry.title}}. I suspect it's a simple answer but not obvious to me. Thanks for any help. models.py from django.db import models from django.contrib.auth.models import User import pubmed_lookup from django.utils.html import strip_tags class Topic(models.Model): """Broad topic to house articles""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model""" return self.text class Entry(models.Model): """Enter and define article from topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) pub_med_url = models.URLField(unique=True) date_added = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): query = self.pub_med_url email = "david.hallsworth@hotmail.com" lookup = pubmed_lookup.PubMedLookup(query, email) publication = pubmed_lookup.Publication(lookup) self.title = strip_tags(publication.title) self.authors = publication.authors self.first_author = publication.first_author self.last_author = publication.last_author self.journal = publication.journal self.year = publication.year self.month = publication.month self.day = publication.day self.url = publication.url self.citation = publication.cite() self.mini_citation = publication.cite_mini() self.abstract = strip_tags(publication.abstract) super().save(*args, **kwargs) class … -
How to get thumbnail of mp4 when upload it with `django-storages`?
I work on local.py I can get instance.video.path and be able to get the thumbnail. Here are my function, testcase, and model utils.py def save_screen_shot(instance: Video) -> Video: try: filename = instance.video.path except ValueError as err: logger.info(f"The 'video' attribute has no file associated with it.") else: video_length = clean_duration(get_length(filename)) instance.video_length = video_length img_output_path = f"/tmp/{str(uuid.uuid4())}.jpg" subprocess.call(['ffmpeg', '-i', filename, '-ss', '00:00:00.000', '-vframes', '1', img_output_path]) # save screen_shot with open(img_output_path, 'rb') as ss_file: instance.screen_shot.save(str(uuid.uuid4()) + '.jpg', ss_file) instance.save() finally: instance.refresh_from_db() return instance tests.py def test_screen_shot(self): client = APIClient() client.force_authenticate(user=self.user_a) with open('media/SampleVideo_1280x720_1mb.mp4', 'rb') as mp4_file: data = { 'text': "Big Bug Bunny", 'multipart_tags': 'Tri Uncle featuring', 'video': mp4_file, } url = reverse('api:tweet-list') res = client.post(url, data=data, format='multipart') video = Video.objects.first() mp4_file.seek(0) # set head to first position before do an `assertion` assert status.HTTP_201_CREATED == res.status_code assert mp4_file.read() == video.video.read() assert video.screen_shot # Not None assert 1 == Video.objects.count() models.py class Video(models.Model): video = models.FileField(upload_to='./videos/', null=True, blank=True) I put debug and found that in my production INSTALLED_APPS has 'storages' in it. And it raise me the error ipdb> instance.video.path *** NotImplementedError: This backend doesn't support absolute paths. ipdb> dir(instance.video) ['DEFAULT_CHUNK_SIZE', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', … -
Internal Server Error when running Django with Scrapy
I am making a relatively simple django app where you can add articles to it. Besides adding the article manually i am attempting to make use of scrapy and after you have added the title of the article manually you would visit the page of the article from the front-end and by the push of a button it would crawl another website to find that article and copy specific links it would find. The problem is that i am facing several issues that results in Internal Server Error. The errors are ValueError: signal only works in main thread when I am not using the options --noreload --nothreading to run the django server. When running the server with the options mentioned just before, i get raise error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable. I would not like to have to use the options --noreload --nothreading to run the django server in general as I read that it limits performance a lot. I made a seperate app in my django project to keep things clean. The views.py I am using is the following from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from templates import * from .models import * import scrapy from scrapy.crawler import CrawlerProcess def …