Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkbox booleanfield modelform in Django
So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything. models: class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms: from .models import * class TaskForm(forms.ModelForm): title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'})) class Meta: model = Task fields = '__all__' views: def index(request): tasks = Task.objects.order_by('-created') form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'to-do.html', context) html: [![<div class="main-container"> <form method="POST" action="/"> {% csrf_token %} <input type="submit"/> {{ form.title }} </form> {% for task in tasks %} {{ form.complete }} {% if form.complete == True %} <h1><strike>{{task.title}}</strike></h1> {% else %} <h1>{{task.title}}</h1> {% endif %} {% endfor %} </div>] -
Send mail when more than 10 matches are assigned to user in a month
I have two models. A User model and a Match model. A user can subscribe to my service for either 6/12/18 months on any given date. I want to limit a user to a maximum of 10 matches per month. If the user crosses 10 matches in a month, I want to send an alert email. The 10 match quota should reset the following month. How do i achieve this? Following are the models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) MembershipStart = models.DateTimeField(blank=True, null=True, verbose_name="Membership Start Date") MembershipLength = models.IntegerField(verbose_name='Length of membership in months from MembershipStart') class Match(models.Model): user = models.ManyToManyField(User, blank = True) name = models.CharField(max_length = 100) created_on = models.DateTimeField(default=timezone.now) -
PyCharm: ImportError: libmysqlclient.so.20 only when I run django app from IDE
I am working on a simple Django app using PyCharm community edition, python 3.9 and ubuntu 20.04. The project's virtual environment is in folder [project root]/venv/ When I start the app from the pycharm terminal window I execute the following commands and everything works fine (no import errors): source ./venv/bin/activate python manage.py runserver When I start the app from the IDE running configuration, I get an ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory. Given that the project runs via the terminal, I believe that my python installation and my virtual environment are ok. I guess that this should not happen if the IDE run/debug configuration was using the same virtual environment hosted in [project root]/venv/. Therefore, I suppose the run/debug configuration is not correctly configured, or there is something missing in my paths. I have checked other posts but I could not find a solution. The following screenshots depict my run/debug configuration and the setup of my virtual environment in the PyCharm IDE (also showing the respective packages). Could somebody please guide me? Is there a setting in PyCharm IDE that I should check for? Do I miss something fundamental about how do python virtual … -
Webpage using Django opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but the page never loads. I have been using the command python manage.py runserver still the page does not load. Can someone help me with where am I going wrong? -
django nesting TextField within ArrayField for postgres
Django provides a nice to way to write ArrayFields in PGSql: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield eg: class Board(models.Model): pieces = ArrayField(ArrayField(models.IntegerField())) I also see other examples using CharField - which I have used in the past and works just fine. Now, I was wondering if I can do the same with TextField like so: class Board(models.Model): extra_array = ArrayField(models.TextField(blank=True), default=list) Is this legit to do this? Are there any gotachas I need to be aware of? None of the examples seem to use TextField and I wondered why! -
Notifications didn't work for me in django
I try to build a notification system, in which anyone (user) clicks like in the video then send a notification, and after this didn't work for me I don't know why my notification model class Notification(models.Model): NOTIFICATION_TYPE = ((1, 'like')) video = models.ForeignKey("videos.Video", on_delete=models.CASCADE, related_name="noti_video", blank=True, null=True) sender = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPE) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) the notification in the video model class Notification(models.Model): NOTIFICATION_TYPE = ((1, 'like')) video = models.ForeignKey("videos.Video", on_delete=models.CASCADE, related_name="noti_video", blank=True, null=True) sender = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPE) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) the view of the notification def showNotifications(request): user = request.user notifications = Notification.objects.filter(user=user).order_by('-date') template = loader.get_template('notifications/notifications.html') context = { 'notifications': notifications, } return HttpResponse(template.render(context, request)) -
Data retrieval from two models that are related to each other with user model
I have two models that are not related to each other but both of them are related to the user model. // modelA class ModelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(null=False) ... // modelB class ModelB(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) category = models.CharField(null=False) ... When I want to return ModelB information, I need to return the name field of ModelA that their user is the same. How can I do this? I tried several times but to no avail like this: @api_view(['GET']) def retrieve_model_b(request, id): try: from django.db.models import Q _qs = ModelB.objects.filter(Q(company__sahamdar__exact=id)) serializer = SahamdarSerializer(_qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ... Serializer is as follow: class ModelBSerializer(serializers.ModelSerializer): name_of_user = PrimaryKeyRelatedField( source='modela_set', many=False, read_only=True, ) class Meta: model = ModelB fields = ('id', 'name_of_user', 'category') -
Inner join and group by in django REST framework
I am new in Django Rest Framework This is my query in SQL SELECT p7_test.professionals.full_name,count(p7_test.job_applications.pro) totalapply FROM p7_test.professionals inner join p7_test.job_applications on p7_test.professionals.id= p7_test.job_applications.pro group by p7_test.professionals.full_name; I want to do it in Django REST Framework -
How to use Djoser with multiple extended users?
Hello I am new to django django rest framework and djoser I was just wondering. How do I use djoser with multiple extended users. Below is my model, serializers and views. Model: I am trying to inherit user with the student model and teacher model (as seen below). I want djoser to use these two model to create the users. from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='student') age = models.IntegerField() address = models.CharField(max_length=200) def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='teacher') description = models.TextField() def __str__(self): return self.user.username class Course(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField(default=25.00) def __str__(self): return self.name Serializer: My serializer is not finished yet I still have to override the create and update methods. from rest_framework import serializers from api.models import * from django.contrib.auth.models import User class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('age', 'address') class StudentUserSerializer(serializers.ModelSerializer): student = StudentSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'student') extra_kwargs = {'password': {'write_only': True, 'required': True}} class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = … -
Error in Django Channel during WebSocket handshake: Unexpected response code: 500
I was following the this tutorial on youtube. The browser gives an error "(index):21 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/asas/' failed: Error during WebSocket handshake: Unexpected response code: 500 (anonymous) @ (index):21" Code: chatroom.html <script> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); console.log(data) document.querySelector("#user-hello").innerHTML = (data.tester) } </script> chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer), ] chat/comsumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type': 'tester_message', 'tester': 'Hello World', } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data = json.dumps({ 'tester':tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) settings.py STATIC_URL = '/static/' ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
heroku procfile problem : ModuleNotFoundError: No module named 'myApp.wsgi'
I' m deploying my first django app on heroku. After deploy the heroku doesn't launch my app. After checking heroku logs --tail I have got an error: : ModuleNotFoundError: No module named 'tabele.wsgi' My procfile looks like: web: gunicorn tabele.wsgi:application --log-file - I tries also: web: gunicorn tabele:app web: gunicorn tabele.wsgi --log-file - I'm beginner and I don't understand if (in my case 'tabele') should be folder containing manage.py or the different one? In my project folders including manage.py and another one including settings.py and wsgi.py has the same name "tabele" Could you explain me what is what in procfile file for better understanding? Any idea what I'm doing wrong? -
Django get all Model Instances that are within 2 hours of timeframe
As a Django beginner I struggle with a very basic problem: Filter a table based on the date difference of two rows. I have the following model: class DataPoint(models.Model): uid = models.CharField(max_length=128) timestamp = models.DateTimeField(auto_now_add=True) and I want to extract data points that have the same UID and are all within the range of e.g. 2 hours. I could of course use something like: DataPoint.objects.filter(uid=uid, timestamp__range=[timezone.now - timedelta(2), timezone.now]) but that would only return everything within the same 2 hour frame from now, but not dynamically given the DataPoint's timestamp. So this data set: (1) DataPoint: 2021-03-07 12:40 (2) DataPoint: 2021-03-07 11:40 (3) DataPoint: 2021-03-07 10:50 (4) DataPoint: 2021-03-07 08:55 would only return (1), (2), (3) with the query above, even though (4) is still considered connected, as it's within a 2h timeframe of (3). Been trying to get this to work with a RECURSIVE RAW SQL, as I thought this was the only way to do it with Django, but it's not working as expected either. WITH RECURSIVE previous AS ( SELECT id, uid_id, timestamp FROM core_datapoints WHERE id = %s UNION ALL SELECT s.id, s.uid_id, s.timestamp FROM core_datapoints s WHERE uid_id = s.uid_id AND (timestamp - INTERVAL '2 … -
Django group by Many to many in models
I have Model like this Class TaskEntry name = date = goals = models.ManyToManyField(Goal, blank=True) I want to get no of tasks done per goal on per day Example ENtry will be like Task1 5 March goals['Goal1', 'Goal2'] Task2 5 March goals['Goal1', 'Goal3'] Task3 5 March goals['Goal2', 'Goal3'] Task5 5 March goals['Goal1', 'Goal7'] I want result like 5 March Goal1 3 5 March Goal2 2 5 March Goal3 2 5 March Goal7 1 -
NoReverseMatch at /article/add/
I've been building my blog in Django and been able to add a list view and an article detail view but my add view isn't working. I have tried every suggestion I saw online. None of them work for me. Here is my add post HTML {% extends "base.html" %} {% load static %} {% block content %} <br> <br> <br> <div class="container" style="margin-top: 2rem; margin-bottom: 2rem;"> x <h1>Add Blog Post</h1> <form action="{% url 'article-detail' post.slug %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary"> Post </button> </form> </div> {% endblock content %} Here is my urls.py from django.urls import path from .views import ArticleListView, AddPostView, ArticleDetailView urlpatterns = [ path('', ArticleListView.as_view(), name='index'), path('article/add/', AddPostView.as_view(), name='add-post'), path('article/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] Here are my class based views from django.db import models from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post # Create your views here. class ArticleListView(ListView): model = Post template_name = 'index.html' paginate_by = 3 class AddPostView(CreateView): model = Post template_name = 'add_post.html' fields = '__all__' context_object_name = 'post' class ArticleDetailView(DetailView): model = Post template_name = 'article_detail.html' context_object_name = 'post' -
how to can i insert varients and UOM as ManyToManyField
Hello I am trying to build and e-commerce project using django and vue. Here is my Product Model: class UOM(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Varients(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=100, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.IntegerField() brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) img = models.ImageField(upload_to="images/", null=True, blank=True) uoms = models.ManyToManyField(UOM, null=True, blank=True, default="Please Enter UOM") varients = models.ManyToManyField(Varients, null=True, blank=True, default="Please Select Varients") description = models.TextField(max_length=350, null=True, blank=True) def __str__(self): return self.title Here i have UOM and vairents model which i took in product as ManyToMany Field. But i dont know how can i add to cart using django and vue.js Though i can only pass these : HEre is my api.py for add to cart : def api_add_to_cart(request): data = json.loads(request.body) jsonresponse = {'success': True} product_id = data['product_id'] update = data['update'] quantity = data['quantity'] cart = Cart(request) product = get_object_or_404(Product, pk=product_id) if not update: cart.add(product=product, quantity=1, updated_quantity=False) else: cart.add(product=product, quantity=quantity, updated_quantity=True) return JsonResponse(jsonresponse) here is add function for adding a product to a cart def add(self, product, quantity=1, updated_quantity=False): product_id = str(product.id) price = product.price if product_id not in self.cart: self.cart[product_id] = {'quantity':0, 'price': price, 'id': product_id} … -
django.contrib.auth.login does not log the user in
I created a custom User model like the following: class User(AbstractBaseUser): class Types(models.TextChoices): CUSTOMER = 'CUSTOMER', 'Customer' SUPPLIER = 'SUPPLIER', 'Supplier' OPERATOR = 'OPERATOR', 'Operator' base_type = Types.CUSTOMER objects = UserManager() phone = models.IntegerField(unique=True) code = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=20, choices=Types.choices, default=base_type) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return str(self.phone) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin And a manager for the User model: class UserManager(BaseUserManager): def create_user(self, phone, code=663322, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, code=code, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, code=663322, password=None): user = self.create_user( phone=phone, code=code, password=password, ) user.is_admin = True user.save(using=self._db) return user I wanted to have 3 different user types (customer, supplier, operator) so I created 3 profile models and having a OneToOneField to the base user model for each profile model (with some specific fields related to the user type). I also created 3 proxy models like so: class Customer(User): objects = CustomerManager() base_type = User.Types.CUSTOMER class Meta: proxy = True class Supplier(User): … -
Django dj-rest-auth registration
I'm using dj-rest-auth registration, which enables to override register serializer and that's what I'm trying to do. Unfortunately I don't know how I am supposed to do that given my models: class CustomUser(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100, unique=True) date_joined = models.DateTimeField('date joined', default=timezone.now) year = models.IntegerField(blank=True, null=True) university = models.ForeignKey(University, related_name='students', on_delete=models.CASCADE) class RegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=40, min_length=3, required=True ) email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) year = serializers.IntegerField(required=True, write_only=True) def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( "A user is already registered with this e-mail address." ) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def custom_signup(self, request, user): user.year = self.validated_data.get('year', '') user.university = University.objects.filter(name=self.validated_data.get('university', '')) user.save(update_fields=['year']) def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'year': self.validated_data.get('year', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) return user My question is how to add my university foreign key to a register serializer, to enable … -
Rename the default django table
Rename the default django table. I can't change the default table name django_sessions Could anyone help? Thanks for listening model.py from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" -
Exception Value: Field 'id' expected a number but got ''
(I searched this error on stackoverflow and tried the solution ideas bu they did not work.) In my Django Project, I tried to add a like button into my article detail page. If users like the article they click the like button and return the same article page. I saw this video on Youtube and wrote the same code by changing name of the some values according to my project. But I encountered an error which says Field 'id' expected a number but got ''. I read some solutions on Stackoverflow and tried to delete migrations files (except init.py) and then I wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately , it did not work. I want to share my code so maybe, I hope, you can give me some solution ideas. model.py class Article(models.Model): author = models.ForeignKey("auth.User", on_delete = models.CASCADE, verbose_name="Kullanıcı") title = models.CharField(max_length = 50, verbose_name="Başlık") content = RichTextField() created_date = models.DateTimeField(auto_now_add = True, verbose_name="Oluşturma Tarihi") likes = models.ManyToManyField(User, related_name='blog_post') urls.py urlpatterns = [ path('dashboard/',views.dashboard, name ="dashboard"), path('addarticle/',views.addarticle, name ="addarticle"), path('article/<int:id>',views.detail, name ="detail"), path('update/<int:id>',views.updateArticle, name ="update"), path('delete/<int:id>',views.deleteArticle, name ="delete"), path('',views.articles, name ="articles"), path('comment/<int:id>',views.addComment, name ="comment"), path('like/<int:id>',views.LikeView, name ="like_post"), ] views.py def LikeView(request, id): post = get_object_or_404(Article, … -
Django web page opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but he page never loads -
.map is not a function reactjs
So I'm following this tutorial, https://www.udemy.com/course/django-with-react-an-ecommerce-website/, but with some custom HTML template that I made. I keep getting the error .map() is not defined. As the udemy course is more so for Django developers, I am a little lost of the react side. Below is my HomeScreen.js page that is supposed to display products. import React from 'react'; import products from '../products' function HomeScreen() { return ( <section class = "w3l-ecommerce-main"> <div class = "ecom-contenthny py-5"> <div class = "container py-lg-5"> <h3 class = "hny-title mb-0 text-center">Shop With<span>Us</span></h3> <p class = "text-center">Handpicked Favourites just for you</p> <div class = "ecom-products-grids row mt-lg-5 mt-3"> { products.map(products => ( <div key = {products._id} class = "col-lg-3 col-6 product-incfhny mt-4"> <div class = "product-grid2 transmitv"> <div class = "product-image2"> <a href = "#"> <img class = "pic-1 img-fluid" src = "/images/shop-1.jpg"/> <img class = "pic-2 img-fluid" src = "/images/shop-11.jpg"/> </a> <ul class = "social"> <li><a href = "#" data-tip = "Quick View"> <span class = "fa fa-eye"></span></a></li> <li><a href = "#" data-tip = "Add to Cart"><span class = "fa fa-shooping-bag"></span></a></li> </ul> <div class = "transmitv single-item"> <form action="#" method = "post"> <input type="hidden" name="cmd" value="_cart"> </input> <input type="hidden" name="add" value="1"> </input> <input type="hidden" … -
VSCode not auto completing python module import
My VSCode editor suddenly stopped listing suggestion when am running import statements. ie. from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404, HttpResponse normally when I type: from django. it should suggest all packages in django or when I type from django.shortcuts import it again should suggest render, get_object_or_404 etc. But this is not more happening. I have to painstakingly type these out myself. please any help would be highly appreciated. Thanks a lot. -
Including another URLconf doesent work, in parent app
I'm facing a problem in the last few days with Django URLs and include(). I'm doing an toturial online to create a chat app using django, and I'm using the newest version of django. my parent app named mySite, and my sub-app called chat. chat.urls from django.urls import path from .import views urlpatterns = [ path('', views.index), ] chat.views from django.shortcuts import render def index(request): return render(request , 'chat/index.html') . ##########################################################################################3 I'm trying to include the chat.URLs in the parent app mySite.urls but I'm getting an error page after I runserver. i tried to migrate and still is not working. mySite.URLs from django.contrib import admin from django.urls import path from django.urls import include from chat import urls urlpatterns = [ path('admin/', admin.site.urls), path('chat/', include('chat.urls')), ] -
How to fix slugs implemented in Django?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having great difficulty with the following: For each subject page I would like the url to include ~/subject_slug/ Currently I am getting ~/subject/subject_slug When I eliminate subject/ from urls.py (line 8), I get the desired ~/subject_slug only. HOWEVER, the individual posts cannot now be accessed. Error: Subject.DoesNotExist: Subject matching query does not exist. Line 21 in views.py is pointed to. There I have tried to include either Subject, or subject, in the bracket before subject_slug=subject_slug. Unfortunately that shows: UnboundLocalError: local variable 'subject' referenced before assignment. Attempts with adding subject to the post_detail view have also not worked. For each post I would like the url to include ~/subject_slug/slug/ Therefore I added str:subject_slug/ to urls.py line 10. This throws the error: NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '('a-slightly-longer-post',)' not found. 1 pattern(s) tried: ['(?P<subject_slug>[^/]+)/(?P[^/]+)/$']. models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify class Subject(models.Model): subject = models.CharField(max_length=200) subject_slug = … -
Connect uploaded file to a post in Django
I am trying to connect an uploaded document with the related post in Django. The idea is that when a user creates a post (I called it seed in my code), he can upload a document with it if he wants to. I tried using the joint method to do so, but it is not working (either telling me it expects an "str" and not an "int" or telling me the ForeignKey condition is not working). Is there any way to then connect those two classes, and successfully upload a file? Thank you for any help!! Here is what I tried: views.py """ def seed_create(request): if request.method == "POST": seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) if seed_form.is_valid() and docu_form.is_valid(): seed_form.instance.user = request.user docu_form.save() seed_form.save() messages.success(request, 'Your seed was successfully created!') return redirect('seed:view_seed') else: messages.error(request, 'Please correct the error below.') else: seed_form = SeedForm(request.POST) docu_form = DocumentForm(request.POST, request.FILES) return render(request, "seed/create.html", context={"seed_form": seed_form, "docu_form": docu_form}) """ models.py """ def gallery_folder(instance, file): return '/'.join(['documents', instance.seed_related_id, file]) class Document(models.Model): seed_related = models.ForeignKey(Seed,on_delete=models.CASCADE,default=1) description = models.CharField(max_length=255, blank=True) file = models.FileField(default="No file",upload_to=gallery_folder) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title """ forms.py """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'file') """