Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get all the properties of objects using foreign key in django model
Using Djangorestframework I had created rest api. I have two models in my app countries and states. I had related countries model to states model using Foreign key method, But while fetching list of states in States api i am getting states names, but in the place of country i am getting countries primary key id instead of it's name how can i get all the fields of Countries instead of PK id ---------- Serializers.py code from rest_framework import serializers from .models import countries, states class countiresSerializers(serializers.ModelSerializer): class Meta: model = countries fields = '__all__' class statesSerializers(serializers.ModelSerializer): class Meta: model = states fields = '__all__' ---------- Viewset.py code-- from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from.models import countries, states from .serializers import countiresSerializers, statesSerializers class countryList(APIView): def get(self, request): country1 = countries.objects.all() serializer = countiresSerializers(country1, many=True) return Response (serializer.data) def __pos__(self): pass class statesList(APIView): def get(self, request): state = states.objects.all() serializer = statesSerializers(state, many=True) return Response (serializer.data) def __pos__(self): pass I had attached image u can see the country displaying primary id instead of it's name, how can i get name and all … -
test_forms with django give AssertionError
I am trying to write test for my forms with my Django project. I try to test following BookForm: forms.py class BookForm(ModelForm): class Meta: model = Book fields = ['title', 'author', 'summary', 'tag', 'genre', 'language', 'book_format', 'read_date'] #labels = widgets = { 'author': AddAnotherWidgetWrapper( forms.Select, reverse_lazy('author_form'),), 'tag': AddAnotherWidgetWrapper( forms.SelectMultiple, reverse_lazy('author_form'),), } permission_required = 'libraryapp.can_edit' def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) # print(self.request.user) super(BookForm, self).__init__(*args, **kwargs) My test_forms.py looks like that: class BookFormTest(TestCase): def test_read_date_in_the_past(self): print('BookForm TEST Lounched') title = 'TestBookPast' author = 'TestAuthorPast' date = datetime.date.today() + datetime.timedelta(days=2) form_data = {'title': title, 'author': author, 'read_date': date} form = BookForm(data=form_data) self.assertTrue(form.is_valid()) I have no idea why it is not working. Maybe I forgot about something really important? I always get AssertionError: self.assertTrue(form.is_valid()) AssertionError: False is not true -
Django User Profile - default value depend on chosen User
I want to create Profile extending User model. from django.db import models from django.contrib.auth.models import User from rest_framework.authtoken.models import Token # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) operatorId = models.CharField( max_length=50, default= 'O'+str(user.id), #get user id blank=False, unique=True, ) Want to add operatorId which depends on userId chosen (operator id i O and user.id as a string). How to get current user id? basically, I need to change default every-time I change user. Is it possible? -
Django - IntegrityError in terminal when migrating changes to a relationship field
I've got a Django model like the following.. class ExampleModel(models.Model): name = models.CharField(...) related_user = models.ForeignKey(UserTypeA, related_name='related_example', blank=True, null=True, on_delete=models.SET_NULL) where I recently had to make a change to the related_user field by changing the ForeignKey from UserTypeA to UserTypeB. Of course, this raises an error in the terminal when I attempt to python manage.py makemigration... django.db.utils.IntegrityError: insert or update on table "models_examplemodel" violates foreign key constraint "models_examplemodel_related_user_id_ac0c6018_fk_accounts_" DETAIL: Key (related_user_id)=(13) is not present in table "accounts_usertypea". What's the safest way to go about making these changes? Currently I'm in development so I'm happy to delete my data/migrations/whatever, but I imagine in production this would be difficult. The ideal behaviour I'd like to see here is the relations from ExampleModel and UserTypeA just being deleted, and so the current relationships would be set to NULL. Thoughts? -
HTTP Error 429: Too Many Requests on my local server
I'm getting HTTP Error 429: Too Many Requests error on my local django server, any way to disable this? -
django2: url based on pk not working
I want to have a form (webpage) for the model ImpCalendar so I can edit it's data. The url should have the calendar_id (primary key), which i set in the urls.py The model (ImpCalendar) has a ForeignKey to Establishments. I do not use that foreignkey in the view/form so i don't know if it is relevant. If i do in views.py; return render(request, 'importer/calendaredit.html', {'form': calendar}) i do see the data on a page, but not a (edit) form. Just the data, not the fill-in fields. When i do return render(request, 'importer/calendaredit.html', {'form': form}) which sounds logical to me, I get the error django.urls.exceptions.NoReverseMatch: Reverse for 'calendaredit' with arguments '('',)' not found. 1 pattern(s) tried: ['importer\\/calendar\\/(?P<calendar_id>[0-9]+)\\/$'] It seems to me, the value returned for the calendar_id is now forms-data (html) which it can not do anything with. But i don't know what I am doing wrong. It has to do something with the html code and the values being transported to it, but i am last. models.py class Impcalendar(models.Model): establishment = models.ForeignKey(Establishments, on_delete=SET_NULL, null=True) url = models.CharField(max_length=255) comment = models.CharField(max_length=255, null=True, blank=True) status = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.establishment) forms.py from django import forms import datetime from importer.models import … -
Python flask RESTful: Directory structure
I am fairly new to python and flask, I have created an authentication stystem, A JWT token based authentication. Currently my directory structure is : Note : If possible, Please answer in detail. -Project -- venv (folder) -- models.py -- resources.py -- run.py -- views.py As the names are self explanatory, models.py have a class which named UserModel, In resources,py there are many classes like UserRegistration, UserLogin, UserLogoutAccess, UserLogoutRefresh, TokenRefresh, AllUsers. run.py have the server related and app initialization code, And also the endpoints resource are defined here like : api.add_resource(resources.UserRegistration, '/registration') I know its messy, But also i have no idea about the python Flask conventions, Should each class have its own file, Should the authentication code be placed in one directory, As the project will obviously grow. I am thinking about the following directory structure : -Project -- venv -- Authentication -- login.py -- registration.py -- logout.py -- userLogoutRefresh.py .... .... -- Models -- UserModel.py .... .... -- run.py Looking for suggestions. -
post_details() got an unexpected keyword argument 'string' in Django?
urls.py : urlpatterns = [ path('', views.posts, name='home'), path('<string:slug>', views.post_details, name='detail'), ] views.py (function) : def post_details(request, slug): posts = Posts.objects.get(pk=slug) return render(request, 'posts/post_details.html', {'posts': posts}) NOTE : I am currently learning django. -
Heroku-Django: requirements.txt
This is not so much of a problem but I have been adding requirements.txt everytime I start a new project and deploy it on heroku. I don't understand the purpose of requirements.txt though and why it is so important. -
Django DRY functions at bottom of forms
In my forms.py I have to setup and then clean a lot of similar variables. class FormOne(forms.Form): email_field = forms.EmailField( required = True, max_length = 70, label = mark_safe("""<i>Enter email address</i>"""), ) # other fields def clean_email_field(self): return data class FormTwo(forms.Form): email_field = forms.EmailField( required = True, max_length = 70, label = mark_safe("""<i>Enter email address</i>"""), ) # other fields def clean_email_field(self): return data In my views.py I can successfully define a function at the bottom of the form and reference it in the code above. But if I try to put something like this at the bottom of the file I get def clean_email_field(form_data): # rest of function ***ERROR*** clean_email_field undefined Is it because forms are classes, not defs? -
Unable to define urls [Django]
I am trying to set up my django project but failed everytime due to one or other error. Please help! Want To Add urlpatterns += patterns('', (r'^catalog/$', 'preview.views.home'),) urls.py (Attempt) from django.contrib import admin from django.urls import path from django.conf.urls import url, include from preview import views urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns = [ url(r'^catalog/', include('', views.home, name='home')), ] urls.py (Attempt) from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns = [ path('preview/', views.page), ] Sample Error Performing system checks... Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x10dba9268> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/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-2.0.6-py3.6.egg/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-2.0.6-py3.6.egg/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/urls/resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0.6-py3.6.egg/django/utils/functional.py", line 36, in … -
validate Django model field using setter
I'm using Django 2.0 I have a model class class AmountGiven(models.Model): amount = models.FloatField(help_text='Amount given to the contact') _given_date = models.DateTimeField( db_column='given_date', default=datetime.now, help_text='Date and time when amount was given to the contact' ) return_date = models.DateTimeField( blank=True, default=None, null=True ) modified = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now=True) def __str__(self): return str(self.amount) @property def given_date(self): return self._given_date @given_date.setter def given_date(self, value): value_2 = value try: value_2 = datetime.strptime(value_2, "%Y-%m-%d %H:%M:%S").date() except ValueError: try: datetime.combine(value, datetime.min.time()) value_2 = datetime.strptime(value_2, "%Y-%m-%d").date() except ValueError: raise ValueError("Date is not of valid format. %Y-%m-%d %H:%M:%s") if value_2 > datetime.today().date(): raise ValueError("The date chosen was in the future.") self._given_date = value I want to validate if given_date is not in future. If given_date is in future, it will raise a validation error and not save the form data. In pytest, I'm doing @pytest.mark.django_db class TestAmountGiven(TestCase): def test_model_add_amount_given(self): amount_given = AmountGiven( amount=10000.00, given_date='2018-1-30 00:00:00', promised_return_date='2019-02-01 00:00:00' ) amount_given.save() But this is giving warning as transactions/tests/test_models.py::TestAmountGiven::test_model_add_amount_given /path_to/python3.6/site-packages/django/db/models/fields/__init__.py:1423: RuntimeWarning: DateTimeField AmountGiven._given_date received a naive datetime (2018-01-30 00:00:00) while time zone support is active. RuntimeWarning) /path_to/python3.6/site-packages/django/db/models/fields/__init__.py:1423: RuntimeWarning: DateTimeField AmountGiven.promised_return_date received a naive datetime (2019-02-01 00:00:00) while time zone support is active. RuntimeWarning) 1. Is this the right approach of writing Field … -
django centos7 AWS ec2 instance
I was trying to follow this tutorial here to just run a django test project. But I am not able to even see django welcome screen. when I try to run it in my browser (http://ec2-http://34.xxx.xx.73.us-west-2.compute.amazonaws.com:8000/) I f anyone can point out what Iam missing here I will be very grateful. this is exactly what I have done: 1- create centos7 EC2 instance and edit its inbound rule (added port 80 (everyone) to ensure it is accessible : 2- in my command terminal I connect to the centos7 server through ssh then did the following: sudo yum install epel-release sudo yum install python-pip httpd mod_wsgi sudo pip install virtualenv mkdir /var/projects cd /var/projects virtualenv myenv cd myenv source bin/activate pip install django django-admin.py startproject myproject python manage.py makemigrations python manage.py migrate python manage.py runserver 0.0.0.0:8000 when I try to open my webpage it fails with the following message: This site can’t be reached xx.xx.xx.xx took too long to respond. ERR_CONNECTION_TIMED_OUT I don’t know what I am missing here …this should be simple… Any help will be highly appreciated..many thanks -
How to retrieve previously enter data in a form in django?
I have written code to display a form on the html page in django. When I click on the update button, everytime, it is showing an empty form. But what I want is, if I have entered some data previously, that data should be displayed in the form normally. Then I have to be able to edit it. But, I am getting an empty form everytime. views.py: def update_longterm(request): if not request.user.is_authenticated: return render(request, 'cups4/index.html') else: form = LongtermForm(request.POST or None, request.FILES or None) if form.is_valid(): longterm = form.save(commit=False) longterm.user = request.user longterm.body = form.cleaned_data['body'] longterm.save() return render(request, 'cups4/detail_longterm.html', {'longterm': longterm}) context = { "form": form, } return render(request, 'cups4/create_template.html', context) Models.py: class NotNecessary(models.Model): title = models.TextField("NotNecessary",editable=False) slug = models.SlugField(max_length=250, unique_for_date='publish') user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title Forms.py: class LongtermForm(forms.ModelForm): class Meta: model = Longterm fields = [ 'body',] template: {% extends 'base.html' %} {% block title %}Immediate{% endblock %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <h3>Immediate Goals</h3> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include … -
Django each model must have a date_created and date_modified field
Is there a way to have a date_created and date_modified fields for each and every model in models.py? I would like to have these two fields for each table being created so that I will be able to know when a row is created or updated. But I don't want to have them shown in my models.py specifically for each model. Is there a way to do this? -
fully customize django admin site
I am new to django. Is there any way to fully change django admin site UI? I have searched a lot but none of them works (most of them were so old like for 5 6 years ago). The most common answer was to create an admin directory in template folders, then inside it a directory with app name and then model name. But nothing happened doing that. Is it ever possible to have my fully customized UI? What should I do? tnx -
Django- how to update admin with function
I can't seem to figure out how to update my admin page with a custom function I have an admin script for myapp: myapp/admin.py That script has a Class for an admin page based on myapp's model: `class MyappAdmin(admin.ModelAdmin):` That Class has a function/method to format one of the model items (filter_days): `def filter_days(self, obj):` How can I get this Class method/function to update my admin page? `cover/myapp.admin.py.html` -
How to include a template inside a template in django?
I have a home page "home.html" which extends a base template "base.html". I am rendering home.html. And in my home.html I have included another template "nav.html" with {% include "qa/nav.html" %}. but it isn't including the navigation bar items which are inside nav.html content of nav.html are as below <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="#"> <span class="nav_item_icon"> <svg width="50px" height="50px" viewBox="0 0 50 50" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="Icons" class="site_nav_icon-fill" stroke="none" fill="#555" fill-rule="evenodd"> <path d="M4,7.99448227 C4,5.23610588 6.24325385,3 9.00365614,3 L46,3 L46,42.1055177 C46,44.8638941 43.7567461,47.1 40.9963439,47.1 L4,47.1 L4,7.99448227 M11,12 L25,12 L25,14 L11,14 M11,20 L25,20 L25,22 L11,22 M11,28 L39,28 L39,30 L11,30 M11,36 L39,36 L39,38 L11,38 M29,12 L39,12 L39,22 L29,22 Z"></path> </g> </svg> </span> <b>Home</b></a> </li> <li class="nav-item"> <a class="nav-link" href="#"><b>Topics</b></a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search"> <!--<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>--> </form> {% if user.is_authenticated %} <a href="#" alt={{user}} class="user-cpanel"><img src="https://qph.ec.quoracdn.net/main-thumb-189662175-50-nlacuvuthjfpbtjeypwczxmegutvhhvn.jpeg" /></a> {% else %} <a class="btn btn-primary btn-lg" role="button" href="{% url 'login' %}">Login</a> {% endif %} whats going wrong here, how do I display the nav items? -
Django Mezzanine blog gönderisine özel alan nasıl eklenir?
Official Documantation for Mezzanine 4.3.0 I want to add a custom text field to the blog post. However, official documentation is not enough. I Added my project's settings.py this lines; EXTRA_MODEL_FIELDS = ( ( "mezzanine.blog.models.BlogPost.caption", "django.db.models.CharField", ("Media",), {"default": 'URL', 'max_length': 128}, ), ) according to the official document I need to add the following lines to some places; MIGRATION_MODULES = { "pages": "path.to.migration.storage.pages_migration", "forms": "path.to.migration.storage.forms_migration", "galleries": "path.to.migration.storage.galleries_migration", } but I do not know where to add it, I guess it could be the same setting.py file. but I do not know how to edit for my configuration. To create the new migration files and apply the changes, simply run: $ python manage.py makemigrations $ python manage.py migrate and finaly Admin Field; # In myapp/admin.py from copy import deepcopy from django.contrib import admin from mezzanine.blog.admin import BlogPostAdmin from mezzanine.blog.models import BlogPost blog_fieldsets = deepcopy(BlogPostAdmin.fieldsets) blog_fieldsets[0][1]["fields"].insert(-2, "image") class MyBlogPostAdmin(BlogPostAdmin): fieldsets = blog_fieldsets admin.site.unregister(BlogPost) admin.site.register(BlogPost, MyBlogPostAdmin) but which admin.py file. I need to create a folder admin.py file where the settings.py file is located? -
(Django) View vs App
I'm a beginner in django and I came across a small question like "what's the exact difference between a view and an application ?" Are they similar to some extent or differ completely ? The reason why this question arised for me is that because view is something which django displays in front-end and app is also similar to that except that app is somewhat reusable. -
Django adding a django search form in the header of the base.html
I wanted to include a search form and not just a search but a django at the header of the base.html.I am doing this because i wanted it to appear on all of my pages that are inheriting the base.html. At the moment the following: search_form.html with the html form tags (actual search form) base.html inheriting the search_form.html forms.py in my app folder - this specifies one input text field to appear as the search field in page `search_form.html` <form class="search--form navbar-right" method="POST" action="{% url 'all_results' %}" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button class="btn" type="submit">Search</button> </form> forms.py from django import forms class SearchForm(forms.Form): search_input = forms.CharField(max_length=100) class Meta(): widgets = { 'search_input':forms.TextInput(attrs={'id':'drilam'}) } I also wanted to include a view for my forms.py but then i realize i would need some url patterns, and when will i call that url pattern. Is there anyway in django maybe some signals working in the background that can be called whenever my base.html is loaded also including the form with the search field? What is working for me now when i run the server , i get a form with the submit button. -
How to check that a user is logged in from chrome extension when using django in backend
I'm developing a web site using django framework and I need to develop a chrome extension for this website. I want when the user click the icon of the extension check if the user is logged in my site to show a specific popup or show a logging popup (if the user is not logged yet). Thank you in advance. -
How to pass a request in django urls
I have this url: (Django 2.0) re_path('auth/(?P<code_>[a-zA-Z0-9]{12})/(?P<email_>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', homePageView.autenticate, name='autenticate'), in my views.py: class homePageView(TemplateView): template_name = 'index.html' def autenticate(self, email_, code_): try: user = Usuario.objects.get(email=email_,activated_code=code_) code = user.two_factors_auth_code if (not user.two_factors_auth) and (code == code_) and (len(code) == 12): user.next_login = True user.save() return redirect('home') except Usuario.DoesNotExist: return redirect('home') I wish I could login user in my autenticate method but I don't have a request parameter in my function. ¿How can I transform my autenticate function to this another? class homePageView(TemplateView): template_name = 'index.html' def autenticate(self, request, email_, code_): try: user = Usuario.objects.get(email=email_,activated_code=code_) code = user.two_factors_auth_code if (not user.two_factors_auth) and (code == code_) and (len(code) == 12): user.next_login = True user.save() #################### login(request,user) #################### return redirect('home') except Usuario.DoesNotExist: return redirect('home') -
[Python Django]How to get field value on another model?
I want to make an Django Application named Blog. I made a code like this: Article.py from django.db import models from models.Writer import Writer class Article(models.Model): createdAt = models.DateTimeField("Created At", auto_now_add=True) id = models.AutoField(primary_key=True) title = models.CharField("Title", max_length=30) contents = models.TextField() writer = models.ForeignKey(Writer, verbose_name="Writer") lastModified = models.DateTimeField("Last Modified", auto_now=True) category = models.ForeignKey(category, verbose_name="Category") Comment.py from django.db import models from models.Writer import Writer class Comment(models.Model): writer = models.ForeignKey(Writer) title = models.CharField(max_length=30) contents = models.TextField() Can django find id field from the model Article? -
Heroku Adding Custom Domains With Wildcard
I am trying to add custom domains to my Heroku hosted Django project. And went through the steps on the website and also looked at this video. https://www.codingforentrepreneurs.com/projects/idea-landing/custom-domain-name-heroku-django/ I would like to add a Wildcard-Domain called: *.wasjournalistenverdienen.de like it is shown in the video. However, if I do so, the response from my heroku CLI is ▸ Apps using ACM are not allowed to have wildcard domains What is the best way to fix this problem? Should I just turn off ACM (which Heroku does not advise)?