Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change django base class's related_name?
I am stuck in this condition: I have two different relation point to the same model, so I have to give the m2m field a related_name. class A(models.Model): b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True,) b_m2m = models.ManyToManyField(B, verbose_name='additional_a', blank=True, related_name="additional_a_group") It works well until I want to inherit it class ABase(models.Model): b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True,) b_m2m = models.ManyToManyField(B, verbose_name='additional_a', blank=True, related_name="additional_a_group") class Meta: abstract = True class A(ABase): pass class C(ABase): pass Now the problem is, B's reverse relation to both A and C have the same related_name additional_a_group and I do not know how to resolve it. If I remove the related_name in ABase, b and b_m2m will conflict. However, if I leave it here, A and C will conflict. I looked back into source code, related_name is used by ManyToManyRel.get_accessor_name. Maybe I could resolve it by overwrite both ManyToManyField and ManyToManyRel, but is there something easier? -
Django urls are not return int, only simplelazyobject as kwargs even when specified
It is my understanding from the documentation, that when using "int:" in a path in a django url, it should send an int to my view in the kwargs. It is sending a simplelazyobject. my urls.py: path('invoices/<int:current_page>/', IndexView.as_view(), name='indexpaged') my views.py current_page = kwargs.get('current_page', 1) print(type(current_page)) output: <class 'django.utils.functional.SimpleLazyObject'> Shouldn't the type be int? If I am misunderstanding the <int:current_page> returning an int, what is the best way to convert from that simplelazyobject to an int? I'm currently using: current_page = int(str(current_page)) to work around it, and this does not seem like it would be the best process. Thanks! -
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'dict'
I saw this question elsewhere, but the answer is not applicable. I am following a course, copying the exact code, yet it doesn't work. Please tell me of any errors. from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Post # Create your views here. def index(request): posts = Post.objects.all() return render(request, 'index.html', {'posts': posts}) def post(request, slug): print(slug) return render('post.html', { 'post': get_object_or_404(Post, slug=slug) }) def about(request): return render(request, 'about.html', {}) This is my exact code, please tell me what I did wrong. I am also new to Django. -
Send email with attachments with django-mailer function send_html_mail()
I'm using send_html_mail() function of django-mailer to send emails in HTML format currently. I'd like to add attachments with the emails but I don't see how to do that in the documentation of django-mailer. I have checked the source code of this function but I don't see any parameters for attachments. Is it possible to add attachments with this function? Or any other way I can use django-mailer to send attachments with HTML emails? -
Where do I add the required positional argument in this Django view?
I'm trying to work with individual customer data within the customers view, so that I can display it on the aggregated list, but am continually running into the following error: TypeError customers() missing 1 required positional argument: 'customer_id' View def customers(request, customer_id): customers = Customer.objects.filter(owner=request.user).order_by('last_name') customer = Customer.objects.get(id=customer_id) # ... snip context = {'customers': customer} return render(request, 'app/customers.html', context) Model class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # ... snip def __str__(self): return f"{self.last_name.title()}, {self.first_name.title()}" URL Pattern urlpatterns = [ # ... snip path('customers/', views.customers, name='customers'), ] -
How to Render contact-from in every view (Django)
Contact-form is placed footer. And most of the different views has footer section. def about-page(request): return render(request, 'about.html') def faq-page(request): return render(request, 'faq.html') def home-page(request): return render(request, 'home.html') All above template have "included" footer section: {% include 'footer.html' %} And this has further included contact-form: {% include 'contact.html' %} So, now if I want to render contact form on all pages, I have to pass it in context. Like: def about-page(request): form = ContactForm() return render(request, 'about.html',{'form':form}) def faq-page(request): form = ContactForm() return render(request, 'faq.html',{'form':form}) def home-page(request): form = ContactForm() return render(request, 'homeabout.html',{'form':form}) Is there any universal function I can do to add form to all pages by not repeating. Because I have way to many pages in whole site. -
Get an attribute of the last record in a django model filtering by user id
I'm trying to get the attribute "query" of the last record in a django model called "conversation" filtering by user id. I used this code but it didn't work : if Conversation.objects.filter(user=request.user, query='question').last: ... and if Conversation.objects.filter(user=request.user).last.query = 'question': ... the conversation model : class Conversation(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) query = models.TextField() response = models.TextField() def __unicode__(self): return self.query def save(self, *args, **kwargs): super().save() Please help me through that and thanks in advance -
Django login not view not displaying
I am using django built-in auth and actually straight up copying code from my own project that works, but must be doing something wrong. I added auth to my main site urls, then I created a login template in PROJECT ROOT/templates/registration/login.html (basically copied from django docs) I added 'templates' to templatedirs in my settings. In my base.html (which all other templates are extended from) I have a link to 'logout' view which seems to successfully logout the user when clicked upon (they were logged in via admin app). Anyone know why after clicking logout, even though I am logged out, it is staying on my 'index.html'? MAIN SITE urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', include('quizapp.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) templates/registration/login.html {% extends "base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif … -
Sending Email as HTML not showing context
I am trying to set a logic so that when a user submits a design, a notification email is sent with the details of the post like Name, Title, Profile etc. I am reached to the part where the email is sent but it is completely blank and empty except that when I typed random text it appeared but anything related to the name of user of post details it is not showing. Here is the model.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) title = models.CharField(max_length=100, unique=True) def __str__(self): return self.title Here is the veiws.py class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'design'] template_name = "post_form.html" success_url = "/score/" success_message = "Your Design has been submitted for Review" def form_valid(self, form): form.instance.designer = self.request.user template = render_to_string("new_design_submitted.html", {'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name, 'post': Post}) msg = EmailMessage('New Design Submitted', template, settings.EMAIL_HOST_USER, [self.request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send return super().form_valid(form) Here is the email template Hi {{ first_name }} {{ last_name }} <--------------- Only `Hi` appears <div class='content_container' style="padding-top: 30px;position:relative;top:50px"> <div class="dcard"> <div class="dcard_header"> <div class="profile_image" > <img class="profile_image" … -
How to disable automatic file upload on django?
Hi I have a column named foto, I use this colum to store the path from my firebase storage so I do not need django storage but every time that I upload my file django generates a new file. from django.db import models from users.models import User class Empleado(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) fecha_contratacion = models.DateField(null=True,blank=True) fecha_nacimiento = models.DateField(null=True,blank=True) curp = models.CharField(unique=True, max_length=200) rfc = models.CharField(unique=True, max_length=200) telefono = models.CharField(max_length=200) foto = models.ImageField(blank=True, null=True, upload_to='fotos/') -
How to pass a complex url to a generic class Update view in django
Im trying to create an update view for my django blog project and I haven't been able to figure it out. I have a model that creates a url based on the date it was posted and the title which also goes through a random slug generator it was given and Im having trouble passing that url to the update view I keep getting the error "AttributeError at /posts2020/7/24/hello-93ej/update/ Generic detail view PostUpdateView must be called with either an object pk or a slug in the URLconf" here is my code models.py class Post(models.Model): STATUS_CHOICES = ( ('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),) title = models.CharField(max_length = 300) slug = models.SlugField(max_length = 300, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared') objects = models.Manager() cleared = PublishedManager() class Meta: ordering =('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) urls.py from . import views from django.urls import path, include from django.contrib.auth import views as auth_views from .views import PostListView, PostCreateView,PostUpdateView app_name = 'posts' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), path('post/new/',PostCreateView.as_view(), name='post-create'), path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'), views.py class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post fields = ['title','body'] def get_success_url(self): return … -
Accidentally deleted thumbnails folder
I am using sorl-thumbnail==12.6.3 to generate thumbnail. Accidentally I deleted thumbnails image folder while actual images of products are still alive. Is there any command to regenerate thumbnails back and map those to correctly. django-oscar==2.1 Django==3.0.8 sorl-thumbnail==12.6.3 -
Django: Custom permissions for group-based model
I'm new to Django and StackOverflow so please be a bit chill with me! I will update the code and everything as per requests. I'm currently working on a system where students can join groups called Societies. These Societies have a ManyToManyField relationship with Users. I have been trying to think of a way to build a system where within each Society, there are Leaders and general members. Leaders can promote members to be fellow leaders, delete posts in the society, or even kick members of the society. I would love some guidance in the right direction on how to structure (or re-structure!) my code. Specifically, I would like to know how to incorporate a "Leader" group of users with custom permissions like the one described above, that I can then use in my templates. Thank you! class Society(models.Model): name = models.CharField(max_length = 200) description = models.TextField() members = models.ManyToManyField(User, verbose_name=("Members")) def __str__(self): return f"{self.name}" class SocPost(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) society = models.ForeignKey(Society, on_delete=models.CASCADE, related_name="posts") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'society_id':self.society.id, 'pk':self.pk}) -
Get count of celery tasks that are running
I'm running celery+gevent like this celery worker -A tasks --pool gevent --concurrency 30 -l info I could get the queued tasks count within redis by: 127.0.0.1:6379> LLEN celery (integer) 83 So pending tasks are stored in celery key with a LIST value and I did get the length by LLEN. Now, what about getting the count of running tasks? how can I achieve this? Thanks in advance. PS: celery inspect active -A tasks did not work when using gevent which im using, it did only with default prefork -
DRF returns empty csv, but json is ok
I am using djangorestframework-csv in my DRF API and i try to specify csv correctly, so user can get correct table (with default settings user will get a table where all objects are specified in 1 row). views.py class MyCSVRenderer(CSVRenderer): header = ['wmi', 'country'] class CarCertainView(ListAPIView): serializer_class = CarSerializer lookup_field = 'wmi' renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + (MyCSVRenderer,) def get_queryset(self): wmi = self.kwargs.get('key', None) print(wmi) cars = Car.objects(wmi=wmi.upper()) content = [{'wmi': car.wmi, 'country': car.country} for car in cars] return content But here is the problem: if i choose json render in browser, its ok: "mark": null, "wmi": "VSA", "add_cod": null, "manufacturer": null, "mark_owner": null, "country_code": null, "country": "Испания", (i didn't specified all fields yet, but fields specified in MyCSVRenderer(CSVRenderer) class are correct in JSON response). But when i choose to request CSV there is only wmi,country , Documentation used: https://github.com/mjumbewu/django-rest-framework-csv -
Sending an Email for a Post Create View not working in an HTML format
I am trying to send an email after a new Post has been submitted but I not getting it right, there is something wrong with my code and I am trying to know how to send email using a Create View. How can I fix this beginner error, how to add a function to automatically send email after a new post is submitted. Here is the views.py class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'post'] template_name = "post_form.html" success_url = "/score/" success_message = "Your Post has been submitted for Review" template = render_to_string("new_post_submitted.html", {'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name, 'post': Post}) msg = EmailMessage('New post Submitted', template, settings.EMAIL_HOST_USER, [self.request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send here is the models.py class Post(models.Model): --------------------------------- title = models.CharField(max_length=100, unique=True) def __str__(self): return self.title -
Django redirect show all details
I have a newbie question. I am passing some values to the index template but via the /ideas/ url of the website. This means, some of the data from the original index view does not show, as we're looking at a different view. How can I achieve the same as the below, but redirecting back to the index & also passing the context in? def ideas(request): idea = request.POST.get('ideasx') if idea == 'itsupport': skills = ['Computer Networking', 'sss'] else: skills = 'sss' return render(request, 'index.html', {'skills':skills}) -
How do I get my pythonanywhere to make changes on my web page after doing hit pull?
I have a problem with updating my code from GitHub to Python Anywhere. I am following Django Girls Tutorial. I've updated some code on my local files and have pushed to GitHub with new commit. I could see the change in my Github repository. Then I tried 'git pull' at Python Anywhere and I saw this message: Updating ebefb9b..75b3566 error: Your local changes to the following files would be overwritten by merge: blog/templates/blog/base.html blog/templates/blog/post_detail.html blog/views.py mysite/settings.py mysite/urls.py Please, commit your changes or stash them before you can merge. error: The following untracked working tree files would be overwritten by merge: blog/templates/registration/login.html Please move or remove them before you can merge. Aborting. So I tried everything but still it didn’t work until I saw a post here on stackoverflow that suggested, git reset --hard before git pull and I applied it and it solved the problem but I couldn’t see changes on my web page. I can only see the Django installation success web page. I have done reload, refresh everything but still can’t get any help. -
Perma-loading fetch using apollo-client
I'm working with my react-native (expo) app and suddenly I cannot seem to connect to my Django server: whenever I launch a query/mutation, it'll just load permanently. I'm using my phone to run the expo app. This is my frontend code: import React, { useState } from "react"; import { AppRegistry } from "react-native"; import * as SecureStore from "expo-secure-store"; import { ApolloProvider } from "@apollo/react-hooks"; import { ApolloClient } from "apollo-client"; import { InMemoryCache } from "apollo-cache-inmemory"; import { createHttpLink } from "apollo-link-http"; import { setContext } from "apollo-link-context"; import Navigator from "./Navigator"; const httpLink = createHttpLink({ uri: "http://192.168.XXX.XXX:8000/graphql/", }); const App = () => { const [token, setToken] = useState(""); const authLink = setContext((_, { headers }) => { // get the authentication token from local storage if it exists (async () => { await SecureStore.getItemAsync("LOGIN_TOKEN").then((data) => { if (data !== null) { setToken(data); } }); })(); return { headers: { ...headers, authorization: `JWT ${token}`, }, }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), }); return ( <ApolloProvider client={client}> <Navigator /> </ApolloProvider> ); }; AppRegistry.registerComponent("MyApplication", () => App); export default App; I checked the follwing things: When I type ipconfig, the IPv4 is the … -
In Django REST framework, how do I tell my serializer to update a member field instead of trying to create it from scratch?
I'm using Django 3 and Python 3.8 along with the Django rest framework. I have the following model. Notice the many-to-many relationship with addresses ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I have created the following serializers. I'm having trouble with updating the model so I exluded the create methods for simplicity ... class AddressTypeField(serializers.PrimaryKeyRelatedField): queryset = Address.objects def to_internal_value(self, data): if type(data) == dict: locality = data['locality'] state = None if not re.match(r"[0-9]+", str(locality['state'])) else State.objects.get(pk=locality['state']) locality['state'] = state locality, created = Locality.objects.get_or_create(**locality) data['locality'] = locality address = Address.objects.create(**data) # Replace the dict with the ID of the newly obtained object data = address.pk return super().to_internal_value(data) ... class CoopSerializer(serializers.ModelSerializer): types = CoopTypeSerializer(many=True, allow_empty=False) addresses = AddressTypeField(many=True) phone = ContactMethodPhoneSerializer() email = ContactMethodEmailSerializer() class Meta: model = Coop fields = '__all__' ... def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, given the validated data. """ instance.name = validated_data.get('name', instance.name) try: coop_types = validated_data['types'] instance.types.clear() # Disassociates all CoopTypes from instance. for item in coop_types: coop_type, _ = … -
django query a model that has a foreign key, checking a property of that foreign key
Let's say I have two models, model_0 and model_1 model_0 is defined as following def model_0: ... foreign_key = models.ForeignKey(model_1) ... and model_1 def model_1: ... random_property = models.Charfield() ... model_1 is a foreign key (could be a manytomany or whatever) in model_0 How can I perform a query in the model_1 objects checking the property of the model_0 Something like model_0.objects.filter(model_0.random_property="Something") I know that you can easily perform queries with the model like model_0.objectsl.filter(model_0="Instance of model 0") But I haven't seen any way to check a specific property of that object -
I'm trying to create a Web App using Django, I've encountered unknown 500 errors I can't debug
This is the error that occurs, it seems to happen when I request a .html file from my templates folder but for some unknown reason to me it fails to show and throws these errors I haven't been able to figure out for a couple days. If additional information is needed I will provide it thank you to anyone who assists Traceback (most recent call last): File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\uknow\Desktop\Coding\GoFishFarms\pages\views.py", line 5, in index return render(request, 'index.html') File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\uknow\Desktop\Coding\GoFishFarms\venv\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html [25/Jul/2020 13:29:40] "GET / HTTP/1.1" 500 82139 -
I got a "'ManyRelatedManager' object is not iterable" error on Django 3.0 on a Queryset thats returns a list of objects
I'm stuck with a TypeError: 'ManyRelatedManager' object is not iterable error in Django 3.0 Here is my problem: I have to models Collection and Element with have a ManyToMany relationship. Here are the models (I obviously omitted all the other attributes and methods which are not related to the problem): class Collection(models.Models): elements = models.ManyToManyField(Element, related_name="collections") @proprety def total_elements_value(self): total = 0 for element in self.elements.all(): # The problem is on this line ! total += element.total_value return total class Element(models.Models): value1 = models.IntegerField() value2 = models.IntegerField() @proprety def total_value(self): return self.value1 + self.value2 But when I try to call the Collection.total_elements_value proprety, I got this error: TypeError: 'ManyRelatedManager' object is not iterable I don't understand. The self.elements.all() return a list as Queryset, so it should be iterable, isn't it ? When I try this in the python shell, this works fine: c = Collection.objects.all()[0] total = 0 for element in c.elements.all(): total += element.total_value return total # Works But not when I call the proprety: c = Collection.objects.all()[0] c.total_elements_value # Throws the error I would like to know how to fix this, but more important, to understand why this doesn't work. Thank you for your help. -
AttributeError("'Manager' object has no attribute 'active'")
AttributeError at /products/all/ 'Manager' object has no attribute 'active' Request Method: GET Request URL: http://127.0.0.1:8000/products/all/ Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'Manager' object has no attribute 'active' Exception Location: C:\Users\Raha\python_projects\booktime\main\views.py in get_queryset, line 49 Python Executable: C:\Users\Raha.virtualenvs\Raha-mxEOCQfG\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\Users\Raha\python_projects\booktime', 'C:\Users\Raha\AppData\Local\Programs\Python\Python38', 'C:\Users\Raha\.virtualenvs\Raha-mxEOCQfG\Scripts\python38.zip', 'c:\users\raha\appdata\local\programs\python\python38\DLLs', 'c:\users\raha\appdata\local\programs\python\python38\lib', 'C:\Users\Raha\.virtualenvs\Raha-mxEOCQfG', 'C:\Users\Raha\.virtualenvs\Raha-mxEOCQfG\lib\site-packages'] Server time: Sat, 25 Jul 2020 20:07:32 +0000 -
How to add django static template tags when generating html using gulp?
Forgive me if this is a silly question but I'm new to web development. I'm generating html files using gulp. It creates relative file paths in the html for assets. For example: <link rel="stylesheet" href="./assets/fonts/feather/feather.css" /> I'm using Django for the backend and I'm trying to get it to recognise the assets directory. One way of doing this is to add the static template tag. For example: <link rel="stylesheet" href="{% static "/assets/fonts/feather/feather.css" %}" /> Is there a way of automatically adding the static template tag whenever generating files using gulp? Or should I be using some other approach? Thanks