Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating token in django
I'm very new to django. I'm working on resetting the password with PasswordResetView. I've made all the necessary configurations. All the views are working properly(reset,done,confirm,complete) but the email is not being sent. I'm using file based method. The mail content is also stored in a text file successfully. The text file MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Subject: Password reset on 127.0.0.1:8000 From: webmaster@localhost To: user1991@gmail.com Date: Fri, 08 May 2020 13:07:44 -0000 Message-ID: <158894326451.7060.3441580324173819052@DESKTOP-G46QTJT.localdomain> You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000. Please go to the following page and choose a new password: http://127.0.0.1:8000/accounts/profile/reset-password/confirm/Ng/5gb-4468fc4f5f5c9ad67d90/ Your username, in case you’ve forgotten: test@5 Thanks for using our site! The 127.0.0.1:8000 team ------------------------------------------------------------------------------- But i didn't received the mail. Hoping for a solution. Atleast I want to know how to generate the one time url alone like the one django created automatically. -
Django accessing sublass of model within a form
I have different models in a class and subclasses of them - and I want to create a form for all of them - I know I could do it with a single page for all of them, but is there a smart way to this? models.py: class ProductBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Per part", decimal_places=2, max_digits=6) class Software(ProductBase): link = models.URLField('Download Link', blank=True) class Hardware(ProductBase): shipping_cost = models.DecimalField("UPS", decimal_places=2, max_digits=6) forms.py: class ProductForm(ModelForm): required_css_class = "required" class Meta: model = Product fields = "__all__" views.py: def add_part(request): submitted = False if request.method == "POST": form = PartForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/add_product/?submitted=True") else: form = PartForm() if "submitted" in request.GET: submitted = True return render(request, "gap/add_product.html", {"form": form, "submitted": submitted}) add_product.html: {% extends 'base.html' %} {% block content %} {% if submitted %} <p class="success">Part was saved successfully.</p> {% else %} <form action="" method="post" novalidate> <table> {{ form.as_table }} <tr><td><input type="submit" value="Submit"></td></tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} This way I create the form to save a product in the database in the probably simplest way. Is there any way I can achieve something like a dropdown menu that lets me … -
AttributeError: 'TweetSerializer' object has no attribute 'get_likes'
I am following a series https://youtu.be/f1R_bykXHGE and I am getting error with the code for serializers. Code is working fine but when i tried to add likes = serializers.SerializerMethodField(read_only=True) it's throwing error AttributeError: 'TweetSerializer' object has no attribute 'get_likes'. I am not able find the error. serializers.py class TweetSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content','likes'] def get_likes(self, obj): return obj.likes.count() def validate_content(self, value): if len(value) > MAX_TWEET_LENGTH: raise forms.ValidationError("This tweet is too long") return value #models.py import random from django.conf import settings from django.db import models User = settings.AUTH_USER_MODEL # Create your models here. class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): # id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) #many users can have maany tweets likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) content = models.TextField(null=True, blank=True) image = models.FileField(upload_to='images/', blank=True, null=True) #image bs file timestamp = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.content class Meta: ordering = ['-id'] def serialize(self): return { "id": self.id, "content": self.content, "likes": random.randint(0, 25) } views.py import random from django.conf import settings from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from … -
Why my django code is not sending Email to my newly register user?
I want to verify new user registration by sending confirmation token to email of user. the code is showing no error in console but also not sending the email to user email. i am using django 3.0 and python 3.8. the code is executing this part, when i signup a new user, this message poput but i am not receiving email "Open your email to activate account." help me to fix this: views.py from .forms import CreateUserForm from django.views import View from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.core.mail import EmailMessage from .tokens import activation_token from django.contrib.auth.models import User from django.contrib import messages class RegisterPageView(View): def get(self, request, *args, **kwargs): form = CreateUserForm() template_name = "register/register.html" return render(request, template_name, {"form": form}) def post(self, request, *args, **kwargs): form = CreateUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() message_subject = "Activate your account" domain_url = get_current_site(request) user_email = form.cleaned_data["email"] message = render_to_string( "Backend/accounts/activation_message.html", { "domain": domain_url.domain, "user": user, "uid": urlsafe_base64_encode(force_bytes(user.id)), "token": activation_token.make_token(user), }, ) email = EmailMessage(message_subject, message, to=[user_email]) email.send() activation_msg = "Open your email to activate account." return render( request, "Backend/accounts/activate_email.html", {"activation_msg": activation_msg} ) template_name = 'register/register.html' … -
I want values in single row if job no and invoice no is same
This is my windows look like but i want the values in a single row not multiple rows if job no is same -
Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['catalog/projects/(?P<pk>[0-9]+)/$']
I am trying to figure out why it is that I am getting the following error: NoReverseMatch at /catalog/projects/delete/1/ Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['catalog/projects/(?P<pk>[0-9]+)/$'] Here's the url for the catalog app. I think the problem is from here but I don't seem to be able to figure it out urls.py urlpatterns = [ path('projects/', views.ProjectListView.as_view(), name='list'), path('projects/<int:pk>/', views.ProjectDetailView.as_view(), name='project_detail'), path('projects/new/', views.ProjectCreateView.as_view(), name='project_new'), path('projects/edit/<int:pk>/', views.ProjectUpdateView.as_view(), name='project_edit'), path('projects/delete/<int:pk>/', views.ProjectDeleteView.as_view(), name='project_delete') ] views.py class HomeView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context = { 'projects': Project.objects.all(), 'num_projects': Project.objects.all().count(), 'num_ongoing_projects': Project.objects.filter(status__exact='OG').count(), 'num_clients': Client.objects.count(), } return context class ProjectListView(ListView): context_object_name = 'projects' model = Project paginate_by = 10 class ProjectDetailView(DetailView): model = Project context_object_name = 'project_detail' template_name = 'catalog/project_detail.html' class ProjectCreateView(CreateView): # login_url = '/login/' form_class = ProjectForm model = Project redirect_field_name = 'catalog/project_detail.html' class ProjectUpdateView(UpdateView): fields=('project_title', 'location', 'status', 'start_date', 'end_date') # form_class = ProjectForm model = Project redirect_field_name = 'catalog/project_detail.html' class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('catalog:list') The edit button works fine but the delete button doesn't. It produces that error code project_detail.html {% extends "catalog/catalog_base.html" %} {% block content %} <h1>Welcome to Project Detail Page</h1> <h2>Project details:</h2> <p><strong>Project Number:</strong> … -
Django 2.2 Deleting any user on the admin interface raises this error
Here is the error in question: IntegrityError at /admin/accounts/user/ FOREIGN KEY constraint failed I looked elsewhere and couldn't find any simple fix. This error I believe is because I've used a custom User model where I inherit from AbstractBaseUser because I want my website to not have usernames but instead users are identified primarily by their emails. I am at a beginner level for using Django as well as anything related to relational databases. #src/accounts.models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from django.core.mail import send_mail from django.template.loader import get_template class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), full_name=full_name ) user_obj.set_password(password) # change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.is_active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email,full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name=None, password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_active = … -
Filter by calculated field dependent on foreign key
How to filter django queryset by calculated field dependent on foreign key? This is my models.py: class RealEstate(models.Model): location = models.TextField() @property def is_occupied(self): return Agreement.objects.filter(allocated_house=self, contract_expiration_date__gte=date.today()).exists() class Agreement(models.Model): allocated_house = models.ForeignKey(RealEstate, on_delete=models.CASCADE) contract_expiration_date = models.DateField() I need something like RealEstate.objects.filter(is_occupied=True). Thank you for your time. -
I can't run python manage.py collectstatic?
So I've been trying to fix up an old project of mine made using Django. I've been trying to deploy to heroku and after searching online, someone said I had to run the collectstatic command. But when I do it, this happens (this is after having tweaked loads of stuff in the settings.py): Found another file with the destination path 'admin/js/vendor/select2/i18n/gl.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/js/vendor/select2/i18n/it.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Post-processing 'admin/css/base.7ea12481fb59.css' failed! Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 133, in collect raise processed whitenoise.storage.MissingFileError: The file 'admin/css/fonts.cc6140298ba7.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object … -
Is there possibility for integrating css and html files with django?
i'm working on a personal project that involves full-stack development of a AI Recruiting website.I developed its backend using django.I know basic front end development.(HTML,CSS).But the thing is how to integrate my frontend designs with my django ?. -
Can we create private chat rooms in django channels and send notifications
I am working on my personal project and stuck on a logic I am creating a application in which users can search coding articles posted by another user Once user searches an article, I want to show if the author of that user is online and if the author of that post is online, ask (notification will be sent to) the author for chat and if author accepts the chat connect both of them to a chat room Currently I am not able to do with properly I am using long polling Using django channels Please help me out with this Thanks -
Inserting v-modal attribute form django forms
I have a long form and I use django generated forms. {{form.myfield}} I want to insert v-model attribute form django forms. If in forms.py I do: widgets:{ 'my_field': forms.Textarea(attrs={ "v-model":"value", 'my-attrs':'value1', 'rows':4,} } Only my-attrs is rendered. <textarea name="my_fiels" my-attrs="value1" maxlength="500" cols="40" rows="4" class="textarea form-control">My text goes here</textarea> Is this possible to achieve? I want to do some frontend validation and manipulation and use vue instead of jquery. I now probably it is not the best practice, but in this case I would not need to re-write 50+ forms fields.. -
How to avoid url hitting from browser for Python Django application
I have a Djnago web application and my url looks like path('desgjson/', master.desg_get), and it direct to def desg_get(request): if request.method == 'GET': formm = mMasters.Masters() formm.entity_gid = decry_data(request.session['Entity_gid']) dict_add = formm.get_designation() return JsonResponse(json.dumps(dict_add), safe=False) Now i need the url only be access by the application, and by any browser url hit or from any tool. Thanks. -
BootStrap wokrs well locally yet failed after deploied on PythonAnyWhere
I learn from a tutorial of Django which builds a board. I follow everystep it tells me, and I really build a simple board locally. When I visit 127.0.0.1:8000 it look OK. However, it doesn't works well after I deploied it on PythonAnyWhere. I guess the problem maybe comes from the failing of Bootstrap? I checked some parallel Questions on stackoverflow, and I changed my setting.py to this. Still failed. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Thank you for your help! PS: the source code of this project on github is here: LINK -
How to implement PermissionRequiredMixin in function based view Django?
I can implement PermissionRequiredMixin in class based view but dont know hoe to implement in function based view. Can anybody help me? -
Django orm query access value
Respected Sir/Mam, I have two models want to get value of one model from another.Every this is explained in view.py comments. models.py class Service(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='image', blank = True) #business_profile = models.ManyToManyField("BusinessProfile", blank=True, related_name="business_of_services") def __str__(self): return "Service - {}".format(self.name) class BusinessProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) business_name = models.CharField(max_length=100, unique =True) register_date = models.DateTimeField(default=timezone.now) pan_number = models.IntegerField(unique=True) pan_name = models.CharField(max_length=100) address = models.TextField(max_length=200) pincode = models.IntegerField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) service = models.ManyToManyField("Service", blank=True, related_name="services_of_business") image = models.ManyToManyField("Service", related_name="image_of_business") Views.py service = Service.objects.all() #getting all the services for i in service : print(i.name) # working # Now as services is also connected to bussinessprofile i want to print bussiness_id for this service. print(i.bussiness_id) # something like this -
'crop_image.png' but when i change self.profile_picture.name field name floder create in media file
when i am call self.profile_picture.save() method in under 'crop_image.png' but when i change self.profile_picture.name field name floder create in media file Create your models here. class UserProfile(models.Model): """ This table is join with User table. User profile picture information is save in it""" user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to="profilepic/",default='profilepic/default-user.png', null=True, blank=True) company_logo = models.ImageField(upload_to="profilepic/",default='profilepic/default-user.png', null=True, blank=True) def save(self, args, *kwargs): import numpy as np from PIL import Image, ImageDraw from io import BytesIO from django.core.files.base import ContentFile # Open the input image as numpy array, convert to RGB img=Image.open(self.profile_picture).convert("RGB") npImage=np.array(img) h,w=img.size print('h -w, ===',h,w) alpha = Image.new('L', img.size,0) draw = ImageDraw.Draw(alpha) draw.pieslice([0,0,h,w],0,360,fill=255) npAlpha=np.array(alpha) # Add alpha layer to RGB npImage=np.dstack((npImage,npAlpha)) image_data = Image.fromarray(npImage) new_image_io = BytesIO() image_data.save(new_image_io, format='PNG') # self.profile_picture = new_image_io.getvalue() # self.profile_picture = '../surveyapp_project/media/profile_pic/a1.png' self.profile_picture.save( # 'crop_image.png', # self.profile_picture.name, content=ContentFile(new_image_io.getvalue()), save=False # os.path.basename(self.url), ) img.close() new_image_io.close() super(UserProfile,self).save(*args, **kwargs) -
Django 3.0: Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']
I have model named Book in models.py file. And this model has slug field to display details of books Books are being displayed in home.html template and product.html template is to display details of selected book. I really don't know much about slugs, and how they work. Models.py: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField('Title', max_length=255) authors = models.ManyToManyField(Author, related_name='books_written') publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published') price = models.DecimalField('Price', decimal_places=2, max_digits=10) description = models.TextField('Description') upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True) categories = models.ManyToManyField(Category, related_name='book_category') cover = models.ImageField(upload_to='covers', null=True,blank=True) copyright_proof = models.ImageField(upload_to=book_copyrights_path, null=True,blank=True) slug = models.SlugField(max_length=100,blank=True) def get_absolute_url(self): return reverse("bookrepo:product", kwargs={ 'slug': self.slug }) class Meta: unique_together = ('title', 'publisher') get_latest_by = '-upload_timestamp' def get_authors(self): return ', '.join([author.__str__() for author in self.authors.all()]) def __str__(self): return "Title: {} | Authors: {} | Price: {}".format( self.title, self.get_authors(), self.price ) urls.py app_name = 'bookrepo' urlpatterns = [ path('product/<slug>/', ItemDetailView.as_view(), name='product'), path('',views.home,name='home'), path('about/',views.about,name='about'), path('faq/',views.faq,name='faq'), path('login/',views.user_login,name='login'), path('shop/',views.shop,name='shop'), path('signup/',views.registration,name='signup'), path('logout/', views.user_logout, name='logout'), ] views.py class ItemDetailView(DetailView): model = Book template_name = "bookrepo/product.html" def home(request): bookz = Book.objects.order_by('title') var = {'books': bookz, 'range': 10} return render(request, 'bookrepo/home.html', context=var) home.html <div class="row"> {% load my_filters %} {% for b in books|slice:":10" %} <div class="col-lg-2 col-md-3 col-sm-4"> <div class="item"> … -
I'm trying to deploy Django on Docker in AWS Lightsail, and the pages are stuck loading with no connection to server
I have been trying to deploy a Django app on Lightsail with Gunicorn, NginX, and Docker. I've looked at multiple tutorials, all without success. I'm not familiar with most of the concepts, and I've pretty much been following blindly. So far, everything seems to work on the server itself, but I can't see the results on a webpage. I have configured it for "production" (not sure if I'm even doing it right), and I've added a record to my domain which redirects to this server. The webpage just buffers continuously, even when I try to set it to port 8000 (for development). I think I've gotten a few instances where I saw a "301 5" permanently moved log show up on the docker-compose logs, but that's about it. Here are the Dockerfile, docker-compose.yml, and nginx conf.d file (which are probably the most important. docker-compose.yml version: '3.7' services: web: build: environment: - ENVIRONMENT=production - SECRET_KEY=NOT IMPORTANT - DEBUG=0 - EMAIL_HOST_USER=EMAIL - EMAIL_HOST_PASSWORD=PASSWORD volumes: - .:/code - static_volume:/code/staticfiles depends_on: - db networks: - nginx_network - db_network db: image: postgres:11 env_file: - config/db/db_env networks: - db_network volumes: - db_volume:/var/lib/postgresql/data nginx: image: nginx:1.17.0 ports: - 80:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/code/staticfiles depends_on: - web … -
How to generate a csv file using django ?
Say there's a dataframe whose structure like below: import pandas as pd indexs = {0: ['cost', '2020-01', 'testing'], 1: ['cost', '2020-01', '360 Limited'], 2: ['cost', '2020-02', 'Korea Co.,LTD'], 3: ['cost', '2020-02', 'ADS4EACH HK TECH LIMITED']} columns =[['jim'], ['amy'], ['tom'], ['zara'], ['jay'], ['Lee'], ['Uzi'], ['Zome'], ['Qoe'], ['Aoi'], ['Yeezy'], ['Hazy'], ['Wash'], ['pany'], ['zoey'], ['Moe'], ['total']] data = { 0: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], 1: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], 2: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], 3: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85] } index = pd.MultiIndex.from_tuples(indexs.values()) column = pd.MultiIndex.from_tuples(columns) data = data.values() df = pd.DataFrame(data, index=index, columns=column) print(df) jim amy tom zara ... pany zoey Moe total cost 2020-01 testing 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 7.85 360 Limited 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 7.85 2020-02 Korea Co.,LTD 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 7.85 ADS4EACH HK TECH LIMITED 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 … -
DJango switch between databases
I'm a newbie in python and in DJango, so please, if you can, explain in details. I want to use in DJango 3 databases: 1) For DJango auth, admin etc 2) For local website store 3) For the main database So, frist of all, in my old project (PHP) i was using two databases: *Frist Database ( localdatabase ): -> This database was running on my webhost and contains some variables for the main database *Second Database ( the main database): -> Contains a lot of tables and rows inside which the localdatabase dosn't. So i want to make a script that reads the tables in this order: Auth > Localdatabase > Maindatabase Ex: * Localdatabase have this tables: ->autobrands ->autoparts Maindatabase have this tables: ->AllAutoBrands ->AllAutoParts. I been trying to connect multiple databases, but i don't get it, why is reading only 2 of them. The code is reading the auth database and the local database. I have this code: settings.py DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'gws2', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '', }, 'primary': { 'NAME': 'gws', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '', }, 'secondary':{ 'NAME': 'gwsautqe_ocar890', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'UkVP0qdlle9TKP2z', 'HOST': '46.231.42.12', … -
get parameter value in url Django
I am new to Django, I want to receive a value from the URL and then use it in a filter, but I am having this problem. where value is a field of a model, in the view.py class ModelNumber(generics.ListAPIView): permission_classes = [ IsAuthenticated, ] serializer_class = ModelSerializer def get_queryset(self): queryset = Model.objects.all() value = self.request.query_params.get('value') return Model.objects.filter(value = value) at urls.py path('model_number/(?P<receipt_ballot>\w+)$', views.ModelNumber.as_view()), and Model.py class Model(models.Model): value = models.CharField("Number Value", max_length=12, null=True) -
can anyone make me understand simply
def single(request,slug): pro = products.objects.get(slug=slug) images=productImage.objects.filter(product=pro) template = 'products.html' context = {'pro': pro,'images':images} return render(request, template, context) class products(models.Model): title = models.CharField(max_length=120) desc = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2, default=29.99) sales_price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=False, default=0) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title def get_price(self): return self.price def get_absolute_url(self): return reverse("single", kwargs={"slug": self.slug}) class productImage(models.Model): product = models.ForeignKey(products, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') featured = models.BooleanField(default=False) Thumbnail = models.BooleanField(default=False) active = models.BooleanField(default=True) update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self):`enter code here` return self.product.title what is the task of pro = products.objects.get(slug=slug) and images=productImage.objects.filter(productt=product). what is the difference between using product.productImage_set.all rahter than productImage.objects.filter(product=product) -
Restrict url base Django Api with drf
Hi I want to filter one of my Api models by one field. Building the queryset for the view I need to use the whole model using model.objects.all() and the model serializer. Once I set the filterset which the parameter I want to filter. It filters correctly when I make the consult directly but the problem is when I access to the url for the filter, it by default shows me all the elements of this models and if I search for an element that not exist it also shows al the elements. How can do to make it show me the elements that I'm searching, restrict the url base and if the element doesn't exists in the database just show it empty. Any idea? Thanks -
NoReverseMatch at /each_product/1/
I have an anchor tag in an html template as : <a href="{% url 'each_product' pk=product.id %}"> View</a> In urls.py i have set up the url path as follow for this: path("each_product/<int:pk>/", views.each_product, name="each_product") And in view i have defined the function each_product as: def each_product(request, pk): return render(request, "store/view_each_product.html") I have template named as view_each_product.html. Whenever i try to click view tag , it says "Reverse for 'each_product' with no arguments not found. 1 pattern(s) tried: ['each_product/(?P[0-9]+)/$']" But , when i try to render other templates such as home page , or any other than this ! It doesn't show error.