Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User dashboard on django?
I will explain my final degree project. I want to make a web app that have a public area (front web enterprise), admin dashboard (using jet adming or argon admin panel) and user dashboard. The thing is that... I want to make this enterprise web app and need a user web or dashboard. Django got a public area and admin, but no user. How could make a user interface that uses jet admin template? or simply how could make a user dashboard? This is a test project for my degree but dont know if i can do this on django Thanks a lot of! -
I have a problem with my Django URL pattern naming
For whatever reason when I give a name="..." - argument to a URL pattern and I want to refer to it by using the name it does not seem to work. That's my 'webapp/urls.py' file: from django.urls import path from .views import PostListView, PostDetailView, PostCreateView from .import views app_name = 'webapp' urlpatterns = [ path("", PostListView.as_view(), name="webapphome"), path("post/<int:pk>/", PostDetailView.as_view(), name="postdetail"), path('post/new/', PostCreateView.as_view(), name="postcreate"), path("about/", views.About, name="webappabout"), ] And that's my 'webapp/views.py' file: from django.shortcuts import render from django.views import generic from django.views.generic import ListView, DetailView, CreateView from .models import Post def Home(request): context = { 'posts': Post.objects.all() } return render(request, "webapp/home.html", context) class PostListView(ListView): model = Post template_name = 'webapp/home.html' context_object_name = 'posts' ordering = ['-date'] class PostDetailView(DetailView): model = Post template_name = 'webapp/detail.html' class PostCreateView(CreateView): model = Post fields = ['title', 'content'] template_name = 'webapp/postform.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def About(request): return render(request, "webapp/about.html", {'title': 'About'}) And that's my 'webapp/models.py' file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=300) date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("postdetail", kwargs={'pk': self.pk}) As you can … -
Django User uploaded JPG not being visualized
OK, I've wasted a lot of time on this one and read a lot of other threads on this: I want to visualize a user uploaded profile pic. I'm still on a development server on windows. I can visualize static jpg without any issues. The uploading goes correctly: the jpg is stored in the media folder, but when I try to visualize the jpg, I only get the default jpg icon and a 404 error. I have no idea what's going wrong. Django version 3.0.4 Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' url.py urlpatterns = [ path('', views.index, name='index'), url(r'^creategroup/', views.Groupnew, name='creategroup'), url(r'^createchallenge/', views.NewChallenge, name='createchallenge'), url(r'^updateprofile/', views.UpdateProfile, name='updateprofile'), #url(r'^showprofpic/', views.ShowProfPic, name='showprofpic'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Resulting HTML code /media/profilepics/filename.jpg The actual file is stored in C:(local path)(projectname)\media\profilepics. I also copied the file to C:(local path)(projectname)(appname)\media\profilepics. Anybody has any idea? I feel like I'm not getting the correct path to the file. -
Is there a way to avoid recalculating some values in a recursive many-to-many relationship using django and graphene?
Let's say I have a recursive a many-to-many relationship on one of my Django models, and I'm using graphene_django to query a tree. Something like this: query getTree{ tree{ id active percentage children{ id active percentage children{ ... } } } } Where 'percentage' is a value based on how many of the node's children are active. I could calculate the percentage on each node on their own, but then a bunch of nodes would be calculated multiple times. Is there a way to avoid this? -
Python Django log in with encrypt/decrypt messages
I've used this source code https://github.com/sibtc/simple-django-login. Before logging in I want to display encrypted messages on the log in page, and when logged in I want these messages to be decrypted. I also want the user who is logged in to be able to post another message to these already displayed messages. I will have txt files that will consist of the messages that will be displayed, so when a user posts a new message it will be added to this. I know each time the program is run them posts will be lost but thats okay for what I am currently looking for. The file system the program simple-django-login has slightly confused me as I'm unsure where I should put my python encrypt.py file which will handle the encryption. Any help with this project would be helpful like a drafted encrypt.py file and where it should be placed. Or inputting a form on the html and referencing when a message is posted where should the submit button redirect you. Thanks in advance -
Can't configure Docker + Django with Nginx and Gunicorn
I am trying to run the Django project inside Docker container using nginx and gunicorn. It seems that wsgi server running successfully but when I navigate to localhost (127.0.0.1:8000) the page is not loading. Here is my docker-compose.yml configuration: version: '3' services: app: build: context: . ports: - "8000:8000" env_file: - django.env volumes: - ./app:/app command: > sh -c "python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn -w 4 "app.wsgi -b 0.0.0.0:8000 environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword ports: - "5432:5432" nginx: build: context: . dockerfile: nginx/Dockerfile ports: - 80:80 and nginx configuration: server{ listen 80; server_name localhost; location / { proxy_pass http://app:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } finally console: db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-04-13 10:22:22.719 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-04-13 10:22:22.719 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2020-04-13 10:22:22.833 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2020-04-13 10:22:23.150 UTC [20] LOG: database system was shut down at 2020-04-13 … -
Django translation returns page not found (404) for all secondary languages
I am using Django 3.0.4. I am trying to setup multiple languages in my project but for some reason only the default language is accessible. Here's my setup: settings.py: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGES = ( ('en', _('English')), ('el', _('Greek')), ) LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = False USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) urls.py: from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('superadmin/', admin.site.urls), ] # Enable debug toolbar if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns urlpatterns += i18n_patterns( path( 'dashboard/', include('fusers.dashboard_urls'), name="usersDashboard" ), ) And the result is that I cannot access the dashboard/ without the default language as a prefix: /en/dashboard/ --OK /dashboard/ --404 /el/dashboard/ --404 -
How can I change the returned field metadata type in the json returned by OPTIONS using the Django REST Framework?
I am currently writing an automated script to extract metadata types from my models in Django endpoints which I am trying to hook up to swift. How to pass information about the field data type to the frontend when using Django Rest Framework? The previous question on stack exchange explains how the OPTIONS field can be used to extract the metadata from my models; however, I run into a problem in that not all fields returned are detailed. Particularly, foreign key fields do not specify the correct metadata type. for instance, "created_by_merchant": { "type": "field", "required": false, "read_only": true, "label": "Created by merchant" } "item_size_selection": { "type": "field", "required": false, "read_only": false, "label": "Item size selection" } Both are foreign keys. Created by merchant should be an integer, item_size_selection should be a charfield. Is there any way I can specify the type for particular fields in my OPTIONS? -
why when I add select to <option> django automatically add ="" next to it?
I have this code in template: <option value="{{elem.0}}" {% if elem.0 == def_choice %} selected {% endif %} > {{elem.1|capfirst}} </option> when it is rendered have this result : <option value="profile/images/batata.jpg" selected=""> Batata </option> what is adding the ="" is it django rendering? -
'User' object has no attribute
I just tried to select my API but I got this error. My API http://127.0.0.1:8000/api/user/ My model=> class User(models.Model): userid = models.AutoField(primary_key=True) username = models.CharField(max_length=50,null=False,blank=False,unique=True) phno = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(upload_to='user', blank=True) email = models.EmailField(null=False,blank=False) pwd = models.CharField(max_length=20,null=False,blank=False) created_date = models.DateTimeField(auto_now_add=True) created_usr = models.IntegerField(blank=False,null=False) lastmodified_date = models.DateTimeField(null=True,blank=True) lastmodified_usr = models.IntegerField(null=True,blank=True) class Meta: db_table= 'user' def image_tag(self): # used in the admin site model as a "thumbnail" if len(self.image) <=0 : return '' else: return mark_safe('<img src="%s%s" width="150" height="150" />' % (settings.MEDIA_URL,self.image)) # return mark_safe('<img src="{}" width="150" height="150" />'.format(self.url()) ) image_tag.short_description = 'Image' image_tag.allow_tags = True My Serializer => class Base64ImageField(serializers.ImageField): """ A Django REST framework field for handling image-uploads through raw post data. It uses base64 for encoding and decoding the contents of the file. Heavily based on https://github.com/tomchristie/django-rest-framework/pull/1268 Updated for Django REST framework 3. """ def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid # Check if this is a base64 string if len(data) <= 0 : return '' if isinstance(data, six.string_types): # Check if the base64 string is in the "data:" format if 'data:' in data and ';base64,' in data: # Break out the header from the base64 content header, data = data.split(';base64,') # … -
Unable to import 'misaka' - Django
I am following a tutorial about how to build a social network. I run into this error: IntegrityError at /posts/new/ NOT NULL constraint failed: posts_post.user_id Complete traceback (please note the lines in bold): The above exception (NOT NULL constraint failed: posts_post.user_id) was the direct cause of the following exception: C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\contrib\auth\mixins.py in dispatch return super().dispatch(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in post return super().post(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in post return self.form_valid(form) … ▶ Local vars C:\Users\Tommaso\Django rest framework\Udemy Django\simplesocial\posts\views.py in form_valid return super().form_valid(form) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in form_valid self.object = form.save() … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\forms\models.py in save self.instance.save() … ▶ Local vars C:\Users\Tommaso\Django rest framework\Udemy Django\simplesocial\posts\models.py in save super().save(*args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in save force_update=force_update, update_fields=update_fields) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in save_base force_update, using, update_fields, … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in _save_table result … -
Get _meta of model through relationship
I have two models. I would like to pass one of the models to a function, and then have the function traverse the ManyToManyField to display the related model's fields. class Email(models.Model): subject = models.CharField(max_length=50) body = models.TextField() time_sent = models.DateTimeField(null=True, blank=True) recipients = models.ManyToManyField(Email, related_name='emails') class Contact(models.Model): email_address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) The end result would be something like: >>> get_fields_of_related_model(Email) {'recipients': {'email_address': 'EmailField', 'contact_name': 'CharField'}} >>> get_fields_of_related_model(Contact) {'emails': {'subject': 'CharField', 'body': 'TextField', 'time_sent': 'DateTimeField', 'recipients': 'ManyToManyField'}} -
Where to put excel template file in django project
In my Django application users can get excel file for necessary data. I'm using openpyxl library for manipulating excel files. What i want to do is use an formatted excel file as an template for the file users download. I tryed to put my "template.xlsx" under static and other places but i couldn't reach file anyway. This is how I open my excel file in the correspoding view: filename = r'static\app1\template.xlsx' workbook = load_workbook(filename) Also I'm not sure where to put my excel template file, neither how to get path to it. Thanks for any help. -
Django calling a function
Hello stackoverflow im trying to learn django on my own with taking an online course and im pretty sure im doing all the things right but program keep reporting me an error called ( the class has no object attribute ) I know it means what its says but problem is i think we are calling a function to do work with this class not calling an attribute form the class as you can see in the following code: class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() view = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) published_at = models.DateTimeField(default= timezone.now) def __str__(self): return self.title this is the code for the class and the following code is for the section which makes problems for me: def index(request): articles = Article.objects.order_by('created_at')[:10] return render(request , 'index.html' , { 'title' : 'Articles Page', 'articles' : articles }) def single(request , article_id): articles = Article.objects.get(id= article_id) return render(request , 'single.html' , { 'title' : articles.title , 'articles' : articles }) Both << Article from def index and def single >> giving me this error "Article has no 'objects' member." any tips? -
Django Success URL Gets Appended To Middleware Redirect URL Instead of Redirecting To Success URL
I have a form with a username field on it located at /accounts/choose-username/. views.py from django.views.generic import FormView from .forms import ChooseUsernameForm from django.contrib.auth import get_user_model User = get_user_model() class ChooseUsernameView(FormView): template_name = 'registration/choose-username.html' form_class = ChooseUsernameForm success_url = 'accounts/profile/' # <------------- def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" print(form.cleaned_data['username']) print(self.request.user) user = User.objects.get(email=self.request.user) user.username = form.cleaned_data['username'] user.save() return super().form_valid(form) middleware.py from django.shortcuts import redirect, reverse class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) if request.user.is_authenticated: if request.user.username is None: print(request.path) if not request.path == reverse('choose_username'): return redirect(reverse('choose_username')) return response When I submit the form, my url is accounts/choose-username/accounts/profile/ I want it to be accounts/profile/ MIDDLEWARE settings.py looks like this: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'accounts.middleware.SimpleMiddleware', # <--- 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] My Question Why does my success URL get appended to my accounts/choose-username/ URL? How can I fix it? -
How to update related model fields in Django
I have two models (purchase and stock), I Want when i purchase an item the quantity field in stock to be updated. (eg. i have 2 Mangoes in stock and i purchase 3 Mongoes, i want the updated stock to be 5 Mangoes) My Models class Stock(models.Model): product = models.ForeignKey(Products, null=True, blank=True, on_delete = models.SET_NULL) stock_date = models.DateField(null=True, blank=True) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) class Purchase(models.Model): product = models.ForeignKey(Stock, null=True, blank=True, on_delete = models.SET_NULL) order_date = models.DateField(null=True, blank=True) quantity = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) buying_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank=True) Can anyone help please! -
Django testing - client.cookies empty if there was another test case before
I'm testing my Django application with Selenium in Docker. I encounter a peculiar thing related to cookies availability (I use cookies to authenticate in my tests). Here is the code that works: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from users.models import CustomUser class SomeTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): cls.host = "web" # Docker service name super().setUpClass() CustomUser.objects.create_user(username="user", password="password") def setUp(self): self.browser = webdriver.Remote("http://selenium:4444/wd/hub", DesiredCapabilities.FIREFOX) self.browser.get(self.live_server_url) def tearDown(self): self.browser.quit() def test2(self): self.client.login(username="user", password="password") cookie = self.client.cookies["sessionid"] ... However, when I insert there another test case before test2, let it be something as simple as def test1(self): pass then the code crashes with the following error: Traceback (most recent call last): File "/home/mysite/functional_tests/test.py", line 28, in test2 cookie = self.client.cookies["sessionid"] KeyError: 'sessionid' So the only difference between the working and not-working code is a dummy test function, but what does it change? As far as I know the setUp and tearDown methods make sure that the "environment" is the same for every test case, no matter what happens in other test methods and here it clearly depends on the (non-)existence of other test cases before running my test... Is there something I misunderstand? Or is it some … -
Django Admin Inline hit database multiple times
DjangoVersion:2.1.7 PythonVersion:3.8.2 I have a StoreLocation model which has ForeignKeys to Store, City and Site (this is the default DjangoSitesFramework model). I have created TabularInline for StoreLocation and added it to the Store admin. everything works fine and there isn't any problem with these basic parts. now I'm trying to optimize my admin database queries, therefore I realized that StoreLocationInline will hit database 3 times for each StoreLocation inline data. I'm using raw_id_fields, managed to override get_queryset and select_related or prefetch_related on StoreLocationInline, StoreAdmin and even in StoreLocationManager, i have tried BaseInlineFormsSet to create custom formset for StoreLocationInline. None of them worked. Store Model: class Store(models.AbstractBaseModel): name = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return '[{}] {}'.format(self.id, self.name) City Model: class City(models.AbstractBaseModel, models.AbstractLatitudeLongitudeModel): province = models.ForeignKey('locations.Province', on_delete=models.CASCADE, related_name='cities') name = models.CharField(max_length=200) has_shipping = models.BooleanField(default=False) class Meta: unique_together = ('province', 'name') def __str__(self): return '[{}] {}'.format(self.id, self.name) StoreLocation model with manager: class StoreLocationManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('store', 'city', 'site') class StoreLocation(models.AbstractBaseModel): store = models.ForeignKey('stores.Store', on_delete=models.CASCADE, related_name='locations') city = models.ForeignKey('locations.City', on_delete=models.CASCADE, related_name='store_locations') site = models.ForeignKey(models.Site, on_delete=models.CASCADE, related_name='store_locations') has_shipping = models.BooleanField(default=False) # i have tried without manager too objects = StoreLocationManager() class Meta: unique_together = ('store', 'city', 'site') def __str__(self): return '[{}] {} … -
AngularJS Retrieve nested JSON
I have a loop which loops through my dictionary: for p in place.values(): print(p) jString = json.dumps(p.__dict__) The output looked like this: {"Place": "Liberty City", "time": [{"07:00": 116}, {"08:00": 120}, ...]} I did a print(place.items()). This is the output: `dict_items([('Liberty City', <myapp.models.Place object at 0x0930C150>), ('San Andreas', <myapp.models.Place object at 0x0930C390>`)...] Why am I able to get the Json string but unable to get the value of the dictionary? This is my model: class Location: def __str__(self): s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()] return '\n'.join(s) -
Why depth values in serializer Meta class not work?
I have a serializer serializer.py class VendorManagementUpdateSerializer(serializers.ModelSerializer): ... parent = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) ... class Meta: model = Vendors fields = (..., ...., 'parent', ) depth = 1 class VendorToFrontSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('pk', 'vendor_name') But response data after PUT request return only id fields. And I need to get all the fields out of the serializer VendorToFrontSerializer ('pk', 'vendor_name') Isn't that what depth is used for? I know I can use this type of serializer parent = VendorToFrontSerializer() But the problem is that I use partial_update and when I send this field to the PUT request { "parent":123 } what I get is { "parent": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } How do I do it right? -
Django Graphene form validation with integer field
Here's my simple scenario. I have a model that has two mandatory fields name and age: class Person(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() I'm using Django model form with Graphene class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'age') class PersonType(DjangoObjectType): class Meta: model = Person class PersonMutation(DjangoModelFormMutation): class Meta: form_class = PersonForm class Mutation(graphene.ObjectType): person_mutation = PersonMutation.Field() Lets say a person fills age field but not name field. I can then send a mutation query mutation { personMutation(input: {age: 25, name: ""}) { errors { field messages } } } I get the following response, which is exactly what I want. This response is easy to go through and I get name field validation message. { "data": { "personMutation": { "errors": [ { "field": "name", "messages": [ "This field is required." ] } ] } } } But what if the user fills name but not age? What kind of mutation query should I make? If I make mutation { personMutation(input: {name: "my name"}) { errors { field messages } } } I get the response below. That is a horrible message, I can't show that to user. Also response json format is different than before. … -
Parameters for Post request for form-data in pyresttest
I want to check whether my api is working through pyresttest where we can check testcases, but how can I check testcase to check form-data. My postman looks like: I want to test the api in pyresttest. and where will I keep the file to check it in pyresttest ? -
Django: The page isn't redirecting properly error
I'm getting `the page isn't redirecting properly' coming up in my browser. I'm trying to move an app to be in a sub-folder of another app (because logically it is a special case of that app). This code is causing the loop, but I do not understand why. if administration_instance.study.instrument.form in ['CAT'] : return redirect('cat_forms:administer_cat_form', hash_id=hash_id) My main urls.py have this line: url(r'^form/', include('cdi_forms.urls')), My cdi_forms.urls has this line: url(r'fill/(?P<hash_id>[0-9a-f]{64})/$', views.administer_cdi_form, name='administer_cdi_form'), #I've included this line because it is the url being called in the loop path('cat/', include(('cdi_forms.cat_forms.urls', 'cat_forms'), namespace="cat_forms")), And my cdi_forms.cat_forms.urls has path('fill/<hash_id>/', views.AdministerAdministraionView.as_view(), name='administer_cat_form'), This generates a url /form/cat/fill/614764fa0f135073bc6166ab560882da3a4ed674fcd7f05030583daa1e637230/ which is correct but it is calling the initial function which is at url /form/fill/614764fa0f135073bc6166ab560882da3a4ed674fcd7f05030583daa1e637230/. The difference is the inclusion of cat in the former. Why is it looping? -
How can I disable/remove authorize button in swagger using django
I'm unable to remove authorize button in swagger using Django -
like and comment section: in django
I like to put like and comment section with some info like no. of likes and comment and also show user who comment on it in django project but don't know how can anyone help me her is my html code {% for post in post %} <article class="media mt-4"> <div class="media-body"> <img class="rounded-circle article-img" id="dp" src="{{ post.author.profile.image.url }}"> <div class="article-metadata"> <a class="mr-2" href="{% url 'Love Travel-User' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'User-Posts-Details' post.id %}">{{ post.title }}</a></h2> <img src="{{ post.img.url }}" class="article-img"> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} here views.py class PostListViews(ListView): model = Post template_name = 'userpost/posts.html' context_object_name = 'post' ordering = ['-date_posted'] paginate_by = 7 and models.py class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) anyone can please help me?