Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django google books API totalItems is changing
I am creating an application that retrieves data from the google books API. At the very beginning I download a number of books from JSON ["totalItems"] and iterate through the for loop, calling the API in order to get another 40 items. The problem is that the number of books increases and decreases during iteration, so when, for example, on a 550 book, I get a list index out of range error. Anyone please help me download all the books? My request looks like this: requests.get(f'https://www.googleapis.com/books/v1/volumes?q={search}\ &maxResults=40&startIndex={end_range}') end_range is increased by 40 each time data is downloaded. -
Go import from specific branch github in the same repository where it is hosted
I have a repository with a golang project in github, I need to import in a module a specific branch, to make relevant modifications. It looks like this: package events_entity import ( "github.com/repository/utils/date_utils" "github.com/repository/utils/utils/error_utils" "github.com/repository/utils/utils/hour_utils" "strconv" "strings" ) The importation is always done directly from the master. I just need this module to import from a different branch. Thanks!!! -
Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin
My error : Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin i am getting this error in admin panel, i havent entered any data in placed order yet and neither in restaurants class Restaurants(models.Model): name = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=50, blank=False) city = models.ForeignKey(City, on_delete=models.CASCADE) mob_no = models.IntegerField() opening_time = models.TimeField() closing_time = models.TimeField() website = models.URLField(blank=True) cover = models.ImageField(upload_to='restraunts/cover') # Create your models here. class PlacedOrder(models.Model): order_id= models.CharField(max_length=255) restraunt = models.ForeignKey(to='restaurants.Restaurants', on_delete=models.CASCADE) order_time = models.TimeField( auto_now_add=True) estimated_delivery_time = models.TimeField() actual_delivery_time = models.TimeField() food_ready_time = models.TimeField() total_price = models.DecimalField(max_digits=12, decimal_places=2) -
Custom User Primary Key - Django
I have a Django website and a format similar to google sheets in which people can add data and it shows up in a row. To the left is the number associated with that row of data. Normally I used pk which worked great because when one data row was deleted no other ones changed. Now I have 2 users and I'm separating the data based on ForeignKey fields in all of my models. The problem with this is, for example, User1 adds 1 row of data then User2 adds one row of data then User1 adds another row of data, then when User1's data is being displayed it will show 2 rows labeled 1 and 3. I need them to be specific to the user and in numerical order. It is as if I need a separate pk for each user in the same model. I temporarily fixed this by {{ forloop.revcounter }} in the forloops of the rows. This now keeps the row number in numerical order and specific to the user. The problem is that if User1 now deletes the first data row labeled #1 then now the table only shows 1 row and the data row … -
Ordering by multiple fields
I'm wanting to order a queryset based on a couple of different related fields Models.py class Appointment(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Event(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Job(models.Model): event = models.ForeignKey(Event, on_delete=models.SET_NULL) appointment = models.ForeignKey(appointment, on_delete=models.SET_NULL) views.py qs = Job.objects.all().order_by('event__start_time','appointment__start_time') Is this the correct way to do this? Will this always order all of the jobs in the correct order based on the associated star time? Thanks! -
The view basket.views.basket_remove didn't return an HttpResponse object. It returned None instead
Can someone explain me why am i getting this error? I am creating online store in which basket functionality depends on sessionid in cookies. Look, I have a function basked_add on every product in store, which adds specified product to basket and it works correctly without any issues. I have also a function basket_delete in basket to remove specified product from basket, and somehow it doesn't work correctly. And this is the main reason why i made this question. Function basket_delete is called by JQuery like that (equal to basked_add): 1. basket.html $(document).on('click', '#remove-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_delete" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post', }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) 2. basket > urls.py app_name = 'basket' urlpatterns = [ path('', views.basket, name='basket'), path('add/', views.basket_add, name='basket_add'), path('delete/', views.basket_delete, name='basket_delete'), ] 3. Then function is getting executed basket > views.py from django.http.response import JsonResponse from basket.basket import Basket def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) response = JsonResponse({'Success': True}) return response basket > context_processors.py from .basket import Basket def basket(request): return {'basket': Basket(request)} basket > basket.py class … -
GET http://localhost:3000/product/[object%20Object] 404 (Not Found) [object%20Object]:1
I am trying to fetch image data from django using api calls, redux state is updated successfully with api call data's But the image is not loading on the page Its giving below error in console and in python terminal Not Found: /product/[object Object] [31/Jul/2021 14:44:36] "GET /api/products/image/7 HTTP/1.1" 301 0 [31/Jul/2021 14:44:36] "GET /product/[object%20Object] HTTP/1.1" 404 2724 productAction.js export const listProductImage = (id) => async (dispatch) => { try{ dispatch({ type: PRODUCT_IMAGE_REQUEST }) const {data} = await axios.get(`http://127.0.0.1:8000/api/products/image/${id}`) dispatch({type: PRODUCT_IMAGE_SUCCESS, payload: data}) }catch(error){ dispatch({ type: PRODUCT_IMAGE_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } productReducers.js export const productImagesReducers = (state={pImage:[]}, action) => { switch(action.type) { case PRODUCT_IMAGE_REQUEST: return {loading:true, pImage:[] } case PRODUCT_IMAGE_SUCCESS: return {loading:false, pImage:action.payload } case PRODUCT_IMAGE_FAIL: return {loading:false, error: action.payload } default: return state } } ProductImageGallery.js (Template) Dispatching Code const dispatch = useDispatch() const ProductImageGallery = ({ match, productID }) => { const dispatch = useDispatch() const productImage = useSelector(state => state.productImage) const {pImage} = productImage useEffect(()=>{ dispatch(listProductImage(productID)) }, [dispatch, productID]) } models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200,null=True,blank=True) image = models.ImageField(null=True,blank=True) brand = models.CharField(max_length=200,null=True,blank=True) category = models.CharField(max_length=200,null=True,blank=True) description = models.TextField(null=True,blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2,null=True, blank=True) numReviews = … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello only admin/ path is defined
i am following the django instructions to build a web application hello i have done everthing after the document but this happens Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order: admin/ The current path, hello, didn’t match any of these. there must be another path as hello/ this is my code: views.py/hello: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello.") urls.py/pythonweb(my app): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] urls.py/hello: from django.urls import path from . import views urlpatterns = [ path('', views.index, name =('index')) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello/', ] -
create user function doesn't work in UserCustomManager django
I write a custom user and UserCustomManager but my user don't create. this is my code of models and UserCustomManager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("default") Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('otp', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone_number, **extra_fields) class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) otp = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' about user.set_password("default") it is ok and I wanna my custom … -
customize django model meta ordering option
I want to set ordering according to condition something like this. if self.name_format == "First name Last name": class Meta: ordering = ['first_name', 'last_name'] elif self.name_format == "Last name First name": class Meta: ordering = ["last_name","first_name"] elif self.name_format == "Last name, First name": class Meta: ordering = ["last_name","first_name"] else: class Meta: ordering = ["first_name","last_name"] How can i achieve that? -
I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Signup Page</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'login/signuppage.css' %}"> </head> <body> <div class="login"> <div class ="form"> <h3>Sign in</h3> <form class="registration-form" method="POST"> {% csrf_token %} {% for field in form %} <p>{{ field.label_tag }} {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <!--<input type="text" placeholder="Username"/> <input type="email" placeholder="Email ID"/> <input type="password" placeholder="Password"/> <input type="password" placeholder="Confirm Password"/>--> <button>Sign in</button> <p><a href ="#">Login</a></p> </form> </div> </div> </body> </html> Sign in page views views.py: def SignupPage(request): form = UserSigninForm() if request.method=='POST': form=UserSigninForm(request.POST) if form.is_valid(): user=form.save() auth_login(request, user) return redirect('/home/') else: form = UserSigninForm() context = {'form': form} return render(request,'login/signuppage.html',context) signin page forms forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.forms import ModelForm class UserSigninForm(UserCreationForm): class Meta: model = User fields=['username','email','password1','password2'] I am trying to create a signin page but after sign in a file with 0 kb is getting downloaded and getting CSRF verification failed. Request aborted as an error. I am trying not to exempt csrf token in code. What needs to be done here to resolve the issue? -
RabbitMQ, Celery and Django - connection to broker lost. Trying to re-establish the connection
Celery disconnects each time a task is passed to rabbitMQ, however the task does eventually succeed: My questions are: How can I solve this issue? What improvements can you suggest for my celery/rabbitmq configuration? Celery version: 5.1.2 RabbitMQ version: 3.9.0 Erlang version: 24.0.4 RabbitMQ error (sorry for the length of the log: ** Generic server <0.11908.0> terminating ** Last message in was {'$gen_cast', {method,{'basic.ack',1,false},none,noflow}} ** When Server state == {ch, {conf,running,rabbit_framing_amqp_0_9_1,1, <0.11899.0>,<0.11906.0>,<0.11899.0>, <<"someIPAddress:45610 -> someIPAddress:5672">>, undefined, {user,<<"someadmin">>, [administrator], [{rabbit_auth_backend_internal,none}]}, <<"backoffice">>,<<"celery">>,<0.11900.0>, [{<<"consumer_cancel_notify">>,bool,true}, {<<"connection.blocked">>,bool,true}, {<<"authentication_failure_close">>,bool,true}], none,0,134217728,1800000,#{},1000000000}, {lstate,<0.11907.0>,true}, none,2, {1, {[{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}], []}}, {state,#{},erlang}, #{<<"None4">> => {{amqqueue, {resource,<<"backoffice">>,queue,<<"celery">>}, true,false,none,[],<0.471.0>,[],[],[],undefined, undefined,[],[],live,0,[],<<"backoffice">>, #{user => <<"someadmin">>}, rabbit_classic_queue,#{}}, {false,0,false,[]}}}, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {1,{<<"None4">>,nil,nil}}}, {state,none,5000,undefined}, false,1, {rabbit_confirms,undefined,#{}}, [],[],none,flow,[], {rabbit_queue_type, #{{resource,<<"backoffice">>,queue,<<"celery">>} => {ctx,rabbit_classic_queue, {resource,<<"backoffice">>,queue,<<"celery">>}, {rabbit_classic_queue,<0.471.0>, {resource,<<"backoffice">>,queue,<<"celery">>}, #{}}}}, #{<0.471.0> => {resource,<<"backoffice">>,queue,<<"celery">>}}}, #Ref<0.4203289403.2328100865.106387>,false} ** Reason for termination == ** {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue,<<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2,[{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2,[{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3,[{file,"proc_lib.erl"},{line,236}]}]} crasher: initial call: rabbit_channel:init/1 pid: <0.11908.0> registered_name: [] exception exit: {function_clause, [{rabbit_channel,'-notify_limiter/2-fun-0-', [{pending_ack,1,<<"None4">>,1627738474140, {resource,<<"backoffice">>,queue, <<"celery">>}, 2097}, 0], [{file,"src/rabbit_channel.erl"},{line,2124}]}, {lists,foldl,3,[{file,"lists.erl"},{line,1267}]}, {rabbit_channel,notify_limiter,2, [{file,"src/rabbit_channel.erl"},{line,2124}]}, {rabbit_channel,ack,2, [{file,"src/rabbit_channel.erl"},{line,2057}]}, {rabbit_channel,handle_method,3, [{file,"src/rabbit_channel.erl"},{line,1343}]}, {rabbit_channel,handle_cast,2, [{file,"src/rabbit_channel.erl"},{line,644}]}, {gen_server2,handle_msg,2, [{file,"src/gen_server2.erl"},{line,1067}]}, {proc_lib,wake_up,3, [{file,"proc_lib.erl"},{line,236}]}]} in function gen_server2:terminate/3 (src/gen_server2.erl, line 1183) ancestors: [<0.11905.0>,<0.11903.0>,<0.11898.0>,<0.11897.0>,<0.508.0>, <0.507.0>,<0.506.0>,<0.504.0>,<0.503.0>,rabbit_sup, <0.224.0>] message_queue_len: 0 messages: [] links: [<0.11905.0>] dictionary: [{channel_operation_timeout,15000}, {process_name, {rabbit_channel, {<<"someIPAddress:45610 -> someIPAddress:5672">>, 1}}}, … -
generator expression must be parenthesized
I'm using Python 3.8 and I'm adding a model in my models file, when I did the makemigration it gave me this reply enter image description here -
show error message for any incorrect path in Django
how can I show an error message for any incorrect slug in Django? URLs.py from django.urls import path, re_path from register import views urlpatterns = [ path('', views.index, name='home'), path('singup', views.Register_user, name='singup'), path('singin', views.login_user, name='singin'), path('registration/success/<slug:user_slug>', views.success_message, name='success_message'), path('registration/failed', views.failed_message, name='failed_message'), path('profile/<slug:user_slug>', views.user_detail, name='profile'), path('profile/<slug:user_slug>/new-blog', views.blog_post, name='new_blog'), path('<str:user_slug>', views.wrong_slug, name='error_msg') ] I trying "path('<str:user_slug>', views.wrong_slug, name='error_msg')" this but it not work after Slash('/'). -
how to create and show a task with POST method in django
i have a model that name is Task it have just name field from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Task @csrf_exempt def list_create_tasks(request): if request.method == 'POST': name = request.POST.get("name") Task.objects.create(name=name) task = Task.objects.filter("name") return HttpResponse("Task Created: "+"'"+str(task)+"'") -
How to make form html for updateview
I was making my own forms for CreateView and UpdateView with my html file because I don't want to display the form like this {{form.as_p}}. forms.py from django import forms from .models import Post class PostCreationForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'cover', 'text',) widgets = { 'title': forms.TextInput(attrs={'class': 'title'}), 'cover': forms.FileInput(attrs={'class': 'image'}), 'text': forms.TextInput(attrs={'class': 'text'}) } class PostDeleteForm(forms.ModelForm): class Meta: model = Post fields = ('__all__') views.py from django.shortcuts import reverse from django.http import HttpResponseRedirect from django.views import generic from .models import Post from .forms import PostCreationForm, PostDeleteForm class PostListView(generic.ListView): model = Post context_object_view = 'post_list' template_name = 'forum/post_list.html' class PostDetailView(generic.DetailView): model = Post context_object_view = 'post' template_name = 'forum/post_detail.html' class PostCreateView(generic.CreateView): model = Post form_class = PostCreationForm template_name = 'forum/post_create.html' def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.author = self.request.user response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostUpdateView(generic.UpdateView): model = Post context_object_view = 'post' form_class = PostCreationForm template_name = 'forum/post_edit.html' def get_post(self, pk): return get_object_or_404(Post, pk=pk) def form_valid(self, form): if form.is_valid(): response = form.save(commit = False) response.save() return HttpResponseRedirect(reverse('post_detail', args=[str(response.id)])) class PostDeleteView(generic.DeleteView): model = Post context_object_view = 'post' form_class = PostDeleteForm template_name = 'forum/post_delete.html' success_url = '/' def get_post(self, pk): return get_object_or_404(Post, pk=pk) post_create.html {% … -
Run JS after Django POST Request
I am learning Django Channels and I already have a few months of basic Django experience. Essentially what I am trying to do is after the POST request is sent, to trigger the JS function that will deal with sending the message. I have the following part of views.py code if request.method == "GET": # irrelevant logic pass if request.method == "POST": msg = Message(...) msg.save() return render(request, "index.html", {"msg":str(msg)}) return render("msg":"Hello World"})` And in my index.html, I have the following relevant part: HTML: <form method="post" id="send"> {% csrf_token %} .... </form> JS: var formData = $("#send"); socket.onmessage = function(e){ formData.submit( function(event){ event.preventDefault(); var finalData = { 'msg' : "{{msg}}" } console.log(JSON.stringify(finalData)); socket.send(JSON.stringify(finalData)); formData[0].reset() }) } However, when I try printing the event in my consumers.py as follows: async def websocket_receive(self, event): print("Received", event) What I would expect is to get the text of the message, but what I get in the console is: HTTP GET / 200 [0.01, 127.0.0.1:45652] ... Received {'type': 'websocket.receive', 'text': '{"msg":"Hello World"}'} ... HTTP POST / 200 [0.02, 127.0.0.1:45652] Which means the message gets sent before the post request goes through. Is there some convenient way to fix this? Thanks for your help :) -
How to give permission to some specific user to access some specific templates in django
I am trying to create a Online exam portal and I have created one admin portal for that site.I have 2 types of users in my site "Students" and "Teachers".How can I restrict students from accessing the admin portal and other views of admin panel? -
nip.io is not working, what can be the issue?
im using gmail authentication in Django, and its not accepting private address so I came up with a solution, that is, using wildcard DNS. its working fine in my laptop and im able to access the website from other devices using this IP address. but I when I repeat the same steps in my client laptop, the nip.io is not working. -
Django model querying for first N rows that sum up to a given number
I am sing Django 3.2 I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=255) num_visits = models.PositiveSmallNumber() created_at = models.DateTimeField() class Meta: ordering = ['created_at'] I want to select the first N rows where the number of visits = 100 (as an example) A trivial (but probably DB intensive way) to do it would be to iterate through the rows in the table (i.e. elements of the queryset) - but I don't want to do that - for reasons that should be obvious. How can I write a query that fetches the first N rows where the sum of visits is a specified number? def get_rows_satisfying_visit_count(number=100): MyModel.objects.filter(/* what ? */) -
Best solution for extending user model twice (Student / Teacher)
I'm coding a application in Django where there are 2 types of users that need to login on the webapplication: teachers and students. Now I'm not sure what is the best approach for this. I already read a lot of tutorials and Stackoverflow questions that explains how to extend the user model, but I'm not sure which is the best option. The requirements: 2 kind of profiles with different fields needed (teacher and student) Possibility to have separate admin "objects" where the superstaff of the application can login in the backend and manage the separate objects. Option 1: Make use of the method to extend the AbstractUser class. This works for now, however I don't know if I can use AUTH_USER_MODEL twice (teacher and student). Now it's one profile with both fields for students and teachers. With proxy models I can show only the necessary fields for teachers or students. Option 2: (I think this is the best solution) Make 2 models (Teacher and Student) with each a Foreignkey to User (OneToOneField). Problem here is that if the Administrator of the website creates a new teacher or student, they also need to create a separate user first (that can login) … -
how to send an image to Django-rest-framework without having the unicodeDecode error
I'm trying to upload an image to my Django project using DRF but I get this error : 'utf-8' codec can't decode byte 0xfd in position 34: invalid start byte Here is how I do it on Django : models class Project(models.Model): # relations supplier = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project_supplier", null=True, blank=True) client = models.ForeignKey(User, on_delete=models.CASCADE, related_name="project_client", null=True, blank=True) # fields created = models.DateTimeField(auto_now_add=True, editable=False,null=True) name = models.CharField(max_length=200) cost = models.PositiveIntegerField(null=True, blank=True) rate = models.PositiveIntegerField(null=True, blank=True) is_done = models.BooleanField(default=True) image_1 = models.ImageField(upload_to="upload/images/") image_2 = models.ImageField(upload_to="upload/images/") image_3 = models.ImageField(upload_to="upload/images/") image_4 = models.ImageField(upload_to="upload/images/", null=True, blank=True) image_5 = models.ImageField(upload_to="upload/images/", null=True, blank=True) API @api_view(["POST", ]) def create_new_project(request): if is_post(request): lang = request.data["lang"] name = request.data["name"] image_1 = request.data["image_1"] image_2 = request.data["image_2"] if request.data["image_2"] is not "" else None image_3 = request.data["image_3"] if request.data["image_3"] is not "" else None image_4 = request.data["image_4"] if request.data["image_4"] is not "" else None image_5 = request.data["image_5"] if request.data["image_5"] is not "" else None the_token = request.META.get('HTTP_AUTHORIZATION')[6:] user = Token.objects.get(key=the_token).user try: new_project = Project.objects.create(supplier=user, name=name, image_1=image_1, image_2=image_2, image_3=image_3, image_4=image_4, image_5=image_5) data = model_to_dict(new_project) return generate_response(True, "Projected added successfully" if lang == "en" else "تم إضافة المشروع بنجاح", data) except Exception as e: return generate_response(False, e, None) And here Is how i … -
How to redirect to an absolute url path in django?
I am trying to reroute to the "listing" path from the the watchlist page using the 'url' attribute in Django templates. However, the problem is that Django ignores the parts of the URL it has already used in rerouting (i.e."/watchlist") and so looks for the url with path "/watchlist/listing_title" instead of just "/listing_title", which is what I want. Is there a way to work around this? urls.py path("", views.index, name="index"), path("<str:listing_title>", views.listing, name="listing"), path("watchlist", views.watchlist, name="watchlist"), watchlist.html <a href={% url 'listing' listing.title %}"> -
Django Rest Framework "detail": "Not found."
Here is the URL in url.py: path('follow/<int:pk>/', FollowUser.as_view()), And here is the Class Based View: class FollowUser(UpdateAPIView): """ Follow a user by their PK """ serializer_class = FollowingSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Following.objects.get(user=self.request.user) Why am I getting {"detail": "Not found."} Here is the end point I'm trying to hit: http://localhost:8000/fapi/follow/23/ -
Why is django not making migrations for my models
I uploaded my django app to pythonanywhere and it worked with sqlite database, but on switching to mysql it doesnt make migrations but it migrates the admin tables when i rum python manage.py migrate this is my settings app import os from pathlib import Path import environ env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = env('DEBUG') BASE_DIR = Path(__file__).resolve().parent.parent # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') if DEBUG: ALLOWED_HOSTS = [] else: ALLOWED_HOSTS = [ '*', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'projects', 'services', 'crispy_forms', 'crispy_bootstrap5', # should be at bottom 'django_cleanup.apps.CleanupConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'vectorapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'vectorapp.wsgi.application' if not DEBUG: DATABASES = { 'default': { 'ENGINE': os.getenv("DB_ENGINE"), 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), # 'PORT': os.getenv("DB_PORT"), "OPTIONS": { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", 'charset': 'utf8mb4', "autocommit": True, } } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', …