Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create or update a model in Django based on a unique identifier?
I'm using Python 3.7. I want to create a record or update one if it exists so I was using the most voted solution here -- Create Django model or update if exists . However, I'm getting a django.core.exceptions.FieldError: Invalid field name(s) for model MyObject: 'identifier'. error when I run my code. I'm using this my_object, created = MyObject.objects.update_or_create( identifier=path, defaults={"title": title} ) Where my model with my unique constraint is defined below class MyObject(models.Model): title = models.TextField(default='', null=False) path = models.TextField(default='', null=False) url = models.TextField(default='', null=False) votes = models.IntegerField(default=0, null=False) updated_at = models.DateTimeField(null=True) class Meta: unique_together = ("path", ) What else do I need to do to get this working? -
How to get fullchain.pem on heroku
Here we need fullchain.pem on heroku to test a test application that works on WebSockets. How to get it? -
Render a template on nav item click in block content without loading the whole page (Django)
Hell guys, I'm still trying to learn so please dont be harsh :) I'm trying to find a way to render templates in block content. Example Nav items About Contact FAQ Our team If the user clicks on About page (About.html) It renders it in the {block content}without reloading or refreshing the page. If the user then clicks on Contact us the {block content} gets updated with the Contact us page (Contact.html) Is there any way you can do this in Django without using Ajax or Jquery. if not is there somewhere good documentation I can follow to do this? I've been searching the internet for any answers but I can't find anything on this exact matter only found Pjax https://github.com/defunkt/jquery-pjax but I'm a bit afraid of using Ajax and my knowledge regarding Ajax is not really great. Thank you for reading this and for your time. Kind Regards, -
Django user permission to update blog is not working
I have been trying to work with Django permissions on my website, and cannot establish permissions correctly. I've read around nine different websites and have been stuck on this for hours. I don't know how to correctly set the update permissions for my blog posts. I have an app called 'blog' and files for it like models.py, views.py, and the update.html displaying the update a blog using forms. blog.models.py from django.db import models from django.conf import settings from django.utils import timezone from django.db.models import Q from django.contrib.auth.models import Permission User = settings.AUTH_USER_MODEL class BlogPostQuerySet(models.QuerySet): def published(self): now = timezone.now() return self.filter(publish_date__lte=now) def search(self, query): lookup = ( Q(title__icontains=query) | Q(content__icontains=query) | Q(slug__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(user__username__icontains=query) ) return self.filter(lookup) class BlogPostManager(models.Manager): def get_queryset(self): return BlogPostQuerySet(self.model, using=self._db) def published(self): return self.get_queryset().published() def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().published().search(query) class BlogPost(models.Model): # blogpost_set -> queryset user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) images = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # Example: "hello world" -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date','-updated','-timestamp'] permissions = [ ('can_change','Can … -
TemplateDoesNotExist at /post/15/ post_detail..... what is the problem?
i have made an blog page and now i am just trying to add more features. when i add a new post after attaching the imagefile, it says TemplateDoesNotExist at /post/(post number)/post_detail. but meanwhile new post can be seen in first page with image. blog/views.py: from django.views.generic import ListView,DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.urls import reverse_lazy class BlogListView(LoginRequiredMixin,ListView): model=Post template_name='home.html' login_url='login' class BlogDetailView(LoginRequiredMixin,DetailView): model=Post template_name='post_detail' login_url='login' class BlogCreateView(LoginRequiredMixin,CreateView): model=Post template_name='post_new.html' fields=('title','body','image') login_url='login' def form_valid(self,form): form.instance.author=self.request.user return super().form_valid(form) class BlogUpdateView(LoginRequiredMixin,UpdateView,UserPassesTestMixin): model=Post template_name='post_edit.html' fields=('title','body','image') login_url='login' def test_func(self): obj=self.get_object() return obj.author==self.request.user class BlogDeleteView(LoginRequiredMixin,DeleteView,UserPassesTestMixin): model=Post template_name='post_delete.html' success_url=reverse_lazy('home') login_url='login' def test_func(self): obj=self.get_object() return obj.author==self.request.user blog/urls.py: from django.urls import path from .views import ( BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView, ) from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',BlogListView.as_view(), name='home'), path('post/new/',BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/',BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/',BlogDetailView. as_view(), name='post_detail'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] if settings.DEBUG: urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) pages/templates/postdetails.html: {% extends 'base.html' %} {%load static%} {% block content %} <div class="container"> <!-- Page Heading/Breadcrumbs --> <h1 class="mt-4 mb-3">{{object.title}} <small>by <a href="#">{{object.author}}</a> </small> </h1> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="/">Blogs</a> </li> <li class="breadcrumb-item active">Blog Post Detail</li> </ol> <a href="{%url 'post_edit' post.pk%}">+Edit this posts</a> <div class="row"> <!-- Post … -
In Python/Django, how do I import one service I created from another one I created?
I'm using Pyton 3.7 and Django. I have a directory where I keep my services my_project my_app services __init__.py foo_service.py bar_service.py "init.py" is empty. Within "foo_service.py", I define class "FooService" and within "bar_service.py," I define class "BarService." How do I import BarService in FooService? I tried import services.bar_service but got the error ModuleNotFoundError: No module named 'services' -
Is there any way to create a program what run inside a server?
Currently I am creating web application in Django and for one user request I have to make more requests to database. So, I think like creating a program that will handle all the database requests in the mid way. So, I don't have to send requests per each user.I know how to make that program. The problem is how can I make that program and web app in the same server? Is there any chance? Note: I will host my app on own server. Not on others. -
django dropdownlist showing object id instead of names
i have two apps in 1)boq 2)inputs inputs has a model building class building(models.Model): building = models.CharField(max_length=300 my boq app has a model boqmodel class boqmodel(models.Model): code = models.IntegerField() building =models.CharField(max_length=300) level = models.CharField(max_length=300) activity = models.CharField(max_length=300) subactivity = models.CharField(max_length=300) duration=models.IntegerField() linkactivity= models.CharField(max_length=300) linktype= models.CharField(max_length=300) linkduration=models.IntegerField() plannedstart=models.DateField() plannedfinish=models.DateField() actualstart=models.DateField() actualfinish=models.DateField() i have a form in boq app as follows class boqform(forms.ModelForm): class Meta: model = boqmodel fields = ['code', 'building', 'level', 'activity', 'subactivity', 'duration', 'linkactivity', 'linktype', 'linkduration', 'plannedstart', 'plannedfinish', 'actualstart', 'actualfinish'] building coloumn is same in boq and inputs app i need to have a drop down in boq form for building with values from model in inputs.building model -
Related if in one of two fields in Django
I want to have two m2m related fields in my model admins and users but specified Profile can but in of admins or users in one Session. What is the best way to resolve it? class Session(models.Model): admins = models.ManyToManyField(Profile, related_name='admins') users = models.ManyToManyField(Profile, related_name='users') -
Address Django translation messages using variables
Is there a way to set translation messages parametrically in Django? For example, when I need to traslate a message in a template, I always need to write the whole text: <h1>{% trans "Hello World" %}</h1> Instead, I'm wondering if there is something that allows to use variables, something similar to Ruby on Rails: <h1><%= t :hello_world %></h1> -
django messages syntaxerror useing f string
i am trying to send a message to the user of my site when they register i used django message import but i did not work here is my views.py code # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render, redirect from .models import cooking from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages # Create your views here. def homepage(request): return render(request=request,template_name='main/home.html',context={"cooking": cooking.objects.all}) def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.succees(request, f"new account created: {username}")#error on this line login(request, user) return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, form.error_messages[msg]) form = UserCreationForm return render(request,"main/register.html",context={"form":form }) -
Make_password and user.set_password before user saving get different value from after saving
when I create new user, I set pass by user.set_password, after saving make_password make different value from user.set_password, and when I trying to check password by check_password(password,user.password) I get False. But if I call make_password before saving I get same. Sorry for my english ^_^ class MyUserManager(BaseUserManager): def create_user(self, email, password, first_name, sername, sex, date_of_birth, **extra_fields): if not email: raise ValueError('Email must be.') user = self.model( email = self.normalize_email(email), first_name = first_name, sername = sername, sex = sex, date_of_birth = date_of_birth, ) user.set_password(password) user.save() print(f'email {user.email} pass {password} passhash {user.password} hasher {make_password(password)}') return user def create_superuser(self, email, password, first_name, sername, sex, date_of_birth, **extra_fields): if not email: raise ValueError('Email must be.') extra_fields.setdefault('is_staff', True) return self.create_user(email, password, first_name, sername, sex, date_of_birth, **extra_fields) In models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.hashers import check_password, make_password from .managers import MyUserManager # Create your models here. class MyUser(AbstractBaseUser): first_name = models.CharField(max_length = 80) sername = models.CharField(max_length = 80) email = models.EmailField(unique = True) password = models.CharField(max_length = 80) date_joined = models.DateField(auto_now_add = True) date_of_birth = models.DateField() sex = models.BooleanField() balance = models.FloatField(null=True) ticket = models.PositiveSmallIntegerField(null=True) ticket_date_end = models.DateField(null=True) ticket_next = models.PositiveSmallIntegerField(null=True) ticket_next_date_end = models.DateField(null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) REQUIRED_FIELDS = … -
Is there any way to identify the source of a serialization dependency error in django?
I've got a fairly complicated django project with 4 apps and (unfortunately) a bunch of many-to-many relationships. Sometime recently, dumpdata and tests stopped working, throwing the following error: Can't resolve dependencies for app1.ActionItem, app1.ActivityLog, app2.AnnualEvaluation, app1.Citation, app2.Commitment, app1.Complaint, app1.ComplaintStage, app1.ComplaintSubscription, app1.Contact, app1.Document, app2.Feedback, app1.Goal, app2.Goal, app1.GoalUpdate, app1.Investment, app1.KeyDate, app1.Note, app2.ProfessionalDevelopmentGoal, app1.Project, app2.QuarterlyUpdate, app1.ResearchRequest, app1.Source, app1.SubGoal, accounts.Subscription, app1.SupportItem, app2.Tactic, app1.UserProfile, app1.Workplan in serialized app list. This happens whether or not I use natural key handling. Specifying the natural key dependencies explicitly in the model also doesn't seem to have any effect. I know it's a bit of a tangled web, but is there any way to figure out which specific model relationships are causing this error? -
Django project css and js not loading
Had a similar question with an older version of Django... trying to get my site to load with its css and js This is the structure of my project gradMVPV1 --> .idea --> catalog views models apps .... --> gradMVPV1 settings urls wsgi .... --> templates ---->static css js ... ---->index.html db.sqlite3 manage.py this is what I have on settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/templates/static') -
Pointing to index.html in Django
I just updated to a newer version of django and now having difficulties pointing to my index.html file This is the structure of my project gradMVPV1 --> .idea --> catalog views models apps .... --> gradMVPV1 settings urls wsgi .... --> templates ---->index.html db.sqlite3 manage.py This is my settings.py file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, '/templates') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, "index"), ] and views def index(request): return render(request, "index.html") this is my error message ValueError at / dictionary update sequence element #0 has length 1; 2 is required -
Django signals "object has no attribute"
I have problem with show count -=1 with the signals. Pesquisei aqui mas não achei nada parecido, apesar da mensagem de error ser comum: "AttributeError at /admin/statements/statement/ 'Watched_lessons' object has no attribute 'purchased_lessons'" I tried it: watched_lessons/models.py from lessons.models import lesson from django.conf import settings from purchased_lessons.models import Purchased_lessons from datetime import datetime from django.dispatch import receiver from django.db.models.signals import post_delete class Watched_lessons(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) lesson = models.ForeignKey(Statement, on_delete=models.CASCADE) watched_date = models.DateTimeField(default=datetime.now) @receiver(post_delete, sender=Watched_lessons) def rem_watched_lessons_count(instance, **kwargs): instance.purchased_lessons.count -= 1 instance.purchased_lessons.save() The other codes: lesson/models.py from courses.models import Course class Lesson(models.Model): course = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) lesson = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.lesson courses/models.py from django.db import models class Course(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title purchased_lessons/models.py from django.db import models from django.conf import settings from courses.models import Course class Purchased_lessons(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) count = models.IntegerField(default=0) def __str__(self): return self.course When I delete a Lesson, I automatically delete Watched_lessons, because I put the `lesson = models.ForeignKey (Statement, on_delete = models.CASCADE) function` So, I need to automatically, when a "Watched_lessons" is deleted, register a signal "- = 1" in the "count" attribute of purchased_lessons / models.py. How can I … -
Cannot catch an exception in a try/catch block
I have a typical drf view which get some data, serialize it, process it in a separate service. I validate input data with python-trafaret inside my service. def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) # one field serializer; data = JsonField() serializer.is_valid(raise_exception=True) upload_obj = serializer.save() try: self.uploader_class(upload_obj).execute() except UploaderValidateError as e: raise UploadFailed(detail=str(e)) # drf exception with 400 status return Response(status=status.HTTP_204_NO_CONTENT) If trafaret cannot parse input data it raises a DataError. I catch it inside my execute method like this: try: validated_data = self.validate_data(data) except t.DataError as e: raise UploaderValidateError(e.as_dict()) Traceback says that there was an unhandled UploaderValidateError with the text: ...exceptions.UploaderValidateError: {0: {'value': "value can't be converted to float"} I tried to change this line of code: except UploaderValidateError as e: to except Exception as e: but I still can't catch an error -
Django registration template doesn't load form when entered
I have a problem with my Django registration template. To register I'm using a Django-auth system. Theoretically it works, because whenever I enter my registration site, it loads the template, but it only shows my registration button. When I click it, the page reload and the form shows up. I assume it's something about POST method but I can't figure it out to load form right away, after redirect. This is my views.py: class RegisterView(TemplateView): template_name = 'register/register.html' def post(self, request, *args, **kwargs): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() return render(request, self.template_name, {'form': form, }) forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] Here is picture of my register.html template, somehow I couldn't paste it as a code -
Django model's clean method and foreign key validation in FormView
In my django app I have simple Category and Offer models: class Category(BaseModel): title = models.CharField(_('Category title'), max_length=256) available = models.BooleanField(_('Is available'), default=True) slug = models.SlugField(max_length=256, null=True, blank=True, unique=True, verbose_name=_(Slug')) requires_item_price = models.BooleanField(default=False, verbose_name=_('Requires item price to be provided')) class Offer(BaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, verbose_name=_('Category')) item_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, verbose_name=_('Item price'), blank=True) def clean(self): if self.category.requires_item_price and not self.item_price: raise ValidationError({'item_price': _('If category requires item price - you have to provide it')}) My form class: class NewPaginatedOfferForm(forms.ModelForm): class Meta: model = Offer fields = ('item_price',) def __init__(self, category, *args, **kwargs): super().__init__(*args, **kwargs) self.category = category self.helper = FormHelper() self.helper.form_id = self.__class__.__name__.lower() self.initial['category'] = category self.helper.layout = Layout( Field('page_price'), Field('page_per_day'), Div( Submit('submit', _(Save &rarr;'), css_class="btn btn-lg bold btn-block btn-success", ), ) ) and my view class, based on generic CreateView class: class NewOfferForCategoryView(CreateView): model = Offer category = None template_name = 'web/new_offer_for_category.html' def get_form_class(self): print('get_form_class') if self.category.requires_item_price: return NewPaginatedOfferForm def get_form_kwargs(self): print('get_form_kwargs') kwargs = super().get_form_kwargs() kwargs['category'] = self.category print('kwargs:', kwargs) return kwargs def dispatch(self, request, *args, **kwargs): print('dispatch, ', request.method) try: self.category = Category.objects.get(slug=self.kwargs.get('cat_slug'), available=True) except: print('wrong category') return redirect(reverse('web:new_offer')) print('self category is', self.category) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): print('form_valid') form.instance.category = self.category return super().form_valid(form) … -
get objects from db django
How can I get the objects from the db when I press an a tag? View def product(request): template_name = 'u/product.html' search = {"name":["Mais","Perzik","Brocolli"]} context = {"info":search['name']} return render(request, template_name, context) Template {% for x in info %} <a href="{% url 'product' %}">{{x}}</a> {% endfor %} What I want is how can I, if I press Mais, get the products from the db that has the title Mais? Product.objects.filter(product_name=search??) But where and how do I implement this filter? -
How do I avoid `obj.save()` not to update `updated_at` field?
The title alone seems to be vague. Here is the detail. I have the following Model: class Post(models.Model): title = models.CharField(max_length=100) # deleted for brevity created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) count_visits = models.PositiveIntegerField(default=1) # counts visit time of posts and added the following code in blogs.html: {% if post.created_at == post.updated_at %} Posted {{ post.created_at|naturaltime }} {% else %} Updated {{ post.updated_at|naturaltime }} {% endif %} then I made a simple if statement in DetailView to keep track of number of visitors of a certain post: def post_detail(request, title_slug): obj = get_object_or_404(Post, slug=title_slug) session_key = f'key_{title_slug}' if not request.session.get(session_key, False): obj.count_visits += 1 obj.save() request.session[session_key] = True return render(request, 'blogApp/detail.html', {'post': obj}) Here is the problem, When I create a post, in list view it shows Posted now. but as I click the post to view its detail. It shows Updated now and I think I know what is the problem, when I go to detail view. it creates a session_key, increments obj.count_visits += 1 and save the object obj.save(). When obj.save() is called it updates the database including updated_at field and that is why I get Updated now. How do I solve this? I want to … -
java script loop copmare string JSON
I'm having trouble with comparing a simple loop and if condition here , trying to compare a string from a return Jzon file and compare it . here is my json file "interface": [["enp1s0", "e4:3a:6e:09:bb:d3", "10.0.0.250/24", "fe80::e63a:6eff:fe09:bbd3/64"], ["enp2s0", "e4:3a:6e:09:bb:d4", "192.168.0.250/24", "fe80::e63a:6eff:fe09:bbd4/64"], ["enp3s0", "e4:3a:6e:09:bb:d5", "unavailable", "unavailable"], ["enp4s0", "e4:3a:6e:09:bb:d6", "unavailable", "unavailable"]]} and this is my js code that tries to compare if the the ip address is defined to fill mt table function getinterfaces() { $.getJSON('/getips/', function(data) { // document.getElementById("enp1s0").setAttribute("data-value", data.interface) for (i = 1; i < 3; i++) { if (data.interface[i][2]==='unavailable') { document.getElementById('enp'+ i +'s0').textContent= data.interface[i][2]; } else { document.getElementById('enp'+ i +'s0').textContent= 'NOT ASSIGNED'; } } }); } I have a table to fill from the json file ...... <td><span id="en1ps0"></span></td> ..... <td><span id="en2ps0"></span></td> ..... <td><span id="en3ps0"></span></td> ..... <td><span id="en4ps0"></span></td>...... Thanks in advance -
What is the primary key in user creation django
After the user completes the reCaptcha I have this: if result['success']: user = form.save() firstName = form.cleaned_data.get('first_name') messages.success(request, f"New Account Created: {firstName}") login(request, user) messages.info(request, f"You are now logged in as {firstName}") and django says login(request, user) is an error "Cannot force an update in save() with no primary key." -
django dynamic add extra field in same model
i am trying to build a model where one of the fields is dynamic add extra and i am not sure how to go about it when am writing the view. i will be using Jquery to populate the extra fields but how to capture them as only one field is added to the db. Model: class Holding_Company (models.Model): main = models.CharField (max_length = 32 , null = False , blank = False ) sub = models.CharField (max_length = 32 , null = False , blank = False ) -
Django Custom Template Tag Arguments not Passed Through
I have a custom template tag which accesses a model's method to get items. However, when I pass through the correct amount of arguments, it says I am missing one- get_reminder_items() missing 1 required positional argument: 'remind_list' HTML: {% for list in remind_lists %} <h3>{{ list.title }}</h3> {% get_list_items user.username list as list_items %} {% for item in list_items %} <p>{{ item.title }}</p> {% endfor %} {% endfor %} Custom tag: register = template.Library() @register.simple_tag def get_list_items(authenticated_user, remind_list): return RemindList.get_reminder_items(authenticated_user, remind_list) I have no idea why its doing that, as I have the correct amount of arguments passed through.