Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"The submitted data was not a file. Check the encoding type on the form"- Django rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. The image is sent in a binary when I checked the data. But I got the following error. I have made a custom parser, but still got the error. The error is. "The submitted data was not a file. Check the encoding type on the form" The data sent is like this. category[0]: 2 category[1]: 1 brand: 4 collection: 3 availability: not_available warranty: local_seller_warranty service: free_shipping rating: 5 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 9 My custom parser: class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # print(result.data) # for case1 with nested serializers # parse each field with json raw =[] flag = True for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value if '[' in key : x=0 s=key while x < len(key): s = s.translate({ord('['): None}) s = s.translate({ord(']'): None}) s = s.translate({ord('0'): None}) s = s.translate({ord('1'): None}) s = s.translate({ord('2'): None}) s = s.translate({ord('3'): None}) s … -
How to load an api response faster and using it in pandas for analysis in django?
I am new to django and currently working on a project which includes data analysis using pandas and showing it on a website. Though it is taking about 1 minute to load on my local server . How can I do it faster ? views.py def contest_analysis(request,con_id): #rating change statistics url = "https://codeforces.com/api/contest.ratingChanges?contestId="+con_id rating_changes = pd.DataFrame(get_api_response(url)) rating_changes = rating_changes.drop(columns=["contestName", "ratingUpdateTimeSeconds", "contestId"]) rank_mapping(rating_changes) participants = rating_changes['oldranking'].value_counts().to_dict() print(participants) #contest all submissions statistics url ="https://codeforces.com/api/contest.standings?contestId="+con_id+"&showUnofficial=false" data = get_api_response(url) df = pd.DataFrame(data["rows"]) df = df.drop(columns=["points", "successfulHackCount", "unsuccessfulHackCount"]) new_columns=problem_sep(df) print(new_columns.keys()) problems2 = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in new_columns.items()])) final_dataset = pd.concat([rating_changes, problems2], axis=1) return render(request,"cheforces/contest_analysis.html",{"p" : con_id, "participants" : participants,}) get_api_response function def get_api_response(url): try: with request.urlopen(url) as response: source = response.read() data = json.loads(source) data = data['result'] return data except: raise Http404('Codeforces Handle Not Found!!!') I am using codeforces API . -
Django Query to select multiply count
Can any member can help to solve the bellow particular problem: select count(total_lead), count(pending), count(progress),count(closed) from leads where user=user How do I achieve this query in Django ORM ? Any help in highly appreciated. Thanks Regards, -
Querying in django models
I have two models user and posts. Each post is associated to a user and user can follow each other and the user model contains a field called is_private_profile depending on which user's posts are visible to eveyone or only to those who follow the user. I want to fetch all the posts whose authors have public profile and the posts for users with private profile only if the user who wants the post follows him class Posts(models.Model): author = models.ForeignKey(User, verbose_name=_( "Author"), on_delete=models.CASCADE, related_name="posts") caption = models.TextField(_("Caption")) created_at = models.DateTimeField( _("Created At"), auto_now=False, auto_now_add=True) updated_at = models.DateTimeField( _("Updated At"), auto_now=True, auto_now_add=False) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("Email"), max_length=254, unique=True) follows = models.ManyToManyField("self", verbose_name=_( "Followers"), symmetrical=False, related_name='followed_by') is_private_profile = models.BooleanField( _("Is Private profile"), default=False) -
How to get data from entity that exists only in session with Django?
I have to store order history as sets of goods in order. I intended to achieve this by copying contents of the cart to model I've created using object.create. But cart was written by someone else and doesn't have actual model as it exists only within session. How do I retrieve data from it to put it into my Order object? My cart class: class Cart(object): def __init__(self, request): """ Инициализируем корзину """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): """ Добавить продукт в корзину или обновить его количество. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # Обновление сессии cart self.session[settings.CART_SESSION_ID] = self.cart # Отметить сеанс как "измененный", чтобы убедиться, что он сохранен self.session.modified = True def remove(self, product): """ Удаление товара из корзины. """ product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Перебор элементов в корзине и получение продуктов из базы данных. """ product_ids = self.cart.keys() # получение объектов product и … -
Django delete superclass update or delete on table violates foreign key constraint
I have two django models, one subclassing another, class A(models.Model) : . . class B(A) : . . the problem is when I'm deleting class A I'm getting update or delete on table "a" violates foreign key constraint "b_a_ptr_id_53f8796d_fk_a" on table "b" Shouldn't the delete automaticly take out the row on table B pointing to the deleted element? Can anyone guide me through this please. -
ERROR (EXTERNAL IP): Internal Server Error: /
We currently have a CA setup with django connected through its API (dogtag). We recently set up a new subordinate CA and tried to redirect django to this new IP, however we are receiving the following error when submitting a CSR request to my CA using django: KeyError at / 'Output' Request Method: POST Request URL: https://10.10.50.4/ Django Version: 2.2.14 Python Executable: /app/PKIWeb/venv/bin/python3.6 Python Version: 3.6.6 Python Path: ['/app/PKIWeb', '/app/PKIWeb/venv/bin', '/app/PKIWeb/venv/lib64/python36.zip', '/app/PKIWeb/venv/lib64/python3.6', '/app/PKIWeb/venv/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6', '/usr/lib/python3.6', '/app/PKIWeb/venv/lib/python3.6/site-packages'] Server time: Sáb, 26 Jun 2021 21:14:30 -0400 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'api', 'django_extensions', 'widget_tweaks', 'rest_framework', 'rest_framework_api_key', 'drf_yasg'] Installed 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', 'camaracomercio.middleware.CsrAPILocaleMiddleware'] Traceback: File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/edit.py" in post 142. return self.form_valid(form) File "/app/PKIWeb/core/views.py" in form_valid 39. cert_request_infos = self.request_ca_certificate(data, profile) File "/app/PKIWeb/core/views.py" in request_ca_certificate 62. enroll_request = client.create_enrollment_request(profile, data) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/__init__.py" in handler 304. return fn_call(inst, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/cert.py" in create_enrollment_request 962. enrollment_template = self.get_enrollment_template(profile_id) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/__init__.py" in … -
How to update Django model data
I am creating an application that gives users donations and points after they fill out the form on my donate.html. I want to know how I can add data to the Django integer field after the ins.save in my code. For example, if the donation field is equal to 3, after the ins.save, I want to add 1 to it and therefore it will be equal to 4. My code is down below. Thank you to everyone who helps! Donate View: def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, ) ins.save() return render(request,'donate.html') Model: (I want to add to this data after the ins.save) class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) -
How can I iterate over object instances associated with another object through many-to-many relationship in Django?
I have a model JobEntry which has a many-to-many relationship with another model ServiceItemStats. Their implementation is: class JobEntry(models.Model): # PK: id - automatically assigned by Django. stats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship class ServiceItemStats(models.Model): service_stats_name = models.CharField(primary_key=True, max_length=20) service_stats_estimate_duration = models.IntegerField() # Many-to-many relationship with JobEntry. def __str__(self): return self.service_stats_name I am trying to get all service_stats_name field values of ServiceItemStats associated with a particular JobEntry in a table by using a loop: <table class="table"> <thead class="thead-dark"> <tr class="table-light"> <th class="lead"><strong>Assigned service items:</strong></th> <td class="lead"> {% for stat in JobEntry.stats_set.all %} {{ stat.service_stats_name }} <br> {% empty %} No service items assigned. {% endfor %} </td> </tr> </thead> </table> This is all done in a JobDetailView: class JobDetailView(DetailView): context_object_name = 'jobDetail' model = JobEntry template_name = 'jobs/job_detail.html' I keep getting "No service items assigned" although if I go through Django admin, I can see that there actually are instances of ServiceItemStats associated with a JobEntry. I am not sure what am I doing wrong here, any help would be appreciated. -
ModuleNotFound error trying to open Django app in Heroku- issue with gunicorn setup?
I've been building my first Django project (just running it locally so far using runserver), and I'm taking the steps to host it on Heroku, adding gunicorn. The build succeeds, but when I try to open the app, the Heroku logs show an exception in worker process: ModuleNotFoundError: No module named 'familytree' I haven't strayed from the defaults generated along the way, but I'm wondering if I'm missing something in my setup or my file structure that's preventing things from working out of the box. My Django project structure is like this: family-django |-mysite | |-familytree | |-myauth | |-mysite | |-asgi.py | |-settings.py | |-urls.py | |-wsgi.py |-Procfile |-requirements.txt wsgi.py and asgi.py were both created at the start of the project. (Not sure if it's wrong to have both?). wsgi.py has: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() The wsgi file is referenced in settings.py like this: WSGI_APPLICATION = 'mysite.wsgi.application' Now that I'd like to get this up on Heroku, they recommend gunicorn, so I've added a requirements.txt: django django-heroku gunicorn Procfile has: web: gunicorn mysite.wsgi --log-file - I've come across a couple similar posts so far, but each had very particular issues/fixes, and since … -
Django Celery task error while invoked in Post request
I have a below task to run notifications asynchronously @shared_task(name="notifications_task") def notifications_task(activity_type,obj=None, target=None): dispatch_notification_activity(activity_type,obj, target) In the views,py in a post request, I am calling this notfications_task as below notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance) The Function dispatch_notification_activity takes care of the push notifications, since it takes more Time , I am running it asynchronously getting the below error while calling the notifications_task : kombu.exceptions.EncodeError: Object of type UpdateTypeEnum is not JSON serializable Traceback (most recent call last): File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "E:\stocktalk-api-platform\apps\stock_watchlist\views.py", line 42, in post notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 421, in delay return self.apply_async(args, kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 561, in apply_async return app.send_task( File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\base.py", line 718, in send_task amqp.send_task_message(P, name, message, **options) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\amqp.py", line 538, in … -
I keep getting core error in Django as a back-end
I'm new with Django, I'm working on a project with Django as back-end and and angular as front-end. I keep having this error while serving Django, please can anyone help me, i tried uninstalling django-cors-headers-3.7.0 and reinstalling it and i still got this error : ``` ModuleNotFoundError: No module named 'corsheaders.middleware.CorsMiddlewaredjango'; 'corsheaders.middleware' is not a package django.core.exceptions.ImproperlyConfigured: WSGI application 'djangoAPI.wsgi.application' could not be loaded; Error importing module. ** -
How to Increment IntegerField on django on button click from template?
How to Increment IntegerField on django on button click from template? I have two buttons on template one for like and other for dislike.I am using different post requests for both of them but get no increase on likes and dislikes. I hope Information is complete. Here is the models.py code class Post(models.Model): Title=models.CharField(max_length=50) slug = models.SlugField(unique=True,null=True,blank=True) Meta_Tags = models.CharField(max_length=200,null=True) Description=models.TextField() Category=models.CharField(max_length=50) Body=RichTextUploadingField() Date=models.DateField(auto_now_add=True) Views=models.IntegerField(default=0,null=True) Likes=models.IntegerField(default=0,null=True) Dis_Likes=models.IntegerField(default=0,null=True) def __str__(self): return self.Title + " | " + str(self.Date) here is the view.py code def blogdetail(request,slug): post=Post.objects.get(slug=slug) post.Views +=1 if request.POST.get('Like'): post.Likes +=1 if request.POST.get('DisLike'): post.Dis_Likes +=1 post.save() context={ 'post':post } return render(request,'blogdetail.html',context) template code is here <div class="submit-reaction p-3 mb-5"> <span class="p-x3 mb-5" style="float:left"> <form action="" method="post"> {% csrf_token %} <button type="submit" name="Like"style="border:none;background:none;"><i class="far fa-3x fa-thumbs-up text-secondary"></i></button> </form> </span> <span class="p-x3 mb-5" style="float:right"> <form action="" method="post"> {% csrf_token %} <button type="submit" name="DisLike"style="border:none;background:none;"> <i class="far fa-3x fa-thumbs-down text-secondary"></i></button> </form> </span> </div> -
How can I extend month in Django
I am trying to add extra month in my expiry_date field in Django, I've done like this import datetime now = datetime.datetime.now() year = now.year day = now.day hour = now.hour minute = now.minute second = now.second def add_expiry(a): month = now.month print('month : ', month) current_month = month+a print('month adding variable : ', current_month) date = f"{year}/{current_month}/{day}" time = f"{hour}:{minute}:{second}" return f"{date} {time}" print(add_expiry(6)) Output : month : 6 month adding variable : 12 2021/12/27 11:54:17 but problem is it will increase only month but what about year how I can handle year please help. -
How to get a user's OAuth2/access token using Django allauth package
I am using django-allauth in my Django application, and my registration process is handled by Twitch, using allauth's Twitch provider. As of now, users can register on the website using Twitch, log out, and later log back in using Twitch with no problem. However, for making requests to some of Twitch API endpoints, I need the user's Twitch access token to be able to make requests on their behalf (such as following a channel, etc.). On a very old github issues page I came upon a question regarding how to access the user's access token and the answer was to query the SocialToken model and find the logged-in user and the desired provider. But in my case my SocialToken model is empty and there are no tokens to be seen there, and I have no clue how to proceed to populate the model and add every new user's access token there, so that I can make requests on their behalf, given I have the correct scope. Is there a way to add every new user's access token in SocialToken model? And is there a way to update the access token using the refresh token? P.S. I'm thinking about having a … -
Django csrf token not refreshed after first login
I have hosted a website at http://cognezic-dev.ap-south-1.elasticbeanstalk.com/login/. On closer inspection, the form has the same csrf token across page refreshes and browsers, which I suspect to be the cause of the issue,this works fine on the local django server.Dont know where this is being cached. I have added CSRF Middleware in the settings.py too. You can use the test credentials as username bismeet and password bis12345 for testing. -
Django is not redirecting to profile page after login. What is wrong with my code?
This is my views.py def LoginPage(request): username = password = '' next = "" if request.GET: next = request.GET['next'] if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None: login(request, user) if next == "": return HttpResponseRedirect('/Profile/') else: return HttpResponseRedirect(next) context = {} return render(request, 'login.html', context) This is my template: {% if next %} <form class="" action='/Profile/' method="post"> {%else%} <form class="" action="/Login/" method="post"> {% endif %} {% csrf_token %} <p class="login-field-title"><strong>Username*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Enter Username" required> <p class="login-field-title"><strong>Password*</strong></p> <input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} <button type="submit" class="btn btn-dark btn-lg col-lg-10 log-btn">Log In</button> </form> I don't understand what I'm doing wrong. Some help would be very appreciated. Even after logging in with a registered user it is not redirecting me to the desired page and when i change the action, even with the un registered user it redirects me to the next page. -
how to check if start date and end date takes then raise an error django
I'm working on a project for a hotel , i have to prevent from select wrong dates for example check_in = 27-6-2021 2:30PM check_out = 30-6-2021 2:30PM i want to prevent from selecting any date into that two dates for example check_in=28-6-2021 2:30PM check_out=2-7-2021 2:30PM and so on .. this is my Booking model class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField(Vistor) check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() #my form class BookingForm(forms.ModelForm): takes_by = forms.ModelMultipleChoiceField(queryset=Vistor.objects.all()) check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) check_out = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'})) class Meta: model = Booking fields = ['takes_by','check_in','check_out'] my views.py @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.room_no = room_number obj.admin = request.user obj.save() messages.success(request,f'room number {room_number} added') form = BookingForm() return render(request,'booking/add_booking.html',{'form':form,'lists':lists,'room_number':room_number}) what should i do to prevent from takes a room in an existing date twice ? thank you so much -
How to add new row to table on button click and get all the datas in a form containing table and other input fields to save in django sqlite3 DB
---HTML--- One table row contains itemname(select2 dropdown) , Nos , Price , Amount , Toggle button... Totally 5 td's in one row. Need one button somewhere which can be used to add indentical row to the table containing all those 5 td's. Last row of the table will always be the total bill amount field which does calculations and displays total amount. This all goes into a form and submit button should trigger GET to fetch all values in the form including the datas in table. <table id="bill" class="table table-sm"> <thead> <tr class="d-flex"> <th class="text-center"> <th class="col-5"> Item Name </th> <th class="col-1"> Nos </th> <th class="col-2"> Price </th> <th class="col-2"> Amount </th> </th> <th class="col-2"> </th> </tr> </thead> <tbody> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem1" class="selectitem" "form-control" style="width: 100%" onchange="myFunction(event,1)" > <option selected disabled="True" class="form-control">Item Name </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-1"> <div class="form-group"> <input type="text" class="form-control qty" name="qty"> </div> </td> <td class="col-sm-1-5"> <div class="form-group"> <input id="myText1" type="text" class="form-control price" value=" " name="price"> </div> </td> <td class="col-sm-2"> <div class="form-group"> <output class="form-control amt" name="amt" readonly > </div> </td> <td class="col-sm-2 "> <div class="form-group"> <div class="col-sm-15 align-self-center"> <div … -
Using widgets on Django forms
I'm having issues with running my widgets on my Django forms. Below is the block of code. Prior to this, I had already installed the necessary Bootstrap element to my base.html file. Please help. Thank you. from django import forms from .models import Post class PostForm (forms.ModelForm): class Meta: model= Post fields= ('title', 'title_tag', 'author', 'body') widgets= { 'title': forms.TextInput (attrs= {'class': 'form-control', 'placeholder': 'Enter title here'}), 'title': forms.TextInput (attrs= {'class': 'form-control'}), 'author': forms.Select (attrs= {'class': 'form-control'}), 'body': forms.Textarea (attrs= {'class': 'form-control'}), } -
Django ModelForm widgets not modifying on the page
I want to style Django forms, but widgets are not taking any effect. My code: forms.py class bidForm(forms.ModelForm): class Meta: model=bid fields = ['bid'] widgets = { 'place a bid': forms.NumberInput(attrs={ 'class': "form-control", 'style': 'font-size: xx-large', 'placeholder': 'place a bid', }) } models.py class bid(models.Model): listing = models.ForeignKey('listing', on_delete=models.CASCADE, related_name='listing') user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2,) def __str__(self): return f"{self.bid}, {self.listing}, {self.user}" What is the reason it's not working? Answer would be greatly appreciated! -
My password reset view in django shows up only when the user has logged in but not when logged out
When I click on forgot password django takes me to another page other than the password reset page, but this doesn't happen when I am logged in only happen when I am logged out. I want it to happen when logged out Please help! views.py @login_required def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "password/password_reset_email.txt" c = { "email": user.email, 'domain': '127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'sample@gmail.com', [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, 'A message with reset password instructions has been sent to your inbox.') return redirect("/password_reset/done/") messages.error(request, 'An invalid email has been entered.') password_reset_form = PasswordResetForm() return render(request=request, template_name="password/password_reset.html", context={"form": password_reset_form}) urls.py urlpatterns = [ path('signup/', signup), path('login/', login_request), path('logout/', logout_request), path('', TemplateView.as_view(template_name="index.html")), path('Admin/Links/', update_profile_links), path('Admin/Appearance/', update_profile_appearance), path('Admin/Social_Links/', update_profile_social), path('Admin/Profile/<str:username>/', profile_view), path('password_reset/', password_reset_request), path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), path('delete_account/', delete_user) ] project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Home.urls')), path('', include('UserManagement.urls')), path('', include('UserLinks.urls')), ] -
How can I resolve this issue when I am trying to uninstall django from system?
enter image description here First I checked the version of django so I got 3.1.3 but when I tried to uninstall with pip uninstall django it says 'Skipping django as it is not installed'. -
Retrieving Django model value based on another model
I was following a youtube's django database model queries but try doing it with different context to see if I understand the model concept and not just blindly following (and it turns out i do not understand it at all). I was trying to retrieve the "views" values in the model based on the tag name. I manage to pull the individual item but i do not know how to retrieve the view count based on the tag name. The table look similar to this: title author body views tags title a author a blog post a 10 apple, orange, pear title b author a blog post b 100 banana, orange title c author a blog post c 50 banana, pear, apple, orange title d author a blog post d 1 grape the value i hope to retrieve is the sum of views that the tags are associated, like this tags|count --|-- apple|60 orange|160 banana|150 grape|1 pear|51 This is the current model class Tag(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return f'{self.name}' class Blog(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() views = models.IntegerField(default=0) tags = models.ManyToManyField(Tag) class Meta: verbose_name_plural = "Blogs" def __str__(self): return f'{self.title} | … -
test db is not able to query from second db
i am writing a test in Django using django.test TestCase and in this test i am acessing both the db but i am getting error like i db is not there in my testdb settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxx', 'PORT': 'xxx', 'TEST': { 'MIRROR': 'default', }, }, 'middle': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', 'HOST': 'xxx', 'PORT': 'xxx', 'TEST': { 'MMIRROR': 'middle', }, } } error in console {'error': "Database queries to 'middle' are not allowed in this test. Add " - "'middle' to file.tests.TestFunc.databases to ensure proper " - 'test isolation and silence this failure.',