Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Swagger API . paginate_queryset takes long time to execute
I designed a REST API with Swagger. When a client tries to fetch response using the API, he gets no response (Response 500). Response Code 500 Response Headers { "connection": "close", "content-length": "131", "content-type": "text/html", "date": "Sun, 19 Sep 2021 10:50:08 GMT" } The issue happens in pagination.py def paginate_queryset(self, queryset, request, view=None): """ Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = self.get_page_number(request, paginator) try: self.page = paginator.page(page_number) except InvalidPage as exc: msg = self.invalid_page_message.format( page_number=page_number, message=str(exc) ) raise NotFound(msg) if paginator.num_pages > 1 and self.template is not None: # The browsable API should display pagination controls. self.display_page_controls = True self.request = request return list(self.page) I put two print statements, before and after list(self.page) . As you can see from the below print statements, return list(self.page) takes a long time. [Sun Sep 19 10:49:44.066406 2021] [pid 108994] File: pagination.py, Class: PageNumberPagination, Function: paginate_queryset. **Before list(self.page)**. self.page= <Page 1 of 223291> [Sun Sep 19 11:08:21.092237 2021] [pid 108994] File: pagination.py, Class: PageNumberPagination, Function: paginate_queryset. **After list(self.page)**. As you can see, list(self.page) took almost 20 … -
Staying login problem about CallbackURL after payment
my view is like : def get_user_pending_order(request): user_profile = get_object_or_404(Profile, user=request.user) order = Order.objects.filter(owner=user_profile, is_ordered=False) if order.exists(): return order[0] return 0 MERCHANT = 'xxx...xxx' ZP_API_REQUEST = "https://api.zarinpal.com/pg/v4/payment/request.json" ZP_API_VERIFY = "https://api.zarinpal.com/pg/v4/payment/verify.json" ZP_API_STARTPAY = "https://www.zarinpal.com/pg/StartPay/{authority}" amount = '' description = "text" # Required email = 'example@email.com' # Optional mobile = '09999999999' # Optional # Important: need to edit for realy server. CallbackURL = 'https://example.com/payment/verify/' def send_request(request): print(get_user_pending_order(request).owner.phone_number) req_data = { "merchant_id": MERCHANT, "amount": int(get_user_pending_order(request).get_total()), "callback_url": CallbackURL, "description": description, "metadata": {"mobile": mobile, "email": email} } req_header = {"accept": "application/json", "content-type": "application/json'"} req = requests.post(url=ZP_API_REQUEST, data=json.dumps( req_data), headers=req_header) authority = req.json()['data']['authority'] if len(req.json()['errors']) == 0: return redirect(ZP_API_STARTPAY.format(authority=authority)) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") def verify(request): t_status = request.GET.get('Status') t_authority = request.GET['Authority'] if request.GET.get('Status') == 'OK': req_header = {"accept": "application/json", "content-type": "application/json'"} req_data = { "merchant_id": MERCHANT, "amount": int(get_user_pending_order(request).get_total()), "authority": t_authority } req = requests.post(url=ZP_API_VERIFY, data=json.dumps(req_data), headers=req_header) if len(req.json()['errors']) == 0: t_status = req.json()['data']['code'] if t_status == 100: user = request.user order_to_purchase = get_user_pending_order(request) order_to_purchase.is_ordered = True order_to_purchase.date_ordered=datetime.datetime.now() order_to_purchase.created_on_time=datetime.datetime.now() order_to_purchase.save() order_items = order_to_purchase.items.all() for order_item in order_items: order_item.product.quantity = order_item.product.quantity - 1 order_item.product.save() order_items.update(is_ordered=True, date_ordered=datetime.datetime.now()) subject = 'successful' c = { "refid":str(req.json()['data']['ref_id']), "ref_code":order_to_purchase.ref_code, "owner":order_to_purchase.owner, } email_template_name = … -
AttributeError: 'Request' object has no attribute 'Get' while making a GET request
I am trying to make a Get request , but am getting this error : AttributeError: 'Request' object has no attribute 'Get' Below is my code : class VerifyEmail(APIView): """Verify user account.""" serializer_class = EmailVerificationSerializer def get(self, request): """Obtain email token.""" token = request.Get.get('token') payload = jwt.decode(token, settings.SECRET_KEY) In the urls.py : path('email-verify/', views.VerifyEmail.as_view(), name='email-verify'), The issue is on this line : token = request.Get.get('token') What could be the issue for this ? -
How to solve this issue in Django 3.2?
While developing an django website i came across an issue. please anyone give a solution how to fix this situation. what iam trying to do is creating two gallery page. if anyone clicked image on first page redirect to another page contain more images of it. Please help, Thanks in advance. -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' (settings.py)
settings.py SECURE_SSL_REDIRECT=bool(int(os.environ.get('SECURE_SSL_REDIRECT'))) I retrieve the following error: line 57, in <module> SECURE_SSL_REDIRECT=bool(int(os.environ.get('SECURE_SSL_REDIRECT'))) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' please solve this -
Setting a password for a model(non User) in django for simple authentication
For my website, i am not planning to make it compulsory for the users to sign up. Instead, they can create a post and set a password for it in order to manage it. I can use the 'set_password' method django provides for the User model: def set_password(self, raw_password): import random algo = 'sha1' salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5] hsh = get_hexdigest(algo, salt, raw_password) self.password = '%s$%s$%s' % (algo, salt, hsh) so that sorts out the storing password part. But this will hash the password (which is good) but now i am stuck on how to authenticate this?? So when someone wants to edit the instance of the model they have created, they first need to be authenticated. How do i go about doing that? Thank you -
how to get str from POST method and save in db nad return a message with str in django?
so, The contents of the POST request Task/name The received object is just a string and a Task object must be created using this string. This string is equal to the same name field in the Task object. This page is located at the following URL: http: // localhost: 8000 / tasks After adding the task, the following message should be displayed to the user: For example, if a task called 'Study for 2 hours' is added, the following message should be displayed to the user: Task Created: 'Study for 2 hours' model : from django.db import models class Task(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name view: from .models import * from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def list_create_tasks(request): if request.method == 'POST': name = request.POST.get('name') all_task = Task(name=name) all_task.save() return HttpResponse(f"Task Created: {name}") It does not work according to the view. How do I fix it? -
ValueError: time data 'Sept. 30, 2021' does not match format '%B %d, %Y'
I have a web app,backend using Django, frontend normal HTML5. when I tried to convert the date sent from frontend, error occurs:ValueError: time data 'Sept. 30, 2021' does not match format '%B %d, %Y' at this line end_date = datetime.strptime(end_date, '%B %d, %Y').strftime('%Y-%m-%d') view.py: @csrf_exempt def assign_to_exec(request): if request.method == 'GET': end_date = request.GET.getlist('end_date')[0] end_date = datetime.strptime(end_date, '%B %d, %Y').strftime('%Y-%m-%d') How could I correct it? -
Using JsonField in django to make a simple post api
I have a task to create a simple post api to send a visitor messages through a contact form. I created a model name Contacts and created api using APIView. But when the code was reviewed, I was suggested to use a jsonfield which is already defined in a Core model. So I am quite stuck how to use it. My Core model is like this: class Core(models.Model): """ Model that saves the corresponding credentials for the slug. """ slug = models.CharField(max_length=255, null=False) example = models.JSONField(null=False, default=dict) def __str__(self) -> str: return self.slug I have searched and found that I can pass a dictionary data inside the example field, but I dont know how to use it. What I have done is like this for now. I have a model just below the core model named Conatcts and created the serializer and view files. class Contacts(models.Model): full_name = models.CharField(max_length=100,blank=True,default="") email = models.EmailField() phone = models.CharField(max_length= 16) address = models.CharField(max_length=255,blank=True,default="") message = RichTextField() def __str__(self): return self.email class Meta: verbose_name_plural = 'Visitor Messages' My view: class ContactsView(APIView): permission_classes = [AllowAny] def post(self,request): data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({ 'message': "You message has been sent successfully.", 'data':serializer.data … -
How to get all the data from form submission in django
I am very much new to Django. I am working on an online school system. I am very much new to Django. I have created a student list in my database and from that database, I have retrieved that student data to my template and displayed them on a table. Now I want to confirm they are present to the class and get that data back to the backend. I have added a select option for that to select yes and no. Then I have added a submit button. But after submitting I get only the data of the last student. Please explain to me how to get all the student data to the backend. This is a great help. My model class StudentAttendance(models.Model): grade = models.CharField(max_length=100, null=True, blank=True) subject = models.CharField(max_length=100, null=True, blank=True) admission_number = models.CharField(max_length=100, null=True, blank=True) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) attendance = models.CharField(max_length=100, null=True, blank=True) held_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) submit_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return self.grade My view @login_required(login_url='login') def grade8_dashboard(request): if request.method == "POST": grade = request.POST.get("grade","") subject = request.POST.get("subject","") admission_number = request.POST.get("admission_number","") first_name = request.POST.get("first_name","") last_name = request.POST.get("last_name","") attendance = request.POST.get("attendance","") # held_date = request.POST.get("held_date","") submit_date … -
modify query_params in django in djangofilterbackends
i have a model called product as below, for which i am proving filters using djangofilterbackend with filter_fields = 'all' class Product(models.Model): id name created_at updated_at price and so on.... now when someone sends a query_param related to datetime like "created_at", "updated_at" they are sending epoch timestamps. is there any way to convert epoch timestamps in query_params to datetime ?? things ive tried : ive tried to modify the request_dict in get_queryset identifying the timestamp params and converting them to datetime django. But the request_dict is immutable in DRF. is there any way to modify the query_params in djangofilterbackend ? -
Django: unsupported operand type(s) for +: 'int' and 'str'
I want to sum all the fields of a model by using aggregate(sum()) function but getting this error. Views.py def paymentdailyreport(request): cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(sum('Amount')) print(cashsum) context={ } return render(request,'paymentdailyreport.html',context) Models.py class Payment(models.Model): Date=models.CharField(max_length=20) User=models.CharField(max_length=50) PatientName=models.CharField(max_length=50) Dentist=models.CharField(max_length=50) Scheme=models.CharField(max_length=50) PaymentMethod=models.CharField(max_length=50) Amount=models.DecimalField(max_digits=20,decimal_places=3) def __str__(self): return self.Date + " | " + self.User + " | " + self.PatientName -
How to implement Elastic Search with Django rest framework without using viewsets?
I want to design a search system using Django rest framework and Elastic Search. I could not get a proper tutorial on what each of the things mentioned in elasticsearch-dsl and elasticsearch-dsl-drf stand and how to use them with full explanation. Any guides and suggestions would be very highly appreciated. -
How to fix DetailView is missing a QuerySet Error?
When I try to use DetailView to view my posts I keep getting an exception error. ImproperlyConfigured at /musician_details/1/ DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/musician_details/1/ Django Version: 3.2.5 Exception Type: ImproperlyConfigured Exception Value: DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Exception Location: C:\Program Files\Python38\lib\site-packages\django\views\generic\detail.py, line 69, in get_queryset Python Executable: C:\Program Files\Python38\python.exe Python Version: 3.8.2 Python Path: ['F:\Full Stack\Django\Django Project\Test', 'C:\Program Files\Python38\python38.zip', 'C:\Program Files\Python38\DLLs', 'C:\Program Files\Python38\lib', 'C:\Program Files\Python38', 'C:\Users\Tanim\AppData\Roaming\Python\Python38\site-packages', 'C:\Program Files\Python38\lib\site-packages', 'C:\Program Files\Python38\lib\site-packages\win32', 'C:\Program Files\Python38\lib\site-packages\win32\lib', 'C:\Program Files\Python38\lib\site-packages\Pythonwin'] Server time: Sun, 19 Sep 2021 07:44:37 +0000 views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View, TemplateView, ListView, DetailView from home import models class IndexView(ListView): context_object_name = 'musician_list' model = models.Musician template_name = 'first_app/index.html' class MusicianDetail(DetailView): context_object_name = 'musician' model = models.Musician template_name = 'first_app/musician_details.html' models.py from django.db import models # Create your models here. class Musician(models.Model): first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) instrument=models.CharField(max_length=50) def __str__(self): return self.first_name + " " + self.last_name class Album(models.Model): artist=models.ForeignKey(Musician, on_delete=models.CASCADE) name=models.CharField(max_length=100) release_date=models.DateField() rating=( (1,"Worst"), (2,"Bad"), (3,"Not Bad"), (4,"Good"), (5,"Excellent!"), ) num_Stars=models.IntegerField(choices=rating) def __str__(self): return self.name +", Rating: " +str(self.num_Stars) models.py from django.contrib import admin from django.urls import path from home … -
Django: How to create a separate endpoint login link for admin/staff users
Currently I've been using the generic login/register links (.../account/login, .../account/register etc) which lets all users (staff and non-staff) to login. I'm creating a separate app for only staff members and I'd like to have a separate endpoint link (.../acccount/staff-login) that would only allow staff members to get tokens. This seems pretty basic but I haven't been able to find anything for this. -
Reorder django form fields
I try to reorder a form fields but I do not find a proper way. This is my form class UserSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(UserSignupForm, self).__init__(*args, **kwargs) self.fields["first_name"] = CharField(label="Prénom") self.fields.keyOrder = ['first_name', 'email', 'password1', 'password2'] and the render into the template <form class="signup" id="user_signup_form" method="post" action="{% url 'user_signup' %}"> {% csrf_token %} {{ form|bulma }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/> {% endif %} <button type="submit" class="button is-primary">{% trans "Sign Up" %}</button> </form> as you can see, I override the SignupForm from django-allauth with a field addition. Then, I would like to reorder fields to set the first_name as 1st fields. Unfortunately, I do not find a solution and don't want to edit the html render. Any solution ? -
Django forms for quiz app ( how to disable a form after submission )
I am creating a classroom app. Which has a exam section where students can give test. If a student wants to give a exam he/she has to select subject and then has to go in exam section. I want student to have access to exam form for one time. -
Cannot change istance in a queryset/dropdownlist, with no errors
I am currently developing an app to manage apartments. One requirement is to be able to handle payment from tenants by utilizing his room/security deposit. For this case, the involve models will be as follows (minimum setup): ''' class Billing(models.Model): bill_batch = models.ForeignKey(BillBatch, on_delete=models.PROTECT) reservation = models.ForeignKey( 'tenants.Reservation', on_delete=models.PROTECT) rental = models.DecimalField(max_digits=9, decimal_places=2, default=0) electricity = models.DecimalField(max_digits=9, decimal_places=2, default=0) water = models.DecimalField(max_digits=9, decimal_places=2, default=0) class SecurityDeposit(models.Model): payments = models.ForeignKey(Payment, on_delete=models.PROTECT) reservations = models.ForeignKey( 'tenants.Reservation', on_delete=models.PROTECT) deposit_date = models.DateField(default=date.today, verbose_name='Date deposited') deposited_amount = models.DecimalField(max_digits=9, decimal_places=2, default=0, verbose_name='Amount deposited') class ConsumeDeposit(models.Model): billings = models.ForeignKey( 'billings.Billing', on_delete=models.PROTECT) security_deposits = models.ForeignKey( SecurityDeposit, on_delete=models.PROTECT) pay_date = models.DateField() allocated_amount = models.DecimalField( max_digits=9, decimal_places=2, default=0) ''' In my code, ''' class ConsumeDepositEditMixin(object): def dispatch(self, request, *args, **kwargs): self.consume_deposit = get_object_or_404( SecurityDeposit, id=self.kwargs['deposit_id']) # the qs must contain only billings exclusive to the reservation # by which the deposit is allocated for; that is, deposit can't be consumed # by other room reservations of the same tenant self.billing_qs = Billing.objects.filter( reservation=self.consume_deposit.reservations) # TODO: need fix, can't change billing item return super().dispatch(request, *args, **kwargs) def get_form(self, form_class=None): form = super().get_form(form_class=None) form.fields['security_deposits'].widget = forms.HiddenInput() form.fields['billings'].queryset = self.billing_qs return form ''' In the tests I made, I have 2 billings available, … -
Django - PUT endpoint authenticator error "wrapped_view() missing 1 required positional argument: 'request'"
So I'm trying to create a PUT endpoint for editing post data. In the endpoint the post id is given in the URL then the new post dated is inserted into the entity. The issue I'm running into is that request isn't coming through on the authenticator (I'm using Cognito to authenticate, not super important for the error). So even though you can see I'm clearly passing in data, the request isn't coming through on the wrapped_view in the cognito_authenticator function. Why is this happening? The error I'm getting is: "wrapped_view() missing 1 required positional argument: 'request'" Test.py def test_edit(self): response = self.client.put(reverse('edit_post_by_id', kwargs={'post_id': str(self.post.uuid)}), data={'body': 'updated text #update'}, content_type='application/json', **{'HTTP_AUTHORIZATION': f'bearer {self.cognito.access_token}'}) self.assertEqual(response.status_code, status.HTTP_200_OK) View.py @api_view(['PUT']) @method_decorator(cognito_authenticator) def edit_post(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse(dict(error=f'Post id: {post_id} does not exists'), status=status.HTTP_400_BAD_REQUEST) authenticator def cognito_authenticator(view_func=None): if view_func is None: return partial(cognito_authenticator) @wraps(view_func) def wrapped_view(request, *args, **kwargs): # Check the cognito token from the request. auth = request.headers.get("Authorization", None) if not auth: return Response(dict(error='Authorization header expected'), status=status.HTTP_401_UNAUTHORIZED) parts = auth.split() if parts[0].lower() != "bearer": return Response(dict(error='Authorization header must start with bearer'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) == 1: return Response(dict(error='Token not found'), status=status.HTTP_401_UNAUTHORIZED) elif len(parts) > 2: return Response(dict(error='Authorization header … -
Field 'card_exp_month' expected a number but got (4,) - Django and stripe API when adding to model
I'm writing a second ecommerce site. The first one seems to work perfectly well when downloading data from the stripe API. It extracts the card details and saves the information to the model perfectly. The second site, I keep getting the following error and I can't see why. Any help to track this down would be great! Field 'card_exp_month' expected a number but got (4,). This is the code which is being run to save the data I'm getting: def process_card(order, charge): print("I HAVE THE DATA AS: ", charge) print("I have the brand as: ", charge.payment_method_details.card.brand) print("I have the expiry year as: ", charge.payment_method_details.card.exp_year) print("I have the expiry month as: ", charge.payment_method_details.card.exp_month) print("I have the last 4 as: ", charge.payment_method_details.card.last4) payment = order.payment payment.stripe_payment_intent = order.stripe_payment_intent payment.total_paid = Money(charge.amount / 100, charge.currency) payment.card_brand = str(charge.payment_method_details.card.brand), payment.card_exp_year = int(charge.payment_method_details.card.exp_year), payment.card_exp_month = int(charge.payment_method_details.card.exp_month), payment.card_last4 = str(charge.payment_method_details.card.last4), payment.receipt_url = charge.receipt_url payment.save() order.stripe_payment_intent = None order.order_flow = "PAID" order.save() When I view the console I get the following output which seems to show the correct values followed by the error message! I have the brand as: visa I have the expiry year as: 2024 I have the expiry month as: 4 I have the … -
how to return queryset as a list on seperate lines, without the brackets
I have my model for my lessons: class Lessons(models.Model): student = models.ForeignKey(Students, on_delete=models.SET_NULL, null=True) headed_by = models.ForeignKey(Tutors, on_delete=models.SET_NULL, null=True) day = models.CharField(max_length=4, choices=DAY_CHOICES, null=True) start_time = models.TimeField(null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True) price_band = models.CharField(max_length=7, choices=PAYMENT_TYPE_CHOICES, blank=True, null=True) created = models.DateTimeField(auto_now_add=True ) def __str__(self): return str(self.student) + " at " + str(self.start_time)+ " on " + str(self.day) class Meta: ordering=['student',"headed_by",'day','start_time'] I have my Query set: tn_mon = Lessons.objects.all().filter(headed_by__name="Tutor Name").filter(day__icontains="Mon") which returns <QuerySet [<Lessons:Studentname1 at Time on Day>, <Lessons:Studentname2 at Time on Day> how can i return the output without the queryset, ,<> [] so that it returns as set out like below? Studentname1 at Time on Day, Studentname2 at Time on Day -
My urls is not updating correctly adding some extra path itself
I want to update the lead lead of the url If you look on the url section it says update_lead/1 which is perfectly right but when i hit update lead i am getting extra update lead in the url section due to which django cant reach its function i am very confuse about it please help here are my codes from update_lead.html {% extends 'base.html' %} {% block exhead %} {% endblock exhead %} {% block body %} <div class="container"> <h2>Update Lead</h2> <form action="update_lead_handle" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control" id="inputEmail4" required name="name" value="{{lead.name}}"> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Subject</label> <input type="text" class="form-control" id="inputPassword4" name="subject" required value="{{lead.subject}}"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputAddress">Email</label> <input type="email" class="form-control" id="inputAddress" name="email" placeholder="abc@email.com" value="{{lead.email}}"> </div> <div class="form-group col-md-6"> <label for="inputAddress2">Contact Number</label> <input type="number" class="form-control" id="inputAddress2" name="number"value = "{{lead.mobile_no}}" placeholder="99XX80XXXX"> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Source</label> <select id="inputState" class="form-control" name="source" > <option selected value="{{lead.source}}">{{lead.source}}</option> {% for x in source %} <option value="{{x.name}}">{{x.name}}</option> {% endfor %} </select> </div> <div class="form-group col-md-4"> <label for="inputState">Assign To</label> <select id="inputState" class="form-control" name="assign"> <option selected value="{{lead.assign_to}}">{{lead.assign_to}}</option> {% for x in agent %} <option value="{{x.name}}">{{x.name}}</option> {% endfor %} … -
Django unit-testing for ProfileEditForm with disabled (read-only) fields
I want to write unit tests for my ProfileEditForm form that has some fields with disabled=True. So, these fields are read-only and cannot be changed. I want to test this logic. As far as I know, I don't have to give disabled fields to the form. The form itself validates these fields. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=63, blank=False) last_name = models.CharField(max_length=63, blank=False) about_me = models.CharField(max_length=511, blank=True) forms.py class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = [ "username", "email", "first_name", "last_name", "about_me", ] username = forms.CharField(label="Username", disabled=True) email = forms.EmailField(label="Email", disabled=True) first_name = forms.CharField(label="First Name", max_length=63, required=False) last_name = forms.CharField(label="Last Name", max_length=63, required=False) about_me = forms.CharField(label="About Me", max_length=511, required=False) tests.py class ProfileEditFormTests(TestCase): def setUp(self) -> None: self.user = get_user_model().objects.create_user(username="testuser", email="test@test.com", password="password123") self.profile = Profile.objects.create(user=self.user) def test_email_field_is_not_editable(self): form_data = { "username": self.profile.user.username, "email": self.profile.user.email, "first_name": "first", "last_name": "last", "about_me": "", } form = ProfileEditForm(data=form_data) self.assertTrue(form.is_valid()) I get: AssertionError: False is not true When I print out the form errors with print(form.errors): <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>email<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Even if I provide all fields, the form is still invalid. form_data = { "username": self.profile.user.username, "email": self.profile.user.email, "first_name": "first", "last_name": "last", "about_me": "", } … -
Reverse for 'edit-item' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['dashboard/edit\\-item/(?P<slug>[^/]+)/$']
Can you please help me to find out the problem. Previously, the functions for editing and deleting the item are work. But, currently it shows me errors and I cannot find out the reason why this error happened suddenly. Can you guys please help me. I will be very appreciated. html {% for object in furniture %} <tr class="clickable-tr" href="{{ object.get_absolute_url }}"> <td>{{ object.furnitureId }}</td> <td>{{ object.furnitureName }}</td> <td>{{ object.categoryId.categoryName }}</td> <td class="text-center">{{ object.stock }}</td> <td class="text-center"> <a href="{{ object.slug }}"> <i class='material-icons' style="color: brown;">delete</i> </a> </td> </tr> {% endfor %} models.py def get_absolute_url(self): return reverse("administration:edit-item", kwargs={ 'slug': self.slug }) def delete_item_url(self): return reverse("administration:delete-item", kwargs={ 'slug': self.slug }) urls.py app_name = 'administration' urlpatterns = [ path('products/',views.prodManagement,name='dashboard'), path('add-item/',views.addProduct,name='add-item'), path('edit-item/<slug>/',views.editProduct, name='edit-item'), path('delete-item/<slug>/',views.deleteItem, name='delete-item'), ] views.py def prodManagement(request): context = { 'furniture':Furniture.objects.all(), 'category':Category.objects.all() } return render(request, 'admin/prod_management.html', context) def editProduct(request, fid): item = get_object_or_404(Furniture, slug=fid) category = Category.objects.all() context = { 'object':item, 'category':category } return render(request, 'admin/item.html', context) def deleteItem(request, slug): print('here') item = get_object_or_404(Furniture, slug=slug) item.delete() messages.success(request, 'Item is deleted.') return redirect('administration:dashboard') -
cant solve the problem > TypeError: create_superuser() missing 1 required positional argument: 'image'
hello there im new to django and im trying to create my own custom user and this TypeError made me go crazy while i was trying to run py manage.py createsuperuseri dont know how to fix it please review my problem and help me <3 if im missing any other things to mentions please tell me so i will edit my case TypeError: create_superuser() missing 1 required positional argument: 'image' from django.db import models import os from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager class customMemberManager(BaseUserManager): def create_user(self, email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields): if not email: raise ValueError('YOU MUST ENTER VALID EMAIL') email = self.normalize_email(email) user = self.model(email=email, mobileNumber=mobileNumber, name=name, image=image, familyName=familyName, password=password, nationalCode=nationalCode, **other_fields) user.set_password(password) user.image = image user.save() return user def create_superuser(self, email, mobileNumber, name, familyName, image, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50) familyName = models.CharField(max_length=50) email = models.EmailField(max_length=50) nationalCode = models.IntegerField(null=True) mobileNumber …