Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the detailed page by slug and not id in Django Rest Framework class based views
I am building an API using Django Rest Framework. I have the /api/localities endpoint where all of the objects on my database are displayed. Now I want to create the endpoint for a single page of a particular locality, and I want to make it by slug and not id for example /api/localities/munich. I am using Class based views and right now I can get the single page by id, for example /api/localities/2, but I want to change that to the slug. How can I do this? Here is my code: models.py class Localities(models.Model): id_from_api = models.IntegerField() city = models.CharField(max_length=255, null=True, blank=True) slug = models.CharField(max_length=255, null=True, blank=True) postal_code = models.CharField(max_length=20, null=True, blank=True) country_code = models.CharField(max_length=10, null=True, blank=True) lat = models.CharField(max_length=255, null=True, blank=True) lng = models.CharField(max_length=255, null=True, blank=True) google_places_id = models.CharField(max_length=255, null=True, blank=True) search_description = models.CharField(max_length=500, null=True, blank=True) seo_title = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.city serializers.py from rest_framework import serializers from .models import Localities class LocalitiesSerializers(serializers.ModelSerializer): class Meta: model = Localities fields = ( "id", "id_from_api", "city", "slug", "postal_code", "country_code", "lat", "lng", "google_places_id", "search_description", "seo_title", ) views.py from django.shortcuts import render from django.http import HttpResponse from wagtail.core.models import Page from .models import LocalityPage, Localities from django.core.exceptions import ObjectDoesNotExist from … -
trying to link css in html file for a django project
Directories Attached is a photo of my directories. Am am trying to use sudokuStyle.css in sudoku_board.html. However, it does not seem to make the connection in my html file. I am including my head for the HTML. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sudoku Solver</title> <link rel="stylesheet" type="text/css" href="{% static 'css/sudokuStyle.css' %}"> </head> Where could I be going wrong? I have tried a variety of ways to connect but it does not work. -
How to align text or url in Django template? - Python Crash Course, Project "Learning Log"
I am creating "Learning Log" Django web-application using "Python Crash Course, 2nd edition" book. But since I reached 20th chapter of the book, I started having problems. I created a template, that displays all entries of the particular topic. On the page we have entry title, date, a button to edit it, and of course its text. Following the book, I use bootstrap4 to make pages looks more beautiful. But I would like to align the entry date and the "edit entry" url to the right side. I tried style="text-align:right;" , but it doesn't work. I am really new to web development , so I beg you to not judge me strictly :) Page with topic and its entries topic.html {% extends 'learning_logs/base.html' %} {% block page_header %} <h3>{{ topic }}</h3> {% endblock page_header %} {% block content %} <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">Add a new entry</a> </p> {% for entry in entries %} <div class="card mb-3"> <h4 class="card-header"> {{ entry.title }} <small style="text-align:right;"> {{ entry.date_added|date:'M d, Y'}} <a style="text-align:right;" href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </small> </h4> <div class ="card-body"> {% if entry.text|length > 500 %} {{ entry.text|linebreaks|truncatechars:500 }} <p><a href="{% url 'learning_logs:entry' entry.id %}">Read more</a></p> {% … -
How to authenticate to Geonode api v2?
Im am creating a geonode-project app and I want to authenticate to the Geonode API v2, but I cannot find an endpoint to authenticate. I listed all endpoint of the api using http://localhost:8000/api/v2/ but I cannot find and endpoint to authenticate. How can I authenticate to the Geonode REST API? -
How to redirect Django button for loop in HTML to specific HTML page for that service?
Im working on a django project but got stuck here. I have a for loop which loops through the data from a model, basically looping in services which are offered and creating buttons for these. I would like to redirect the button to a specific page for only this service. So basically each service offered gets an own button and if clicked gets redirected to a page for this service only. As I add the link in an anchor I don't know how to get it from the for loop in HTML doc. How should I code this to get the desired result? MODEL: class ServiceTypes(models.Model): typ = models.CharField(max_length=255, primary_key=True, blank=False) pris = models.DecimalField(decimal_places=0, max_digits=6, null=False, blank=False) beskrivning = models.CharField(max_length=255, null=True, blank=True) VIEWS: def boka_service(request): services = ServiceTypes.objects.all() return render(request, 'main/boka.html', {'services': list(services)}) THE HTML PART: {% for r in services %} <a href="{% url 'homepage' %}"> <button class="button_x"> <p style="margin-top: -60px; font-size: 15px; font-weight: bold;">{{ r.typ }} {{ r.pris }},- kr</p> <p>{{ r.beskrivning }}</p> </button></a> {% endfor %} -
How to merge two queryset based on common key name in django
Lets say i have 2 QuerySet: <Queryset [a, b, c]> and <Queryset [a, d, e]> How can i merge those two to achieve : <Queryset [a, b, c, d, e]> -
django.db.utils.IntegrityError not solving this part
I need a help regarding django.db.utils.IntegrityError: I read similar questions on stackoverflow before posting a new question, but I could not find the right solution. Basically, I am following a course, let's say copy-pasting the code in models.py, serializers.py views.py And whenever I call python manage.py migrate, I get this error: django.db.utils.IntegrityError: The row in table 'LittleLemonAPI_menuitem' with primary key '1' has an invalid foreign key: LittleLemonAPI_menuitem.category_id contains a value '1' that does not have a corresponding value in LittleLemonAPI_category.id. Anyone can help, how could I fix that error? The strange part is, that I literally follow each step on the course, it isn't even my code, and I can't figure out what's wrong. I tried to delete all migration related files and db.sqlite3, but in that way I lose all the previously entered data. I tried changing the part from on_delete.PROTECT, default=1. into. on_delete.CASCADE and removing default1, but nothing worked. -
Django form start date and date validation
I am trying to validate that the end date is greater than the start date. This is a form editing an entry submitted in a previous form. The startdate field has already been populated. This function was written based on Django documentation: [https://docs.djangoproject.com/en/4.1/ref/forms/validation/] When I submit the form there is no error thrown. Is this function called simply by submitting the form? What am I missing? ` class EditForm(ModelForm): class Meta: model = Cast fields = [ 'enddate', ] def clean(self): cleaned_data = super().clean() start_date = self.cleaned_data.get('startdate') end_date = self.cleaned_data.get('enddate') if end_date < start_date: raise ValidationError("End date must be greater than start date") ` I was expecting to see the error "End date must be greater than start date" In reality, the form submits no problem with an end date that is less than the start date. -
Django relation of models
I have an e-commerce project and I stuck at admin view. I have 2 models, namely Order and OrderItem. They are connected with FK relationship, and when Order is created I create both Order and related OrderItems in my admin page. Orders in admin page: OrderItems in admin page: When I open my OrderItems, I see my OrderItem belongs to which Order. I want to add Order# to my OrderItem# list in my admin page. In other words: I want to express "OrderItem.str" = "existing OrderItem.str" + "Order.str" My desired OrderItem__str__ format is something like: OrderItem#4-Order#2 views.py file: if request.user.is_authenticated: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost, user=request.user) order_id = order.pk for item in cart: order_item = OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user) # Update stock product = Product.objects.get(title=item['product']) product.stock_qty -= int(item['qty']) product.save() models.py file: class Order(models.Model): full_name = models.CharField(max_length=300) email = models.EmailField(max_length=255) shipping_address = models.TextField(max_length=10000) amount_paid = models.DecimalField(max_digits=8, decimal_places=2) date_ordered = models.DateTimeField(auto_now_add=True) # Foreign key (FK) # Authenticated / not authenticated_users user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class Meta: # Update admin view label verbose_name_plural = 'Orders' # Admin list view of order records def __str__(self): return 'Order - #' + str(self.id) class OrderItem(models.Model): # Link Order to Orderitem class # … -
Django forms dont displaying all fields
I have a problem, i need to create form like scheme, i have my models and created forms.py.When i add my forms into the HTML, i have only 2 of all fields in my forms.What it can be? This is my models.py class Post(models.Model): full_name = models.CharField(max_length=60, verbose_name='Full name'), name_scheme = models.CharField(max_length=40, verbose_name='Name of scheme') job = models.CharField(max_length=100, verbose_name='Job'), email = models.EmailField(verbose_name='Email'), domain_name = models.CharField(max_length=100, verbose_name='Domain'), phone_number = PhoneNumberField, company_name = models.CharField(max_length=30, verbose_name='Company name'), text = models.TextField(max_length=255, verbose_name='Text'), age = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(65)]) address = models.CharField(max_length=255, verbose_name='Address'), created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name forms.py class AddSchemeForm(forms.ModelForm): class Meta: model = Post fields = '__all__' views.py def add_scheme(request): if request.method == 'POST': form = AddSchemeForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = AddSchemeForm() return render(request, 'add_scheme.html', {'form': form}) -
TypeError at /accounts/add_rent_payment/1363902a-c341-4883-84ee-1e12156b0381
I have two model namely Receipt and RentPayment. What I want to achieve is for me to create a Receipt, I want to redirect to a RentPayment form with a initial value of the recently saved receipt in the receipt field. #Models class Receipt(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) receipt_number = models.CharField(max_length=4, null=True, blank=True) property = models.ForeignKey(Property, null=False, blank=False, on_delete=models.CASCADE) month_paid = models.CharField(max_length=15,null=True,blank=True,choices=MONTHS) balance_due = models.DecimalField(max_digits=5, decimal_places=2) total_rent = models.DecimalField(max_digits=7, decimal_places=2, null=True,blank=True) class RentPayment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) receipt = models.ForeignKey(Receipt, null=True, blank=True, on_delete=models.CASCADE) property = models.ForeignKey(Property, null=True, blank=True, on_delete=models.SET_NULL) amount_paid = models.DecimalField(max_digits=7, decimal_places=2) payment_date = models.DateField(auto_now=True) next_payment_due = models.DateField(auto_now=True) #Views def createReceipt(request,pk): property_entity = Property.objects.get(id=pk) form = ReceiptForm(initial={'property' :property_entity}) if request.method == 'POST': form = ReceiptForm(request.POST, initial={'property' :property_entity}) if form.is_valid(): receipt_obj = form.save(commit=False) receipt_obj.property = property_entity receipt_obj.save() return redirect('add_rent_payment', receipt_pk=receipt_obj.id) else: ReceiptForm() context = {'property_entity' :property_entity, 'form' :form } return render(request,"accounting/receipt.html",context) def add_rent_payment(request, pk): receipt = Receipt.objects.get(id=pk) if request.method == 'POST': rent_payment_form = RentPaymentForm(request.POST) if rent_payment_form.is_valid(): rent_payment = rent_payment_form.save(commit=False) rent_payment.receipt = receipt rent_payment.save() return redirect('property_list') else: rent_payment_form = RentPaymentForm() context = { 'receipt': receipt, 'rent_payment_form': rent_payment_form, } return render(request, 'accounting/add_rent_payment.html', context) #urls urlpatterns = [ path('receipt/<str:pk>', views.createReceipt, name="receipt"), path('add_rent_payment/<str:receipt_pk>', views.add_rent_payment, name="add_rent_payment") ] -
Obtaining a refresh token from gapi auth2
I have the following use case: I have a Django REST + Vuejs application in which users log in using Google OAuth 2. Once they've logged in, there are some actions that they might perform which require them to grant my application extra permissions, i.e. more scopes than they originally gave permission for when logging in. These applications are performed on the backend, which will send Google services requests authenticating as the users, so I need to somehow store the access tokens, which have also been granted specific scope permissions, on my backend. In order to implement this flow, I thought about following the guide on incremental auth and do the following: const option = new gapi.auth2.SigninOptionsBuilder(); option.setScope(ADDITIONAL_SCOPES_TO_REQUEST); const googleUser = auth2.currentUser.get(); const res = await googleUser.grant(options) const response = res.getAuthResponse() The response variable will hold an object which, among the other properties, has the access_token returned by Google. After that, I can issue a request to my Django backend to create an instance of some GoogleAccessToken model which will hold the token returned by Google and use it for authenticating server-to-server requests to Google services. The idea is to use it this way: from google.oauth2.credentials import Credentials from .models … -
How to properly create recursive comments in templates django?
I want to create a tree like comment section in my site, but I can't handle to work it as expected. I just ended up with a mess there, but it seems to me that model works perfectly.. Maybe I am wrong, but I assume there is a template logic problems. I've attached a screenshot of how it looks now. As you can see, comments are duplicating each other and do not construct a tree like stuff. Can somebody point me in the right direction? Models.py class Comment(models.Model): user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField(max_length=255) comment_to_reply = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='replies') created_at = models.DateTimeField(auto_now_add=True) comments_template.html {% if post.comments %} {% for comment in post.comments.all %} <a name="comment-{{ comment.id }}"></a> <div class="row" id="{{ comment.id }}"> <div class="shadow-sm mb-3 card border-0 p-3 bg-light"> <div class="panel-heading"> <strong>{{ comment.user.username }}</strong> <a href="#comment-{{ comment.id }}"></a> <small class="text-muted">{{ comment.created_at }}</small> </div> {% if form %} <div class="row"> <div class="col-10">{{ comment.body }}</div> <div class="col text-end"> <a class="btn btn-primary btn-sm" onclick="return show_comments_form({{ comment.id }})">Reply</a> </div> </div> {% else %} <div>{{ comment.body }}</div> {% endif %} </div> </div> {% if comment.replies %} <div class="offset-md-3"> {% for comment in comment.replies.all %} <div class="row"> … -
How display circleMarker data using several colors?
How display circleMarker data using several colors according to magnitude value. For example this map (https://cartonumerique.blogspot.com/2023/02/seismes-en-Turquie-et-Syrie.html)? Here is my map function and my map script. #views.py def data(request): all_evens = Even.objects.all() _data = [[obj.name, obj.date, obj.latitude, obj.longitude, obj.magnitude] for obj in all_evens] return JsonResponse (_data, safe=False) #evenmap.html <!DOCTYPE html> {% load static %} <html lang ="en"> <body> </body> {% block js %} <script> var even = L.layerGroup() $.ajax({ url:"{% url 'even:data' %}", type:"GET" success: function(response){ response.forEach(obj =>{ L.circleMarker([obj[6], obj[7]], { radius: obj[8] * 3, fillColor: "#ff7800", color: "#000", weight: 1, opacity: 1, fillOpacity: 0.6 }).bindPopup('Name: ' + obj[0] + '</br>' + 'Date: ' + obj[1] + '</br>' + 'Latitude: ' + obj[2] + '</br>' + 'Longitude: ' + obj[3] + '</br>' + 'Magnitude: ' + obj[4] ).addTo(even) }); }, error: function(response){ alert(response.statusText); } }); </script> {% end block js %} </html> -
Does anyone used Django-postman for implementing private chat?
Iam newbie to programming as well as in Django framework, recently i am creating a website that user can chat 1 to 1 "private chat" i found lot of tutorials, like creating Django chat with django-channels every on of them are creating with chatroom, i like to implement 1 to 1 chat. is there any tutorial in Django-postman or does anyone created chat with django-postman? if you anyone came across any alternative that would be helpful. Any advice will helpful. -
Django ORM sort by column, descending, drop dublicates and give the top 5
I want to query the top 5 products of a table but they must be unique on the product column, when they have the same value for the column sodium. So its basically sort values by column sodium, show result descending then drop dublicates based on product and only show the first 3 results. I managed to do this on a pandas dataframe but how can i query this via a Django Modell ORM? This is my example tabel: brand product flavour sodium 1 01 twister Tomato 09 2 01 twister Cheese 15 3 01 crumble Apple 07 4 02 cream herbs 17 5 02 cream orange 17 6 03 chips smashed 23 7 03 chips salt 23 8 03 chips vanilla 23 wished Output brand product flavour sodium 7 03 chips salt 23 4 02 cream herbs 17 2 01 twister Cheese 15 At the moment i get this result brand product flavour sodium 7 03 chips salt 23 6 03 chips smashed 23 8 03 chips vanilla 23 Thats what i tried top_product_sodium = Product.objects.all().order_by('-sodium')[:5] -
httprequest sending json to backend error
I'm new to django. I am trying to send a post request to server but somehow got an error. When I tried it in postman it works. I tried console.log and it works fine. console.log : "username":"12345","password":"hahaha","re_password":"hahaha" react code : const handleSubmit = (event) => { event.preventDefault(); const requestBody = JSON.stringify({ username : Id, password : Password, re_password : Re_Password, }); console.log(requestBody) fetch('http://localhost:8000/api/csrf_cookie'); fetch('http://localhost:8000/api/register', { method: 'POST', headers: { 'Content-Type' : 'application/json', 'X-CSRFToken': cookies['csrftoken'], body: requestBody,} }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); }; Output python : Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 134, in _wrapped_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Kerja\Freelance Web … -
How to access django model using JS?
I'm trying to create a e-commerce app and I'm trying to block users not to request more items than in stock. Therefore, I wanted to add some JS to control user. However, although I tried to use answers from other posts, I failed. In my HTML file, I'm sending products and I'm displaying properties of each product using for loop: HTML source code: <main class="pt-5"> <div class="row g-3"> <div class="col-md-5 col-lg-5 order-md-first bg-light"> <div class="mainImage"> <img class="img-fluid mx-auto d-block" alt="Responsive image" src="{{ product.image.url }}"> </div> <ul class="thumb"> <li> <a href="{{ product.image.url }}" target="mainImage"><img src="{{ product.image.url }}" alt="Product Image"></a> {% for im in product_gallery %} <a href="{{ im.image.url }}" target="mainImage"><img src="{{ im.image.url }}" alt="Product Image"></a> {% endfor %} </li> </ul> </div> <div class=" col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4"> {{ product.title }} </h1> <strong> {{ product.brand }} </strong> <hr> <br> <p> {{ product.description }} </p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6"> Price </div> <div class="col-6 text-end"><span class="h4 fw-bold">$ {{ product.price }} </span></div> </div> </div> {% if product.stock_qty >= 1%} <div class="col"> <div class="row p-3"> <div class="col-6"> <button type="button" id="qty-decrease-button" class="btn btn-primary btn-sm"> - </button> &nbsp; <label id = "qty-show" for="select" value="{{ product.id }}">1</label> &nbsp; <button type="button" … -
What is the difference between CsrfViewMiddleware and enforce_csrf?
I am trying to apply CSRF token in Django. I am applying csrf token using middleware and custom authentication. But I think I'm doing the same process twice. Because the value of csrf_token from cookie and response is different. Is it okay to apply+check csrf token by middleware only? MiddleWare settings.py CSRF_COOKIE_SECURE = True # CSRF cookie enabled only Https server CSRF_COOKIE_HTTPONLY = True # CSRF stored in http only cookie CSRF_TESTED_ORIGINS = [ "http://localhost:8000" ] CSRF_COOKIE_SAMESITE = "Lax" # Samesite "Lax" - Protection against csrf attacks MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware' ] enforce csrf during authentication authenticate.py (I have set CustomAuthentication as DEFAULT_AUTHENTICATION_CLASSES) from rest_framework_simplejwt import authentication as jwt_authentication from django.conf import settings from rest_framework import authentication, exceptions as rest_exceptions def enforce_csrf(request): check = authentication.CSRFCheck(request) reason = check.process_view(request, None, (), {}) print(check, reason) print(request.META) if reason: raise rest_exceptions.PermissionDenied('CSRF Failed: %s' % reason) class CustomAuthentication(jwt_authentication.JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token loginView response["X-CSRFToken"] = request.COOKIES.get("csrftoken") You can check the django csrf documentation here. django documentation -
What is Indentation in Python Programming?
Indentation In Python I want to know how Indentation works? And I want to know how to write code using right indentation. -
Django: sending a POST request with Javascript, but then displaying an updated page rather than the old one
I have an input that fires a onclick calling a javascript function in my main template: <div class="removeTagElementChildDiv"> {% csrf_token %} <input type="image" name="deleteTagImage" class="deleteTagImage" src="{% static 'images/deleteTag.png' %}" width = "10" height = "10" onclick="return removeTag(this.parentElement)"> </div> This calls this method: function removeTag(removeSymbolDivForTagToRemove) { tagElement = removeSymbolDivForTagToRemove.parentElement tagValue = tagElement.querySelector('button[name="tagInTagsMenu"]').value console.log(tagValue) if (window.confirm(`Are you sure you want to delete the, ${tagValue}, tag`)) { return test(tagValue) } } Where the test method makes a POST request to one of my specified urls in urls.py: function test(tagValue) { var csrftoken = getCookie('csrftoken') fetch('deleteTag', { method: 'POST', action: 'deleteTag', headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": csrftoken, }, body: tagValue }) } This method deletes the specific tag from the post request, and redirects to the main page: def deleteTag(request): tagName = request.body.decode('utf-8') Tag.objects.filter(name=tagName).delete() tagsFromModel = Tag.objects.all() for tag in tags: if util.findTagByTagName(tag.name,tagsFromModel) == None: #if the tag from the original list is not in the model, it has been deleted tags.remove(tag) loadTagsFromModel() print("end of delete tag method") return(redirect("/")) def main(request): now = datetime.now() time = now.strftime("%H:%M:%S") loadTagsFromModel() context = {'myTags':tags,'time':time} print("tags in main",len(tags)) #problemet er, at den stadig displayer den gamle index.html når man sletter et tag return render(request, 'index.html',context) All this works … -
Getting HttpResponseNotFound in Django test get method
I am building a test case for an endpoint. Visiting the endpoint in the local development using the browser works fine -- I get the expected response. However, during the test, I get an HttpResponseNotFound in which the endpoint is not found on the server. #views.py class ExampleView(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): print('GOT HERE') qs = Example.objects.last() if self.request.user.is_authenticated: if self.request.user.is_subscribed: message = { 'info': 'User can download template.', 'template': qs.file.url } return Response(message, status.HTTP_200_OK) message = { 'info': 'User cannot download template.', 'template': None } return Response(message, status.HTTP_400_BAD_REQUEST) In my urls.py #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('request/download_template', ExampleView.as_view()), ] My test build class TestExample(APITestCase): fixtures = ['fixtures/initial', 'fixtures/auth', 'fixtures/example'] def test_forecast_template_authenticated(self): response = self.client.get( '/request/download_template/') print('result', response) self.assertEqual(response.status_code, status.HTTP_200_OK) The response <HttpResponseNotFound status_code=404, "text/html; charset=utf-8"> I am trying to debug but I do not even reach the print statement I have in my view. I have been figuring out where could be my mistake but its been hours. Why am I getting that response? Where could be my mistake? -
How to check password that has been hashed and salted?
In my register method, I've created a user after hashing and salting their password. And in the login method, I need to check if the user has entered the correct password. The check_password() doesn't seem to accept a salt, and when I use the default authenticate(), I get an error saying: AttributeError: 'Manager' object has no attribute 'get_by_natural_key' I'm guessing this is probably because I created a custom User model by extending AbstractBaseUser. Is there some way I can verify the password by using an existing method? Or will I have to get the salt, hash and salt the password the user just entered, and then compare with the password in the DB? My user model: class User(AbstractBaseUser): name = models.CharField(max_length=128, blank=False) created_at = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(blank=True,default=False, verbose_name="Is admin") designation = models.CharField(max_length=90, blank=True) email = models.EmailField(max_length=160, blank=False, unique=True) USERNAME_FIELD = "email" def __str__(self): return self.name + " " + self.email Method for creating user: def register_user(self, request, **kwargs): serializer = UserSerializer(data=request.data) # handle invalid request if not serializer.is_valid(): for key, values in serializer.errors.items(): errorMsg = key + ": " + values[0].title() return Response( {"message": errorMsg}, status=status.HTTP_400_BAD_REQUEST ) name = serializer.data.get("name") email = serializer.data.get("email") password = serializer.data.get("password") user = User.objects.filter(email=email).first() … -
Why the User has no attribute 'objects'
user = User.objects.filter(email=email).first() AttributeError: type object 'User' has no attribute 'objects' views.py class PasswordReset(generics.GenericAPIView): serializer_class = serializers.EmailSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data["email"] user = User.objects.filter(email=email).first() if user: encoded_pk = urlsafe_base64_encode(force_bytes(user.pk)) token = PasswordResetTokenGenerator().make_token(user) reset_url = reverse("reset-password", kwargs={"encoded_pk": encoded_pk, "token": token}) rest_url = f"localhost:8000{reset_url}" return Response( { "message": f"Your password reset link: {rest_url}" }, status=status.HTTP_200_OK, ) else: Response( { "message": "User doesn't exists" }, status=status.HTTP_400_BAD_REQUEST, ) serializers.py class EmailSerializer(serializers.Serializer): email = serializers.EmailField() class Meta: field = ("email",) -
How make scrollable dropdown in foreignkey field Django
I need to make the city field scrollable, how can i do this? models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.dispatch import receiver from django.db.models.signals import post_save from cities_light.models import City # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')], blank=True, null=True) image = models.ImageField(upload_to='profile/') city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True, null=True) def __str__(self) -> str: return str(self.user) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' exclude = ('user',) edit_profile.html <form method='POST' enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form userForm %} {% bootstrap_form profileForm %} {% buttons %} <button href="{% url 'accounts:profile' %}" type="submit" class='boxed-btn3 w-100'>Save</button> {% endbuttons %} </form> there any argument should add in Forignkey field or the html file should edit?