Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to embed user_id on the url path
Below I have a photo to help understand better. I have tried different ways to achieve this particular problem, but it has not been achieved till now. I want to embed the user_id on the url of the page, which can be used for tracking for later uses. In the picture, the whole page has been taken screenshot. It has url of the page, username of the current user, product id (which can be seen on the url as well as in the product details part). user_id in the database saves the id of the current user who has added the product. The datatype of user_id in the database is integer datatype and has user_ids ad : 1,2(currently I am working with one superuser and one active user) Below are the files. URLS: urlpatterns = [ path('', views.blink_network), # redirect to root - path path('blink_network/', views.blink_network, name='blink_network'), path('AddNewProduct/', views.AddNewProduct, name='AddNewProduct'), path('blink_viewproduct/', views.showproduct), path('blink_viewproduct/', views.blink_viewproduct, name='blink_viewproduct'), path('affiliation/<int:pk>/update', AffProductUpdateView.as_view(), name='affproduct-update'), path('affiliation/<int:pk>/delete', AffProductDeleteView.as_view(), name='affproduct-delete'), path('link/', views.link, name='link'), path('link/<int:uid>/', views.link_view, name='link_view') ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) VIEWS. #Display only single-user products def showproduct(request): if request.user.is_authenticated: current_user = request.user# define current user result = AffProduct.objects.filter(user=request.user) return render(request, 'blink_viewproduct.html', {'result': result}) def link(request): if request.user.is_authenticated: current_user = request.user# define … -
How do I call a specific field in a model into another model?
I am new to django. I wanted to know if it was possible to call a specific field in a model into another model. The goal is to update a the quantity of a specific product in the database and generate a receipt for it. Here's the example: models.py: class Product(models.Model): name = models.CharField(max_length=300, null=True) price = models.FloatField(null=True) quantity = models.IntegerField(default='0', blank=True, null=True) class UpdateStock(models.Model): date = models.DateTimeField(default=timezone.now) wayBill_Number = models.CharField(max_length=300, null=True) product_Name = models.ForeignKey(Product.name, null=True, on_delete= models.SET_NULL) quantity = models.ForeignKey(Product.quantity, null=True, on_delete= models.SET_NULL) I just want to select the product and the quantity to update in the database but I am unable to do so. -
How to restrict django endpoint to localnetwork?
In my project, I use many FastAPI microservices to conduct the specified tasks and a Django app to handle user actions, connect with the front-end, etc. In Django database I store information about the file paths that a microservice should obtain. I want to provide it to a microservice and this microservice only. So I want to restrict access to the endpoint to a specified port on the local network. Other endpoints should be normally available for the web app. Using just Django cors headers will not work since I want access to most of the endpoints normally and restrict it to localhost for only a tiny subset. CORS_ORIGIN_WHITELIST = [ "http://my_frontend_app" # most of the endpoints available from the front end "http://localhost:9877", #the microservice that I want to provide with the path ] Another solution might be to use from corsheaders.signals import check_request_enabled, but in the use cases that I have seen, it was usually used to broaden the access , not to restrict it (front-end should not have access to the subset of endpoints). I’m not sure whether it is a good solution. # myapp/handlers.py from corsheaders.signals import check_request_enabled def cors_allow_particular_urls(sender, request, **kwargs): return request.path.startswith('/public-api/') check_request_enabled.connect(cors_allow_mysites) Is there … -
AttributeError: type object 'CustomUser' has no attribute 'REQUIRED_FIELDS'
I am trying to create a Custom User model in Django. I am getting error which is if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)): AttributeError: type object 'CustomUser' has no attribute 'REQUIRED_FIELDS' I have added my CustomUser model at settings.py like below. AUTH_USER_MODEL = "Pollapp.CustomUser" Also here is my model.py from django.contrib.auth.models import BaseUserManager, PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser class UserManager(BaseUserManager): def create_user(self, email, firstname, lastname, phone,password=None): user = self.model( email = self.normalize_email(email), firstname = firstname, lastname = lastname, phone = phone, ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email,firstname,lastname,phone,password=None): user = self.create_user( email=email, password=password, firstname = firstname, lastname = lastname, phone = phone, ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(max_length=200, default=uuid.uuid4,unique=True,primary_key=True) email = models.EmailField(null=False, max_length=100,unique=True) firstname = models.CharField(null=False, max_length=100) lastname = models.CharField(null=False, max_length=100) phone = models.IntegerField(null=False,unique=True) date_joined = models.DateTimeField(auto_now=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default = False) is_active = models.BooleanField(default = True) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname','lastname','phone'] objects = UserManager() def __str__(self): return self.email + ", " + self.firstname def has_perm(self, perm, obj = None): return self.is_admin def has_module_perms(self, app_label): return True I also tried to give REQUIRED_FIELDS like … -
crispy form tab has twice the same name
I'm currently using three models: SubBriefe with a foreign key pointing to Briefe SubBriefe has a many to many relationship to SubBriefeField which allows every SubBriefe to point to Subriefefields the problem is that when I use the layout helper to render my tabs of SubBriefe I have inside Tabs of the SubBriefeFields, the probleme is that if SubBriefeField tab "example" is in both Subbriefe the ID to activate the tab doesn't work as it is present two time, do you know the function which will make the css.id unique for every tab in my layout helper as I think it already exists for accordion group. -
django connection issue with mysql from docker container
Django database connection: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'baby', 'USER': 'root', 'PASSWORD': 'Thinkonce', 'HOST': 'host.docker.internal', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', "init_command": "SET foreign_key_checks = 0;" }, } } docker-compose file version: "3" services: web: # network_mode: "host" container_name: antiquely build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: "bash -c 'python manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/antiquely ports: - "8000:8000" volumes: - ./:/usr/src/antiquely watcher: container_name: watcher build: ./ command: "bash -c 'python watcher/app.py'" working_dir: /usr/src/antiquely volumes: - ./:/usr/src/antiquely links: - web celery: build: ./ command: celery -A settings worker -l info volumes: - ./:/usr/src/antiquely links: - web - redis # redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" Here is my database connection and docker-compose file for django application. I am trying to connect with my locally installed mysql database watcher | django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'host.docker.internal' (-2)") I am getting this error Please have a look how can i fix it ? -
Django - how to get inputs from the user and return queryset based by
I want to make kind of a reporting tool for end users, Like if we have a book model in the database, the user will select the author to filter by and will receive a filtered queryset what is the proper way to do this? Is this a proper one?: 1- a form+template | 2- filter the queryset by the inputs | 3- return the queryset if this a right approach how should I get the inputs in the code for filtering? should I use get and post? -
Using period symbol after django-admin startproject <projectname>
I have been following two different tutorials about the Django framework and in one of the frameworks, I entered the following commands: django-admin startproject mysite . In this command, the author specifically asked to enter a period after the command. The following pic is the structure of the folder created:https://i.stack.imgur.com/q3Cab.png In the second tutorial which is on the official Django website, I used the following command: django-admin startproject mysite In this command, I did not use a period in the end and the folder structure is as follows: https://i.stack.imgur.com/aI50z.png. You can clearly see from both the images that one has a single mysite folder with 4 other .py modules inside it, whereas in the other there is another mysite folder inside the mysite folder. Can anyone please explain why there is this difference and which is better for use? -
Speed Optimization in Django
I am building a Blog App and I am also thinking to implement video posts in it. I am trying to optimize the speed of the Web App in Development and also in Production. I have deployed many sites build in Django in last several months on PythonAnywhere. I've noticed that most of site contains simple functionalities like :- Create, Edit, Image Upload, ListView, DetailView of Blogs , etc. With 500 to 600 lines of Code (python). Talking about Development :- When i open a page that contains 100 to 150 Blogs with Images, then it is taking 2 to 3 seconds to open the page AND then i think this may be Because of more blogs and queries then I checked the page's queries and query's Time using Django-Debug-Toolbar then I deleted all the posts except 1 post after that I saw in debug-toolbar, it is showing Total time to load the Page is 600ms. 4 queries in 6 to 8ms I removed some queries but still same results. I also searched about it then i found a Post of optimizing queries using select_related then I also used it BUT I didn't see any much improvement. I used to … -
how to set default value in django template using ajax
i'm trying to set default value to an input field in django template , i have two models tables class Ticketing(models.Model): Title = models.CharField(max_length=40) b = models.DecimalField(max_digits=5,decimal_places=2) #others class Cancel(models.Model): ticket = models.ForeignKey(Ticketing,on_delete=models.CASCADE,related_name="ticket") title = models.CharField(max_length=40) #others forms.py class CancelForm(forms.ModelForm): class Meta: model = Cancel fields = ['title',] my views.py def create_cancel(request,id): booking_obj = get_object_or_404(Ticketing,id=id) form = CancelForm() if request.method == 'POST': form = CancelForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.booking = booking_obj obj.save() return redirect('cancel:create' ,booking_obj.id) context = { ' booking_obj':booking_obj,'form':form } return render(request,'cancel/create.html',context) urls path('create/<int:id>',create_cancel,name='create'), path('ajax/check-title/<int:id>',create_cancel,name='check_title'), i tried to call back title using ajax but it doesnt work @login_required def check_invoice_paid(request,id): obj = get_object_or_404(Ticketing,id=id) data = { 'title':obj.title } return JsonResponse(data) my template $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'{% url 'cancel:check_title' booking_obj.id %}', data:data, success:function(data){ if (data.title){ elm.closest("div.ticket ").find("input.title").val(data.title); } } } ) }) <form action="" method="POST">{% csrf_token %} {{form.errors}} <div id="printDv" class="text-lg"> <p class="p-2 header rounded-lg text-center text-white">Cancel</p> <div class="border border-purple-900 mt-2 rounded-lg p-2 text-center"> <p>no. : {{booking_obj.id}} </p> </div> <div class="ticket border border-purple-900 mt-2 text-center rounded-lg p-2 grid grid-cols-1 md:grid-cols-1 gap-3" dir="ltr" > <p>{{form.title | add_class:'title bg-transparent focus:outline-none w-8/12' }} :title</p> </div> </div> <button class="header … -
Django ListView ignore Order_by in get_Queryset
i'm trying to edit order in a listView through get_queryset() funcion and using order_by() when i try print generated query it's ignore order_by query and uses only the default order in Meta class inside my model class Do you know why that appens? Here my view.py file class TagsListView(ListView): model = Tag paginate_by = 250 ordering = ['-tag'] def get_queryset(self): queryset = Tag.objects.all() queryset.order_by('slug', ) # se presente type nell'url aggiunge il filtro category = self.request.GET.get("category", None) # type = self.kwargs.get('type', None) if category : queryset = queryset.filter( category=category ) search = self.request.GET.get("search", None) if search : queryset = queryset.filter( tag__icontains=search ) print('test ordering') queryset.order_by('slug', 'tag', 'date' ) print(queryset.query.__str__()) return queryset #aggiustare l'url that is my model file # Create your models here. class Tag(models.Model): GENERIC = 0 CONSOL = 1 SOCIETA = 2 SAGA = 3 CAT = 4 ALTRO = 5 CATEGORIES = [ (GENERIC,'Generico'), (CONSOL,'Consol'), (SOCIETA,'Sport'), (SAGA,'Salute'), (CAT,'Categorie'), (ALTRO,'Tempo Libero'), ] tag = models.CharField(max_length=40, unique=True) slug = models.SlugField(max_length=40, unique=True) date = models.DateTimeField(default=timezone.now) category = models.IntegerField(choices=CATEGORIES, blank=True, default=GENERIC) custom = models.CharField(max_length=20, blank=True) class Meta: ordering = ('-date', 'tag') #ordinamento degli elementi pass def __str__(self): #metodo righiesto return self.tag + " - " + self.slug def get_absolute_url(self): return reverse("tags:tag-detail", … -
Not able to connect to django rest server at http://127.0.0.1:8000/
I have used the same code as the tutorial on the drf website When i run python manage.py runserver it gives me this in the terminal Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 10, 2021 - 07:12:08 Django version 3.2.5, using settings 'drftut.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Firefox gives me this error: The connection has timed out The server at 127.0.0.1 is taking too long to respond. The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer’s network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web. I'm also using wsl1 and vscode remote desktop for wsl and im running this inside a python enviroment -
Django rest framework authtoken.views.obtain_auth_token returns ' "detail": "Method \"GET\" not allowed."
projectapp/urls.py from django.urls import path from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('token/', obtain_auth_token), ] So when I try to call this using POSTMAN when it's running locally (using runserver) it returns the token and works correctly, but after deploying on cloud using Nginx on Emperor mode (Using POSTMAN to call the API), it returns' { "detail": "Method \"GET\" not allowed." } This was also discussed in here. So basically my client was not sending a POST request. So I read some docs and discussions and found out that when POSTMAN receives a 301 or 302 on POST request, it tries again with GET. So i ran curl on the server with my username and password, it did return a 301, <html> <head><title>301 Moved Permanently</title></head> <body> <center><h1>301 Moved Permanently</h1></center> <hr><center>nginx/1.18.0 (Ubuntu)</center> </body> </html> So my question is, Why is it working in my local server and not in production? And how do I solve the redirect problem so that it accepts POST and i get the token? I'm a newbie in Django and Web Development in particular here is my project/setting.py Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.register.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.register.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.register.password_validation.CommonPasswordValidator', }, … -
Django + Bootstrap navbar button and search field issue
I know that there are similar questions, but I tried and searched hard and didn't find a solution for my problem. I am using Django + bootstrap to complete an exercise which include a navbar. The search button is stubbornly staying below the search field. I would just like to align them, as in this example : Here my code : ''' </div> <div class="collapse navbar-collapse justify-content-center"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <form class="form-inline my-2 my-lg-0 col-3"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> ''' Don't know if it's a naive issue, but I am really struggling and loosing time with it. Many thanks -
how to make dependent model, from one model to another model in Django
I have 3 models and I want to make all of them depend on each other. I have seen this website, and this is a dependent drop-down list in the same HTML template but I have each new HTML page for each model. So, I have one common field in all the models is code. where code field contains a number of codes like eg.: DD1, DD2, DD3, and so on. So, this code is been there for all three models for eg.: Model motor contains the code field, and in the code field there is code like DD1, DD2, DD3, and also in the drum model contain the code field which is DD1, DD2, DD3 and all the three models have same code field and have matching code. So, now I want to make all three models depend on each other with the help of code. Basically, if the user chooses the motor product which having code as DD4 then if the user goes to another page so the user has to get the DD4 code product from other models. I have done coding like this: views.py def addProductMotor(request): user = request.user motor_id = request.GET.get('motor_id') motor_cart = Motor.objects.get(id=motor_id) Cart(user=user, … -
Django change values() dynamically for each record
I'm trying to get values of student records but change the retrieved values upon conditions (parent). Consider having models.py: class Grade(models.Model): code_name = models.CharField(max_length=10) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') class Group(models.Model): code_name = models.CharField(max_length=10) grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="groups") student_record = models.OneToOneField(Student,null=True,blank=True,on_delete=models.SET_NULL) class Class(models.Model): code_name = models.CharField(max_length=10) grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="classes") student_record = models.OneToOneField(Student,null=True,blank=True,on_delete=models.SET_NULL) class Student(models.Model): male_count = models.PositiveSmallIntegerField() female_count = models.PositiveSmallIntegerField() when I retrieve the student records within a table like below: ____________________________________________ | grade | class or group | males | females | |_______|________________|_______|__________| | | | | | |_______|________________|_______|__________| ** Queryset ** would be something like below: rows = Student.objects.filter(<some condition>).values( '<parent>__grade__codename', '<parent> class or group', # here stands the issue 'male_count', 'female_count', ) I've tried many concepts .. like using Case and When, searched for couple of days and found unanswered questions like this one and tried to make it flat with making a queryset for each (students of classes, students of groups) but still can't make it work. Any Support Will Be Appreciated. -
Django error TypeError: __init__() takes 1 positional argument but 2 were given
I am a bit new to python and I am trying to consume an external API serialized with a serializer class within my Django project and I am getting the below error Traceback (most recent call last): File "lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given "GET /project/v1/mypath/ HTTP/1.1" 500 56241 see my view below import json import requests from rest_framework import viewsets from rest_framework.response import Response from .config import * from .serializer import * BASE_URL = BASE_URL ACCOUNT_URL = "{}/v2/account".format(BASE_URL) ORDERS_URL = "{}/v2/orders".format(BASE_URL) HEADERS = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY} # Create your views here. class AlpacaGetAccountView(viewsets.ModelViewSet): serializer_class = AlpacaAccountSerializer def get_account(self): r = requests.get(ACCOUNT_URL, headers=HEADERS) serializer = AlpacaAccountSerializer(r, many=True) return Response(serializer.data) Honestly, I have no idea where the error is coming from Please advise me on how I can resolve this and where the error is coming from -
How to set nested related fields serializers in Djando Rest Framework?
I'm using Django Rest Framework to build an API where I have the following models of Users making, confirming and showing interest on Events: models.py class User(AbstractBaseUser, PermissionsMixin): user_name = models.CharField(_("user name"), max_length=150, unique=True) slug = AutoSlugField(populate_from='user_name', unique=True) class Event(models.Model): name = models.CharField(max_length=100, blank=False, null=False) owner = models.ForeignKey(User, related_name="owned_events", on_delete=models.SET_NULL, blank=True, null=True) confirmed = models.ManyToManyField(User, related_name="confirmed_events", blank=True) interested = models.ManyToManyField(User, related_name="interested_events", blank=True) to serialize it I used the following code as I found here and at the DRF docs: serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ "url", "user_name", "password", ] extra_kwargs = { "password": {"write_only": True} } class EventSerializer(serializers.HyperlinkedModelSerializer): owner = UserSerializer(required=False) confirmed = UserSerializer(required=False, many=True) interested = UserSerializer(required=False, many=True) class Meta: model = Event lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } fields = [ "url", "owner", "name", "confirmed", "interested", ] It works just fine like that, but I wanted the UserSerializer to show confirmed and interested events of each user just like each event shows the users confirmed and interested. I changed serializers and got the url of each event, like that: serializers.py with HyperlinkedRelatedField on UserSerializer class UserSerializer(serializers.HyperlinkedModelSerializer): confirmed_events = serializers.HyperlinkedRelatedField( queryset=Event.objects.all(), view_name='event-detail', lookup_field='slug', many=True, required=False ) interested_events = serializers.HyperlinkedRelatedField( queryset=Event.objects.all(), … -
Sort Django users by specific groups on the top
All users of the application are mapped to at least one group. Here is list of available groups: >>>Group.objects.all() <QuerySet [<Group: superuser>, <Group: maintainer>, <Group: admin>, <Group: executive>, <Group: client>, <Group: other>]> When I render all the users in the queryset with .all(), I want to sort them with a specific custom order such that, all the Superusers should be on the top, then Admins, then Executives and then rest of the Users as per below list. group_order_list = ['superuser', 'admin', 'executive', 'client', 'maintainer', 'other'] Wondering, how can I use sorted() function on my queryset: class UserList(generic.ListView): model = User queryset = User.objects.all() template_name = 'users/users.html' paginate_by = 10 -
Django: how to make POST request with form data?
I'm learning Django and am running into an issue posting a piece of data to the database. Here's my code: urls.py urlpatterns = [ path("", views.index, name="index"), ... path("listing/<int:listing_id>", views.display_listing, name="listing") ] Models.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usr_bids') price = models.DecimalField(max_digits=5, decimal_places=2) class Listing(models.Model): title = models.CharField(max_length=50) bids = models.ManyToManyField(Bid, blank=True, related_name='bids') price = models.DecimalField(max_digits=7, decimal_places=2) closed = models.BooleanField(default=False) Forms.py class BidForm(ModelForm): class Meta: model = Bid fields = ['price'] views.py def display_listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) if not request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) if request.method == "POST": user = User.objects.get(username=request.user) if request.POST.get("button") == "Watchlist": if not user.watchlist.filter(listing=listing): watchlist = Watchlist() watchlist.user = user watchlist.listing = listing watchlist.save() else: user.watchlist.filter(listing=listing).delete() return HttpResponseRedirect(reverse('listing', args=(listing.id, ))) if not listing.closed: if request.POST.get("button") == "Close": listing.closed = True listing.save() else: price = float(request.POST["price"]) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.price: return render(request, 'auctions/listing.html',{ 'listing': listing, 'form': BidForm(), 'message': 'Increase your bid.' }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.price = price listing.save() else: return render(request, 'auctions/listing.html', { 'form': form }) return HttpResponseRedirect(reverse('listing', args=(listing.id, ))) else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), 'comments': listing.comments.all() }) auction/listings.html <div> <form action="{% url 'listing' listing.id … -
Get the value in queryset in Django template
I have used Django to develop a web app. In the View function, I have rendered a queryset list to frontend. view.py: def render_2(request): query_results_book_is_discard = Material.objects.filter(id=course_id).values('is_discard') return render(request, 'main.html', context={'query_results_book_is_discard':query_results_book_is_discard}) In the frontend, the query_results_book_is_discard variable shows the following format : <QuerySet [{'is_discard': True}, {'is_discard': False}, {'is_discard': False}, {'is_discard': False}, {'is_discard': True}, {'is_discard': True}, {'is_discard': False}]> The query_results_book_is_discard variable is in a loop in frontend Django template, I want to use the forloop counter to get the value(True or False) to use if condition to check. I haved tried: {% if query_results_book_is_discard.counter0 != False %} and {% if query_results_book_is_discard.counter0.is_discard != False %} and {% if query_results_book_is_discard.is_discard.counter0 != False %} All failed. How could I get the True or False value in query_results_book_is_discard to use if condition? -
django how to make POST request ONLY using {% url ' x' %} in HTML
Here is my views.py. from django.shortcuts import render, redirect from .models import Todo from .forms import TodoForm from django.views.decorators.http import require_http_methods def index(request): return render(request, 'home.html') def todoPanel(request): form = TodoForm() todo_list = Todo.objects.order_by('id') context = {'form': form, 'tasks': todo_list} return render(request, 'todo_panel.html', context) @require_http_methods def addTask(request): form = TodoForm(request.POST) if form.is_valid(): task = Todo(task=form.cleaned_data['task']) task.save() return redirect('panel') Here is my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='home'), path('panel/', views.todoPanel, name='panel'), path('addTask', views.addTask, name='addTask') #path('delete_confirm', views.todo_delete, name='delete_confirm') ] and here is my todo_panel.HTML {% extends 'base.html' %} {% block content %} <h1>Todo Panel</h1> <!-- Render the form here--> <form action="{% url 'addTask' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Add"> </form> <!-- Display the todos here --> <ul class="list-group"> {% for task in tasks %} <li class="list-group-item">{{ task }}</li> {% endfor %} </ul> {% endblock content %} I don't want django to redirect me to addTask... I want it to make a POST request. I read the example here https://github.com/PrettyPrinted/django_todo_app and he was able to do it without it redirecting to add. I just want it to make a POST request so it can POST a todo to database. -
Should I Use uWSGI?
I am a newbie to web development. My web application is Django + Nginx. My friend suggested using uWSGI too in case the traffic increases and uWSGI will be able to handle that so the website would not become extra slow. But from what I read, it is Nginx that handles high traffic. So which one? -
NoReverseMatch Error Django Can someone explain how these URL's are failing?
Can someone explain to me how these urls work in django? I'm trying to create a follow/unfollow feature for a twitter clone, the follow is working but when I use the unfollow I am getting the following error. Can someone explain to me why this is failing? I am still learning django and would like to know why this isn't working. NoReverseMatch at /u/fake_account/unfollow/ Reverse for 'foxyprofile' with keyword arguments '{'usersname': 'fake_account'}' not found. 1 pattern(s) tried: ['u/(?P[^/]+)/$'] Here is my code let me know if you need more. foxyprofile.html {% extends 'core/base.html' %} {% load humanize %} {% block content %} <div class="container"> <div class="columns"> <div class="column is-12"> <h1 class="title">{{ user.username }}</h1> <p><a href="{% url 'followers' user.username %}"> Followers: {{ user.foxyprofile.followed_by.count }}</p></a> <p><a href="{% url 'following' user.username %}"> Follows {{ user.foxyprofile.follows.count }}</p></a> <hr /> {% if user != request.user %} {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %} <a href="{% url 'unfollow_foxy' username=user.username %}" class="button is-danger">Unfollow {{ user.username}}</a> {% else %} <a href="{% url 'follow_foxy' user.username %}" class="button is-success">Follow {{ user.username}}</a> {% endif %} {% endif %} </div> </div> <div class="columns"> <div class="column is-8"> <div class="wrapper-fox"> {% for fox in user.foxs.all %} <div class="fox"> <p class="name">{{ fox.created_by.username }}</p> <p>{{ fox.body }}</p> … -
"Authentication credentials were not provided." Thunder client Django Rest
I am trying to restrict dashboard access only, which can be viewed only when the token is passed into the header but... if request.method == "POST": user_name = request.POST['user_name'] name = request.POST['first_name'] lastname = request.POST['last_name'] designation = request.POST['designation'] password = request.POST['password'] email = request.POST['email'] user = MyUser(username=user_name, first_name=name, last_name=lastname) user.set_password(password) user.save() obj = Employee(user=user, first_name=name, last_name=lastname, designation=designation, email=email, isactive=False) obj.save() current_site = get_current_site(request) # mail_subject = 'Activate your account.' # message = render_to_string('Auth/email_template.html', { # 'user': user, # 'domain': current_site.domain, # 'uid': urlsafe_base64_encode(force_bytes(user.id)), # 'token': account_activation_token.make_token(user), # }) # to_email = email # send_mail(mail_subject, message, settings.EMAIL_HOST_USER, [to_email]) obj, create = Token.objects.get_or_create(user=user) return JsonResponse(obj.key, safe=False) login view @csrf_exempt @api_view(['GET', 'POST']) def login_in(request): if request.method == 'POST': name = request.data['first_name'] password = request.data['password'] user = authenticate(username=name, password=password) if user is not None: login(request, user) tok = Token.objects.get(user=request.user) return JsonResponse(tok.key, safe=False) else: print('Not authenticated') return render(request, 'Auth/user.html') Dashboard view @api_view(['GET']) @permission_classes([IsAuthenticated]) def dash_board(request): if request.method == 'GET': print(request.user.is_authenticated) return render(request, 'Auth/dashboard.html', { 'user': request.user, }) Response I am getting from thunder client { "detail": "Authentication credentials were not provided." } I am passing request headers using thunder client in which Authorization header is set to Token d2ed0c39f31bb1c080753bkldd0f4c0ab96b5a07