Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - QuerySet Index Instead of Loop
Home Page In the picture above, I am trying to find a way to have 6 featured posts from my database appear instead of just six static entities in HTML. Here is the view for the home page: from django.shortcuts import render from singlePost.models import Post # Create your views here. def index(request): queryset = Post.objects.filter(featured=True) context = { 'object_list': queryset } return render(request, 'index.html', context) Here is a little bit of code from the home page HTML (looping through object_list): {% if forloop.counter0 == 0 %} <h3 class="mb-15 mb-sm-5 font-sm-13"><b>{{ obj.title }}</b></h3> {% endif %} My question is: how can I get the indices of object_list so I can just use the first 6 featured Posts? I do not know how to do that, so it is currently looping through all posts and I use an if as seen above to check the current index, but that just seems wrong looping 6 times instead of using indices. The loop would be fine if all the divs were the same, but as you see in the picture, they are not. So, how do I get the indices of a QuerySet? Or are there any better ways to do this then … -
Related name not working for django many to many field django
I am trying to access the value of an object that holds the ManyToMany relationship, similar to a related name for a ForeignKey or a OneToOne. How do I need to change my models to allow this? This is my current models.py from django.db import models from django.contrib.auth.models import User class Account(models.Model): account_owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account_owner') account_name = models.CharField(max_length=50) members = models.ManyToManyField(User, related_name='account_profile') When I try {{ request.user.account_owner.account_name }} I get the expected value of the account name (if they are the owner). But when I try {{ request.user.account_profile.account_name }} I get nothing. -
how to import urls.py below django project forder
when i create a django project naned test_pro with app01 in it. all settings is default . i wrte "from test_pro import urls". i get a error "django.core.exceptions.ImproperlyConfigured:Requested setting INSTALLED_APPS,but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." i dont know what mean it is ,the querstion is when i write "from test_pro import settings" run success. it makes me confused,could someone tell me why? thanks very much. django version=2.2 python interpreter version=3.7.3 this is my forder construction: -
how to fix 'Reverse for 'password_reset' not found. 'password_reset' is not a valid view function or pattern name.'
I was trying to use the custom password_reset but stucked now even login not working i already try changing url but still not working.i just can not understand why the login page is not working giving error at base.html urls.py from django.conf.urls import url,include from dappx import views app_name = 'dappx' urlpatterns=[ url('register/', views.register, name='register'), url('user_login/', views.user_login, name='user_login'), url('google_login/', views.google_login, name='google_login'), url('special/', views.special, name='special'), url('logout/', views.user_logout, name='logout'), ] views.py from django.contrib import messages from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.shortcuts import render, redirect from django.shortcuts import render from dappx.forms import UserForm,UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from google.oauth2 import id_token from google.auth.transport import requests from .models import UserProfileInfo from django.contrib.auth.models import User #from django.views.decorators.csrf import csrf_exempt def index(request): return render(request,'dappx/index.html') @login_required def special(request): return HttpResponse("You are logged in !") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('index')) else: registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: print('found it') profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True … -
Modifying Django's ORM query in a loop
G'day I'm struggling with modyfing/extending query in Django. Let's say I have query like this one below: query_set = Managers.objects.select_related('managers_contacts').all() and now I'd like to use a Python's loop to go through a dictionary which might looks like: {'continent': 'North America', 'country': '', 'city': ''} in case of some key is not none the query set should be extended by: .filter(managers_addresses__some_field='') I now how to build the loop but there problem is how add .filter() object to existed query set? Using class? Do You have any suggestions At the end I'd like to get something like query_set = Managers.objects.select_related('managers_contacts').all().filter(managers_addresses__some_field='') -
Django 2 stops working after deploying on Heroku
I'm working on a project using Django(2) in which I have some models and the application was working correctly on my local system. But when I have deployed this application to Heroku, it starts returning an error as: column core_votingvalueshistory.value1 does not exist LINE 1: SELECT "core_votingvalueshistory"."id", "core_votingvalueshi... ^ HINT: Perhaps you meant to reference the column "core_votingvalueshistory.value". Here's my model which causes the problem: class VotingValuesHistory(models.Model): # id = models.AutoField(primary_key=True, auto_created=True) value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) and it's also pointing the view where I'm making a query to the objects as: From views.py: v1 = VotingValuesHistory.objects.all().filter() for item in v1: if item.group == groupname: if item.score1 == 'disaster': numscore_disaster += 1 elif item.score1 == 'meh': numscore_meh += 1 else: numscore_helpful += 1 I have tried makemigrations and migrate commands using: heroku run python manage.py makemigrations heroku run python manage.py migrate -
problem with dropdownlist in django netted from database
i have two apps in my project Immob and compte i want make froms with username and password and drop down list filled from database thank you for your help #INVEST_APP/compte/models.py from django.db import models from django.contrib.auth.models import User from immob.models import structure from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) structure=models.ForeignKey(Structure,on_delete=models.CASCADE) def __str__(self): return self.structure @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Parsing fields in django-import-export before importing
I am using django-import-export field to expect a csv file containing a location's name and its longitude and latitude. I want to parse the longitude and latitude field from the csv to convert them into django.contrib.gis.geos.Point object so that I can input it to my Location model's geom field. # models.py from django.contrib.gis.db import models class Location(models.Model): name = models.CharField(max_length=200) geom = models.PointField(null=True, blank=True) def __str__(self): return self.name # admin.py from .models import Location from import_export import resources from import_export.admin import ImportExportModelAdmin class LocationResource(resources.ModelResource): geom = Field() latitude = Field() longitude = Field() class Meta: model = ProjectActivity fields = ('id','name', 'latitude', 'longitude') exclude = ('geom') export_order = ('id', 'name', 'latitude', 'longitude') def dehydrate_geom(self, data): return Point(data.longitude, data.longitude) class LocationAdmin(ImportExportModelAdmin): resource_class = LocationResource admin.site.register(Location, LocationAdmin) This is how far I got but to no success. Must have: Location(name='name', geom=Point(longitude, latitude)) -
Is it possible to register views to the django admin console like model.?
I tried to register the views in Django 2.2 admin interface, But I am not sure how to add it or can we able to add it.? When I tried I am getting the below error. admin.site.register(TargetView) File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register for model in model_or_iterable: TypeError: 'type' object is not iterable -
how to add new features in a deployed django project?
I have a Django project already deployed on an AWS server(Linux distribution). now I want to add new features without messing with the database and without changing the folder structure as I set up a virtual environment in the project folder only on the server machine. I used Github to clone the project to the server, so is there any command that I can write to override the changed files on the server directory? I can override the DB now but in future what's the best practices? -
How to check if class already exists in django?
I have a fabric that creates classes. ...Some code here... def CreateClass(self, _context): classname = _context.__name__ + "Test" return type(classname, (viewsets.ModelViewSet,), { 'set_of_objects':_context.objects.all(), 'template_name': "base.html" Then I have some class when I calls this fabric: bla-bla-bla myClass = CreateClass(Foo) I would like to customize behaviour for specific classes, so I want to create them manually. for example I could create a class class FooTest: set_of_objects = FooSerializer(smth here) template_name = "Foo.html" The problem is, when I call this fabric it creates a FooTest class nevertheless it already exists in my app. I would like to write a method that will allow me: 1. check if class with specific name already exist. (or is there some uniq class ID?) 2. If class already exist method should returns it Could you please help me for first question? I checked some manuals but did not find a solution how can I do this. I already try to use something like this from django.apps import apps cls = apps.get_model(app_label = 'base', model_name = 'FooTest') The problem is, that this method is working, when FooTest is inherited from models.Model (from django.db import models) But is it possible to know if class exist if it not … -
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 …