Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Payment gateway Integration in django
I am implementing the payment integration in Django and creating api using Django rest framework. Want print response of the sandbox link with the parameter like fullname,email,phone which is coming from frontend. I am getting the data from front end but can't able to pass the parameter in the link. I am not getting that how to pass the parameter in the sandbox link. I replaced '{}' to '{{}}' but this also didn't work. @api_view(['POST']) def user_payment(request): headers = { 'Content-Type': 'application/json' } successUrl= 'https://****/thank.html?test=*' cancelUrl= 'https://*********' serializer = user_payment_detailSerializer(data=request.data) #print(request.data) print(serializer) data=request.data fullName=data['fullname'] email=data['email'] phone = data['phone_number'] sum = data['total_amount'] reques = requests.get(f"https://sandbox.abcd.co.il/server/createPaymentProcess/?pageCode={pageCode}&sum={sum}&successUrl={successUrl}&cancelUrl={cancelUrl}&pageField[fullName]={fullName}&pageField[phone]={phone}&pageField[email]={email}", headers=headers) response_body = reques.text print(response_body) if serializer.is_valid(): pass # serializer.save() return render(request,'home.html') -
How to pass a variable coming from HTML to another django view function
Intro: I've been looking for all stackoverflow questions but unfortunately after hours of research I cannot find a solution that suits my needs. I have a variable generated after the user submits a form. I get this variable using an Ajax call and then I pass it to a django view. file.html //if user clicked submit button, call ajax to pass variable to django view $('#submit').click(function() { var dato = 0; $.ajax({ url: '{% url 'todo:get_dato' %}', dataType: 'text', method: "POST", data: { csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), data: JSON.stringify(dato), }, success: function(data, status, xhr){ }, error: function(xhr, status, error){ } }) }) Problem: I can "receive" this variable into a django view function but I cannot pass ajax_date variable to another view function inside the same views.py file views.py 1st function where I get ajax variable coming from HTML @login_required @user_passes_test(staff_check) def get_dato(request): if request.method == 'POST' and 'data' in request.POST: ajax_response_dict = json.loads(request.POST['data']) ajax_date = ajax_response_dict.get('date_id') request.session['ajax_date'] = ajax_date 2nd function where I need to use ajax_date variable @login_required @user_passes_test(staff_check) def calendario(request): form = EventForm(request.POST) if form.is_valid(): form.save() #HERE I NEED TO USE VARIABLE ajax_date = request.session.get('ajax_date') Actual situation: If I print ajax_date from 2nd function I got: None <class 'NoneType'> while … -
Django - AttributeError 'str' object has no attribute 'court_number'
My edit view in my application won't update the court details whenever I want to edit it. I keep getting the error below. Adding, Viewing & Deleting functions are working okay. I cant find a solution on the other S/O answers. Some help on this would be appreciated. Thanks Exception Value: 'str' object has no attribute 'court_number' model.py # Create your models here. class Court(models.Model): court_number = models.CharField(max_length=255, verbose_name='Court Number.') accused_person = models.ForeignKey(AccusedPerson, on_delete=models.CASCADE, verbose_name='Accused Person') court = models.CharField(choices=COURTS, max_length=255, verbose_name='Court') court_verdict = models.CharField(choices=VERDICT, max_length=50, verbose_name='Court Status') scheduled_on = models.DateField(verbose_name='Scheduled On') created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='Police Officer') date_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') date_updated = models.DateTimeField(auto_now=True, verbose_name='Date Updated') def __str__(self): return str(self.court_number) class Meta: verbose_name_plural = 'Court' forms.py class EditCourtInfoForm(forms.Form): court_number = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'id': 'court_number', 'class': 'form-control mb-4', 'name': 'court_number', 'placeholder': 'Court Number'})) accused_person = forms.ChoiceField(required=True, widget=forms.Select(attrs={'id': 'accused_person', 'class': 'form-control mb-4', 'name': 'accused_person', 'placeholder': 'Accused Person'})) court = forms.ChoiceField(choices=COURTS, required=True, widget=forms.Select(attrs={'id': 'court', 'class': 'form-control mb-4', 'name': 'court', 'placeholder': 'Court'})) court_verdict = forms.ChoiceField(choices=VERDICT, required=True, widget=forms.Select(attrs={'id': 'court_verdict', 'class': 'form-control mb-4', 'name': 'court_verdict', 'placeholder': 'Verdict'})) scheduled_on = forms.DateField(required=True, widget=forms.DateInput(attrs={'type': 'date', 'id': 'scheduled_on', 'class': 'form-control mb-4', 'name': 'scheduled_on', 'placeholder': 'Scheduled On'})) def __init__(self, *args, **kwargs): super(EditCourtInfoForm, self).__init__(*args, **kwargs) self.fields['accused_person'].choices = [(e.pk, f"{e.first_name}" + ' … -
How to compare dates in django
I am working on a task manager project, user can define the "ending date" of the task, I would like to change the front end code of a task that isn't completed before the "endind_date".I tried playing around in models.py but i get back this error: "can't compare datetime.datetime to datetime.date" models.py: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(max_length=200, null=True, blank=True) complete = models.BooleanField(default=False) importance = models.ForeignKey(Importance, null=True, blank=False, on_delete=models.CASCADE) creation_date = models.DateField(default=timezone.now) ending_date = models.DateField(null=True, blank=False) # jd = models.DateField(null=True, blank=True) def __str__(self): return self.title def is_end_date(self): if datetime.now() > self.ending_date: if not self.complete: return True else: pass else: pass html(only included related code to the problem): {% if task.is_end_date %} #code {% else %} #code -
I Use for loop inside django template, but Django Generic editing views don't send data to template
I'm very new to django. I'm creating student attendance system. I can add classes and students in each class. But when it comes to check attendance I get stuck. My model, form, view and template for checking attendance are here: models.py choice_list = [(1, 'Present'), (2, "Absent")] class AttendanceChecking(models.Model): pupil = models.OneToOneField(ClassPupils, on_delete=models.CASCADE, related_name='pupil_attendance') pupil_class = models.ForeignKey(SchoolClassess, on_delete=models.CASCADE, related_name='class_attendance') teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='responsible_attendance') date = models.DateField() mark_attendance = models.CharField(max_length=100, choices=choice_list, default='Present') forms.py choice_list = [(1, 'Present'), (2, "Absent")] class AttendanceForm(forms.ModelForm): mark_attendance = forms.ChoiceField(choices=choice_list) class Meta: model = AttendanceChecking fields = ('mark_attendance',) views.py class AttendanceListView(LoginRequiredMixin, FormView): form_class = AttendanceForm context_object_name = 'classes' model = SchoolClassess template_name = 'app_school/attendance_list_view.html' attendance_list_view.html {% extends 'base.html' %} {% block content %} <form method="POST"> {% if user.is_authenticated %} {% for pupil in classes.pupils.all %} {{ pupil.pupil_lname }} {{pupil.pupil_fname}} {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" name=""> {% endfor %} {% endif %} </form> {% endblock %} My purpose is creating a table which is the list of all students in a class and additional column for attendance as shown in image students list for checking attendance. when confirm button is clicked the data must be saved db table. I tried, but when I … -
im using django 4.0.2 and i have thist error
i'm new in django and i cant find the error to resolve, it appears on object 'user'. Any suggestions to make this work? It looks like in the past, this would be the answer class Checkout(LoginRequiredMixin, View): def post (self, request): addres = request.POST.get('addres') comment = request.POST.get('comment') cart = request.session.get('cart') user= request.session.get('user') product = Product.get_product_by_id(cart) print(addres, comment, User, cart, product ) for product in product: print(cart.get(str(product.id))) order = Order(user=User(id=user), product=product, price=product.price, addres=addres, comment=comment, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect ('cart:cart_detail') i was watching a tutorial and doing it but i cant resolve the error that appearsenter image description here, i cant find a solution yet class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product): if str(product.id) not in self.cart.keys(): self.cart[product.id]={ "product_id": product.id, "title":product.title, "quantity": 1, "image":product.image.url, "thumbnail":product.thumbnail.url, "price": str(product.price) } else: for key, value in self.cart.items(): if key== str(product.id): value["quantity"] = value["quantity"]+ 1 break self.save() def save(self): self.session["cart"] = 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 decrement(self, product): for key, value in self.cart.items(): if key == str(product.id): value["quantity"] = value["quantity"]- 1 if … -
Pesquisa por id em django
Estou tentando realizar uma busca por um imóvel pelo id do imóvel, mas não está me retornando nada, o código é seguinte: def buscaPorCodigo(request): id = request.GET.get('id') imovel = get_object_or_404(Imovei, id=id) sugestoes = Imovei.objects.filter(cidade=imovel.cidade).exclude(id=id)[:2] return render(request, 'imovel.html', {'imovel': imovel, 'sugestoes': sugestoes, 'id': id}) -
django pytest / update delete view testing
I'm working on pytest testing for my 1st django app, kind of cookery book. I have problems with edit/delete view tests. For example, i have a test for testing add recipe view. Here is recipe model: class Recipe(models.Model): """Instructions how to prepare a single dish.""" title = models.CharField(max_length=50) cooking_time = models.IntegerField(help_text='in minutes', validators=[MinValueValidator(1), MaxValueValidator(5000)]) difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') meal_plan = models.ManyToManyField('MealPlan', through='RecipeMealPlan') here is it's fixture: @pytest.fixture() def example_recipe(): rec = Recipe.objects.create(title='rec', cooking_time=10, difficulty_level=2, description='bla, bla, bla') return rec And tests which works fine: @pytest.mark.django_db def test_add_recipe(client, example_recipe): dct = { 'title': 'rec', 'cooking_time': 10, 'difficulty_level': 2, 'description': 'bla, bla, bla' } url = reverse('add-recipe') response = client.post(url, dct) assert response.status_code == 302 assert Recipe.objects.get(**dct) @pytest.mark.django_db def test_add_recipe2(client): url = reverse('add-recipe') response = client.get(url) assert response.status_code == 302 Now I'm trying to write test for recipe update/delete views. My recipe update test currently looks like this: @pytest.mark.django_db def test_ingredient_update_view(client, example_ingredient): url = reverse('update-ingredient', kwargs={'id': example_ingredient.id}) response = client.get(url) assert Ingredient.objects.save( name='cos', nutrient=2, glycemic_index=2 ) I know its wrong but i face problems to make it work. Same with delete view. Could someone take a look … -
What should I use to enter data to my database on Django? Django admin or SQL code?
I am a newbie in programming, but now I connected my project with PostgreSQL. I learned the way to enter by SQL code and also found out that we can actually enter /adming (by creating the superuser and add data there). So which one is widely used in webdev? -
Redis server run on heroku
I am using windows and I have deployed a Django project to heroku. This project need to run a redis server for a chatroom. I ran it perfectly on my localhost, but after I deployed it to heroku, the redis server only run in redis://127.0.0.1:6379 only. I have tried to change the redis.conf file from bind 127.0.0.1 to bind mywebsite but it doesn't work. Thanks for all help in advance -
How to send url from template to view in django
How can I send a URL from a template to a view? I have noticed that a normal string works but a URL doesn't. Here is what I have tried. path('imageviewer/<str:theimage>', mainviews.imageviewer, name="imageviewer"), def imageviewer(request, theimage): response = render(request, "imageviewer.html", {"theimage": theimage}) return response How I attempt to pass it : (value.image) is a url <a href="{% url 'imageviewer' theimage=value.image %}" class="effect-lily tm-post-link tm-pt-60"> Error I Get: Reverse for 'imageviewer' with keyword arguments '{'theimage': 'https://storage.googleapis.com/katakata-cb1db.appspot.com/images/humours/1643758561'}' not found. 1 pattern(s) tried: ['imageviewer/(?P<theimage>[^/]+)\\Z'] Thank you. -
What does the empty list passed in the assert function mean?
sorry for the weird title. I am currently learning Django, and going through their tutorial. In Part 5, it discusses test cases which I am understanding well. However, I am unclear what the last line of the snippet means. def test_future_question(self): #questions with a pub_date in the future aren't displayed on the index page. create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) Why must we pass an empty list? It doesn't make any sense to me, and I am just wanting to learn why. Thank you! -
How do i access request.user in self.client.post Testing
I have a model called Quote which has a ForeignKey pointing to User. I want to make a post request to create a Quote but i don't know what data i should give to self.client.post, this is what i got so far i am talking about the test_can_save_a_POST_request: from django.contrib.auth import get_user_model from django.test import TestCase from quotes.models import Quote from quotes.views import home_page User = get_user_model() class HomePageTest(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') def test_display_all_quotes(self): user1 = User.objects.create(email="rafik@test.com", password="foo") Quote.objects.create(text='quote 1', user=user1) Quote.objects.create(text='quote 2', user=user1) response = self.client.get('/') self.assertIn('quote 1', response.content.decode()) self.assertIn('quote 2', response.content.decode()) def test_can_save_a_POST_request(self): user1 = User.objects.create(email="rafik@test.com", password="foo") self.client.post('/', data={ 'quote_text': 'The first ever quote' } ) -
Error while deploying django channels to amazon elastic beanstalk
I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below. django.config ``` option_settings: aws:elasticbeanstalk:container:python: WSGIPath: playzone.wsgi:application aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static ``` Procfile ``` web: gunicorn playzone.wsgi websocket: daphne -p 5000 my_app.asgi:application ``` asgi.py ```py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( routing.websocket_urlpatterns ) }) And there are 2 more simple files `routing.py` and `consumers.py`. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying `WebSocket connection to 'ws://zzzzzzzzzzzz.com/ws/' failed:`. Please help me out on how I can fix it. Also am not using redis or any channel layer. Please help me out on how I can fix it. -
Webpack: Do not parse specific html tag
I'm using webpack to build html templates using Django's templating language. Django templates contain variables and tags using {{ }} and {% %} syntax. Webpack has ignored these just fine and built the html templates as expected, except when parsing srcset tags. Webpack errors when it tries to parse the following html: <source srcset="{% static 'images/my-image.png' %}"> I'd like webpack to either ignore all srcset tags completely, or have some sort of # noqa equivalent which makes webpack simply not make changes to this row of the file. Is that possible? -
Python: Run a code after return something
This is an ApiView from my django project: class Receive_Payment(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAdminUser,) def get(self, request, cc_number): if Card.objects.filter(cc_num = cc_number).exists(): client = Client.objects.get(client_id = (Card.objects.get(cc_num = cc_number).client)) if not client.is_busy: client.is_busy = True client.save() resp = "successful" else: resp = "client_is_busy" else: resp = "fail" return Response({"response": resp}) As you see, if client.is_busy is not True, I'm making it True in here. But in this situation, I need to client.is_busy = False after 30 seconds. If I do it under client.save() code, it delays to response. How can I do it? -
Django - UniqueConstraint not created
I am trying to enforce a constraint for mysql where user is prohibited from inserting twice the same name and model. E.g This should not be allowed to be inserted twice: name:Name1 model:Model1 #Model class Car(models.Model): name = models.CharField(max_length=100) model = models.CharField(max_length=100) #View class CarListCreateAPIView(generics.ListCreateAPIView): serializer_class = CarSerializer def get_queryset(self): trip_code = self.kwargs.get("pk") return Car.objects.filter(trip = trip_code) #Return cars for given trip #Seializer class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('__all__') constraints = [ models.UniqueConstraint(fields=['name', 'model'], name='car_name_model_constraint') ] The problem is that the constraint is never created and thus not enforced. What might be the issue with the code? -
Minio: InvalidRequest when change AWS_S3_FILE_OVERWRITE to False
When AWS_S3_FILE_OVERWRITE was equal to True everything worked fine. But when it was changed to False I get error (when click on link on frontend): At the same time if I copy a link to a file and paste it into browser directly there is no error. Why that's happening this way? P.S. Using django-storages -
model.objects.all() doesn't find anything when foreign key in model
when I load the website i get this error my models.py file looks like: # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.AutoField(primary_key=True) found_articles = models.ForeignKey( Information, on_delete=models.CASCADE) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) def __str__(self): return self.id in my view.py file: def show_articles_with_this_filter_id(request): all = Article_search.objects.all() print(all) return render(request, 'show_article.html') when I get to the print statement I get the error shown in the picture: Unknown column 'database_article_search.found_articles_id' in 'field list' why is the part _id pasted behind found_articles? -
Python simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) while in request.post data
I am trying to post a request with data as following payload={'request_payload': {'name': 'logo', 'description': 'logo file', 'det': {'download_allowed': True, 'watermark': True, 'readonly': False}, 'cat': {'0': 'Tax', '1': '2007', 'Type': '2'}, 'document_type': ['xxxxxxxxx']}} requests.post(url,headers=headersAuth,files=files, data=payload) Which causes this error: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) So i tried using postman which generates the following payload which has single quotes for the value and request.post is success. payload={'request_payload': '{'name': 'logo', 'description': 'logo file', 'det': {'download_allowed': True, 'watermark': True, 'readonly': False}, 'cat': {'0': 'Tax', '1': '2007', 'Type': '2'}, 'document_type': ['xxxxxxxxx']}'} The problem is if i post the later payload in django api through its explorer it json parse error where i placed the single quotesDjango json error image Can anyone tell how to get value formatted as the second payload. Is there anything I am missing -
how can i manipulate several images in a directory and display them conditionally with django?
I have a folder that contains several images, I would then like to display the list of images that have the same name and number (eg: myfile_page1.png, myfile_page2.png, myfile_page2.png,) and then display them in the django template show_file.html -
clearing log file using Django
I am new to Django. I am trying to log the info messages to a log file and clear it every 10 mins. I tried the below code in settings.py 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR,'Logfile.log'), 'when': 'M', 'interval': 10, 'backupCount': 10, 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'main':{ 'handlers': ['file'], 'level': 'INFO', 'propagate': True, } }, I face error stating PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\Folder\LogFile.log' -> 'D:\Folder\LogFile.log.2022-02-24_12-08' I understand the error that I can't rename a file that's open. I would like someone to help me in resolving this and helping me clear the log file. Thanks in advance -
How to insert data using stored procedure in django for mssql?
I get this error, ValueError at /health/ The view Healthcare.views.Sp_tbl_user_detail_views didn't return an HttpResponse object. It returned None instead. models class sp_tbl_user_detail(models.Model): userid = models.CharField(db_column='userID', primary_key=True,max_length=36,editable = False) # Field name made lowercase. username = models.CharField(unique=True, max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS') userfirstname = models.CharField(max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') userlastname = models.CharField(max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') user_contact = models.BigIntegerField(unique=True) user_dob = models.DateField() gender = models.CharField(max_length=1) height = models.FloatField(max_length=6) weight = models.FloatField(max_length=6) blood_group = models.CharField(max_length=3) user_password = models.CharField(max_length=30) # This field type is a guess. user_email=models.CharField(unique=True,max_length=100,db_collation='SQL_Latin1_General_CP1_CI_AS) addedby = models.CharField(max_length=36) addedon = models.DateTimeField(blank=True,null=True,auto_now_add=True) updatedby = models.CharField(max_length=36, blank=True, null=True) updatedon = models.DateTimeField(blank=True,null=True,auto_now=True) active = models.BooleanField() views def Sp_tbl_user_detail_views(request): if request.method=='POST': if request.POST.get('userid') and request.POST.get('username') and request.POST.get('fname') and request.POST.get('lname') and request.POST.get('pnumber') and request.POST.get('dob') and request.POST.get('gender') and request.POST.get('height') and request.POST.get('weight') and request.POST.get('bloodgroup') and request.POST.get('password') and request.POST.get('emailid'): empsave=sp_tbl_user_detail() empsave.userid=str(uuid.uuid4()) empsave.username=request.POST.get('username') empsave.fname=request.POST.get('fname') empsave.lname=request.POST.get('lname') empsave.pnumber=request.POST.get('pnumber') empsave.dob=request.POST.get('dob') empsave.gender=request.POST.get('gender') empsave.height=request.POST.get('height') empsave.weight=request.POST.get('weight') empsave.bloodgroup=request.POST.get('bloodgroup') empsave.password=request.POST.get('password') empsave.emailid=request.POST.get('emailid') empsave.addedby='55CD065E-29ED-442D-90AA-C6A443757CE5' cursor=connection.cursor() cursor.execute ("sp_tbl_user_detail '"+empsave.userid+"','"+empsave.username+"','"+empsave.fname+"','"+empsave.lname+","+empsave.pnumber+"','"+empsave.dob+"','"+empsave.gender+","+empsave.height+","+empsave.weight+",'"+empsave.bloodgroup+"','"+empsave.password+"','"+empsave.emailid+"','"+empsave.addedby) #cursor.execute ("sp_tbl_user_detail (@userID='%s',@username='%s',@userfirstname='%s',@userlastname='%s',@user_contact=%s,@user_dob='%s',@gender'%s',@height=%s,@weight=%s,@blood_group='%s',@user_password='%s',@user_email='%s')",(empsave.userid,empsave.username,empsave.fname,empsave.lname,empsave.pnumber,empsave.dob,empsave.gender,empsave.height,empsave.weight,empsave.bloodgroup,empsave.password,empsave.emailid)) messages.success(request,"Info saved successfully") print('User Created') return JsonResponse(empsave,safe=False) else: return render(request,'Index.html') Index.html <body> <center> <h2>Sign Up</h2> <form method="POST"> {% csrf_token %} <!--User ID: <input type = "text" name="userid" placeholder="Please enter your User Name" /><br/> --> USERNAME: <input type = "text" name="username" placeholder="Please enter your First Name" /><br/> First Name: <input type = "text" name="fname" placeholder="Please enter your First Name" … -
Django nestesd serializers problem for 'Subcategory' object is not iterable
I want to get the category and subcategory with my product serializer, but it is showing me this error that subcategory object is not iterable. I don't know what is the problem I tried the same nested procedure and it worked previously for another field but not with subcategory . #this is my model so you understand the relation class Category(models.Model): name = models.CharField(max_length=220) def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=220) class Product(models.Model): product_type_choices = [ ('With Cylinder', 'With Cylinder'), ('Without Cylinder', 'Without Cylinder'), ] setup_type_choices = [ ('Yes', 'Yes'), ('No', 'No'), ] user = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(max_length=220) image = models.ImageField(null=True, blank=True) product_type = models.CharField(max_length=220, null=True, blank=True, choices=product_type_choices) setup_type = models.CharField(max_length=220, null=True, blank=True, choices=setup_type_choices) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(max_length=10000) rating = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) numReviews = models.IntegerField(null=True, blank=True, default=0) old_price = models.DecimalField(max_digits=11, decimal_places=2) discount = models.IntegerField(blank=True, null=True) price = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) countInStock = models.IntegerField(blank=True, null=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) short_description = models.CharField(max_length=2000, blank=True, null=True) isCampaign = models.BooleanField(blank=True, null=True, default=False) _id = models.AutoField(primary_key=True, editable=False) def save(self, *args, **kwargs): self.price = Decimal(self.old_price * (100 - self.discount) / 100) return super(Product, self).save(*args, **kwargs) class Meta: ordering = ['-createdAt'] … -
Getting custom Django REST user class in React using JSON Web Token
Context: My project is using Django REST together with React. I have made a User class that extends AbstractBaseUser, based on this tutorial to get a couple extra fields, and to use email, instead of username, to authenticate. To log in, I'm using djangorestframework-jwt to get an access token in React. Problem: I haven't found a way to get a user instance from Django REST based on the JSON Web token. What I have tried: Tried using the JWTAuthentication with this view: @api_view(['POST']) @authentication_classes([JWTAuthentication]) def getUser(request, format=None): content = { 'user': str(request.user), 'auth': str(request.auth) } return Response(content) It does kinda work, since it returns the users email address and token, but I want to get all user fields. I also tried copying from this SO answer, but in setting.py I don't know how to specify the path to the JWTAuthentication class. My user class: from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): …