Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i delete record in user table that has foreign key with profile table?
I have profile table : ''' class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) gender = models.IntegerField(default=0) birth_date = models.CharField(max_length=12) ''' and User table that is relate with profile . i want to delete record from user table ,but i can not, ''' @csrf_exempt def delete_user(request,user_id): try: if 'json' in request.META.get('HTTP_ACCEPT'): user_selected = get_object_or_404(User, pk=user_id) user_selected.refresh_from_db() user_selected.delete() return JsonResponse({'code': 100}) else: return redirect('/') except: return JsonResponse({'code': 101}) ''' user_selected.delete() did not work!! -
Output lookup fields in serialiser for OneToOne relationship
I'd like to output in my API fields coming from two different (related) models. I have this models.py: class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return "%s %s" % (self.first_name, self.surname) # I don't want to change this. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', null=True, blank=True) first_nameUnregistered = models.CharField(max_length=120, null=True, blank=True) surnameUnregistered = models.CharField(max_length=120, null=True, blank=True) This is my views.py: class ProfileSerialiser(serializers.HyperlinkedModelSerializer): user = serializers.StringRelatedField(many=False) class Meta: model = Profile fields = ('first_nameUnregistered', 'surnameUnregistered', 'user') And the serialiser: class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerialiser Right now what I see when I go to my /api/profliles endpoint it: [ { "first_nameUnregistered": "", "surnameUnregistered": "", "user": "The full user name, coming from def __str__(self):" }, [...] I want to get something like: [ { "first_nameUnregistered": "", "surnameUnregistered": "", "user.first_name": "first name" "user.surnamee": "surname" }, [...] Lookups such as profile__user.first_name seem not to work, I cannot merge the two querysets because they're from different models, and I cannot use properties in the fields definition of the serialiser. How can I achieve what I want? -
Iterate over queryset in groups of a certain amount
Basically, I want to use a Bootstrap Carousel with a queryset. My question is as to how I should iterate over the queryset so that I can put three objects into a div and then the next three into another div and so on depending on the size of the queryset. See the preudocode below. {% for group in object_list/3 %} <div class=""> {% for object in group %} <p>{{object}}</p> {% endfor %} </div> {% endfor %} -
how to implementsentiment-analysis-roman-urdu in a Django website using django framework
i am implementing sentiment-analysis-roman-urdu in my website this is my idea,i completed my sentiment -analysis how to add it into my django webapp.is it possible to add it into Django web application?i am attaching a video link you can better understand what i want to implement link given below: https://drive.google.com/open?id=1Ji8K6TlJNofyinB0_em9vkOG13ZIb3rN after watch this video kindly tell me how i implementing in djangoapplication,note analysis are completed just need to put into web application -
How to use another model pk?
When I'm trying to add comment i get error. After adding comment I would like to redirect to post detail page. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='post_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 600 or img.width > 600: output_size = (600,600) img.thumbnail(output_size) img.save(self.image.path) class Comment(models.Model): email = EmailField() content = models.TextField() post = models.ForeignKey('Post', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('post-detail', kwargs={'post_pk': self.post.pk, 'comment_pk': self.pk}) views.py class CommentCreateView(CreateView): model = Comment fields = ['email', 'content'] class CommentDetailView(DetailView): model = Comment url.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/comment/', CommentCreateView.as_view(), name='post-comment'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] -
Errors while encoding the InMemoryUploadFile in to base64 encoded string in Django
I am trying to convert the image uploaded to the Django server to the base64 string. I have looked and tried various solutions mentioned on this site and other blogs. Finally I found the accepted answer here on stack-overflow - Encode Base64 Django ImageField Stream I tried - image = request.data.get("image", None) b64_img = base64.b64encode(image.file.read()) However this is throwing error - TypeError: must be str, not bytes Can anyone here help me out in figuring out how to actually convert InMemoryUploadedFile to the encoded base64 string? Thanks -
Making models.py for Django Rest Framework Primary key and foreign key
I made a models like this : from django.db import models import json # Create your models here. class Data(models.Model): node_id = models.ForeignKey("Node", on_delete=models.CASCADE) timestamp = models.DateTimeField() vibration = models.IntegerField() moisture = models.IntegerField() gps_latitude = models.CharField(max_length=250) gps_longitude = models.CharField(max_length=250) gyro_x = models.FloatField() gyro_y = models.FloatField() gyro_z = models.FloatField() accelero_x = models.FloatField() accelero_y = models.FloatField() accelero_z = models.FloatField() displacement = models.IntegerField() class Node(models.Model): node_id = models.IntegerField() latitude = models.CharField(max_length=250) longitude = models.CharField(max_length=250) lokasi = models.CharField(max_length=500) The Data models have endpoint at http://127.0.0.1:8000/api/data/ And Node models have endpoint at http://127.0.0.1:8000/api/node/ I want the node_id in Node class to become a primary key and the node_id from Data class to become a foreign key. I try to post to http://127.0.0.1:8000/api/node/ like this : { "node_id": 1, "latitude": "123", "longitude": "123", "lokasi": "eer" } And then I open the endpoint for Data models at http://127.0.0.1:8000/api/data/ to post some data. On the Node id field, it should be referring to node_id=1, but why it just referring to node object(8) which is the id that generates automatically from Django rest framework? It makes the post data look like this: { "id": 13, "timestamp": "2020-04-14T20:00:00+07:00", "vibration": 1, "moisture": 1, "gps_latitude": "123", "gps_longitude": "123", "gyro_x": 1.0, "gyro_y": 1.0, … -
Django: how to save file in different directory
I want to save the file in different directory according to username and type of job. When I try to save the file from admin, I am able to save file in my mention location but if I submit file through form i am unable to save in mention location. I did not get any error while saving form. Every thing get save even file name. But there is no any folder or file in media folder. If I save from admin panel folder is created and file is saved in defined location but it wont save in first attempt, file is saved in second attempt models.py def file_directory_path(instance, filename): return 'application/{0}/{1}/{2}'.format(instance.applied_job.post_user.username, instance.applied_job.title, filename) class Applicant(models.Model): applicant = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name='applicant') applied_job = models.ForeignKey( Job, on_delete=models.DO_NOTHING, related_name='applied_job') full_name = models.CharField(max_length=100, blank=True) email = models.CharField(max_length=100, blank=True) cv = models.FileField(blank=True, upload_to=file_directory_path) cover_letter = models.TextField() phone_number = models.BigIntegerField() def __str__(self): return f'{self.applied_job.title} applicant detail' views.py def jobApply(request): if request.method == 'POST': id= request.POST['job'] name= request.POST['name'] email=request.POST['email'] contact = request.POST['contact'] cv = request.POST['cv'] cover_letter = request.POST['cover_letter'] user = request.user job = get_object_or_404(Job, pk=id) application = Applicant(applicant = user, applied_job = job, full_name = name, email = email, phone_number = contact, cv = cv, … -
User specified Table for JWT Token in Python Django
I generate a JWT token in Python Django using the default Table auth_user. Now how can use my own table which contains more than column and used across the module and it stores the user data. for eg - erp_mst_temployee is my table. i need to validate and generate the JWT token based on this. -
Inline Form Set: Django 'main.Course' has no ForeignKey to 'main.Teacher'
I have this error and cant really to identify the error.In dynamic url routing I identify the url predifining the app name(main) then the url. <a class="btn btn-info" href="{% url 'main:teacher' teacher.fname %}">View</a> Could this be related with the error of inline form sets? Models: class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True,blank=True) fname = models.CharField(max_length=200) lname = models.CharField(max_length=200) tsc_no = models.CharField(max_length=200,blank=True,unique=True) email = models.CharField(max_length=200,blank=True,unique=True) password = models.CharField(max_length=200,blank=True) profile_picture = models.ImageField(verbose_name='profile_picture',upload_to='photos/%Y/%m/%d',blank=True) national_id = models.CharField(max_length=200,unique=True) dob = models.DateField(blank=True) phone_number = PhoneNumberField() status = models.CharField(max_length=200) clas_teacher = models.CharField(max_length=200,blank=True) date_of_join = models.DateField(blank=True) timetable_color = models.CharField(max_length=200) class Course(models.Model): course_id = models.AutoField(primary_key=True) course_name = models.CharField(max_length=200) description = models.CharField(max_length=200) teacher = models.ManyToManyField(Teacher) class Meta: ordering = ['course_name'] def __str__(self): return self.course_name The view: def addmoreteacher(request,pk_test): teacher = Teacher.objects.get(fname=pk_test) CourseFormSet = inlineformset_factory(Teacher,Course,fields = ('course_name','description')) formset = CourseFormSet(instance=teacher) #form = CourseForm(initial = {'teachers_teaching':teacher}) if request.method == 'POST': #form = TeacherForm(request.POST) #print(form) formset = CourseFormSet(request.POST,instance=teacher) if formset.is_valid(): formset.save() print("saved") return redirect('/') else: print(formset.errors) context = {'formset': formset} return render(request = request,template_name='main/addmoreteacher_form.html',context=context) -
Django, I want to save extra/custom field in built in django registration form
i am using UserCreationForm to register user but i need an extra field to add and save. i did it but it does not save in auth_user model. The extra field i named is accntype and i dont even see the field accntype created in auth_model, rest is being saved. My code is a whole mess sorry for that. my form.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.admin import widgets class signup(UserCreationForm): choice = (('visitor', 'Visitor'),('guest', 'Guest'),('contractor', 'Contractor')) first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField( required=True) accntype = forms.ChoiceField(choices=choice ,required=True) class Meta: model = User fields = ('accntype', 'username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.accntype = self.cleaned_data["accntype"] if commit: user.save() return user here is views.py from django.shortcuts import render, redirect from .form import signup from django.contrib.auth.models import User # Create your views here. def signupview(request): if request.method == 'POST': form = signup(request.POST) if form.is_valid(): user = form.save(commit=False) user.type = form.cleaned_data['accntype'] user.save() return redirect('login') else: form = signup() return render(request, 'registration/signup.html', {'form': form}) signup.html {%load static%} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type='text/css' href="{%static 'css/signup.css'%}"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@800&display=swap" rel="stylesheet"> <title>Sign-up</title> </head> <body> <div class='header'> … -
Why django inlineformset not updating?
I am using inline formset to insert data from 2 model with relation, the create view was success, but i have problem when it need to update data or add new data in update view, I figure out that the inlineformset doesn't valid in form_valid. This is my code Update View class ProductUpdateView(DashProductMixin, DashUpdateView): """ProductUpdateView.""" model = Product form_class = product_forms.DashProductForm template_name = 'dash/product/update.html' def get_context_data(self, **kwargs): """Override get context.""" if self.request.POST: # context['harga_bertingkat_formset'] = HargaBertingkatFormset(self.request.POST) context['harga_bertingkat_formset'] = HargaBertingkatInlineFormset(self.request.POST, instance=self.object) else: # context['harga_bertingkat_formset'] = HargaBertingkatFormset(queryset=HargaBertingkat.objects.none()) context['harga_bertingkat_formset'] = HargaBertingkatInlineFormset(instance=self.object) return context def form_valid(self, form): """Override form valid.""" context = self.get_context_data() harga_bertingkat_formset = context['harga_bertingkat_formset'] # product = form.save() with transaction.atomic(): self.object = form.save() if harga_bertingkat_formset.is_valid(): print("#HRg", harga_bertingkat_formset) harga_bertingkat_formset.instance = self.object harga_bertingkat_formset.save() return super(ProductUpdateView, self).form_valid(form) My form class DashProductHargaBertingkatForm(forms.ModelForm): """Product Harga Bertingkat Form.""" class Meta: model = HargaBertingkat exclude = () HargaBertingkatInlineFormset = inlineformset_factory( Product, HargaBertingkat, form=DashProductHargaBertingkatForm, fields=['max_quantity', 'min_quantity', 'price'], extra=1, can_delete=True ) This my template {{ harga_bertingkat_formset.management_form }} <table id="item_table" class="table table-hover custom-table"> <thead> <tr> <th class="col-form-label">Min quantity:</th> <th class="col-form-label">Max quantity:</th> <th class="col-form-label">Price:</th> <th>Tambah</th> </tr> </thead> <tbody> {% for frm in harga_bertingkat_formset %} <tr class="current-form-row"> <td> {% render_field frm.min_quantity|add_error_class:"is-invalid" class="form-control" %} {% for error in frm.min_quantity.errors %}<div class="invalid-feedback">{{ error }}</div>{% endfor %} … -
How to connect two models User and Profile in one form to edit
How to connect two models User and Profile in one form. When I add new User everything work and I can edit User and Profile in html form but only data from User is showing up (Profile data is not displayed). How can I fix that? models.py from phonenumber_field.modelfields import PhoneNumberField from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) worker_number = models.DecimalField(max_digits=4, decimal_places=0, null=True, blank=True) phone = PhoneNumberField(region='PL', null=True, blank=True) image = models.ImageField(upload_to='Workers_photo', null=True, blank=True,) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile from phonenumber_field.formfields import PhoneNumberField class SignUpForm(UserCreationForm): worker_number = forms.DecimalField(max_digits=4, decimal_places=0, required=True, help_text='*') phone = PhoneNumberField(region='PL', required=False, help_text='*') image = forms.FileField(required=False) first_name = forms.CharField(max_length=30, required=True, help_text='*') last_name = forms.CharField(max_length=30, required=True, help_text='*') email = forms.EmailField(required=True, help_text='*') class Meta: model = User fields = ('worker_number', 'username', 'first_name', 'last_name', 'email', 'phone', 'image', 'password1', 'password2',) views.py @login_required def edit_worker(request, id): user = get_object_or_404(User, pk=id) form = SignUpForm(request.POST or None, request.FILES or None, instance=user) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.worker_number = form.cleaned_data.get('worker_number') user.profile.phone = form.cleaned_data.get('phone') user.profile.image = form.cleaned_data.get('image') user.save() raw_password … -
cant register user with user profile
i have problem with registartion user user profile and patient in same time i get errors like { "profile": [ "This field is required." ], "patient": [ "This field is required." ] } or bad request 400 77 in my cmd i cant understand whats wrong my code Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('date_of_birth',) class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = ('blood_type',) class RegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required = True) patient = PatientSerializer(required = True) class Meta: model = User fields = ('id', 'username', 'email', 'password','profile','patient',) extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') patient_data = validated_data.pop('patient') user = User(**validated_data) username = user.username password = validated_data.pop('password') user.set_password(password) user.save() profile = Profile.objects.create(user=user,name=username,**profile_data) Patient.objects.create(profile=profile,**patient_data) return user Views.py class RegisterAPIView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) My registration form in react class RegisterForm extends Component { renderField = ({ input, label,className, type, meta: { touched, error } }) => { return ( <div className={`field ${touched && error ? 'error' : ''}`}> <label>{label}</label> <input {...input} type={type} … -
Why is React/TypeScript/axios ignoring my session cookies?
Good day, fine Stack Overflow citizens. I have a Django back end serving a React front end. React uses axios to perform requests and handle CSRF magic (which Django employs out of the box). I had a fun time reacquainting myself with the ins and outs of CSRF and CORS, and finally managed to get things running with Django (using Django REST Framework) serving on http://localhost:8000 and React on http://localhost:3000. I especially love how you can set the following and dust your hands off from otherwise tiring details: axios.defaults.xsrfCookieName = XSRF_COOKIE_NAME; axios.defaults.xsrfHeaderName = XSRF_HEADER_NAME; axios.defaults.withCredentials = true; However, now that I've deployed this code into my production environment, Django complains when I try to log in (with the message CSRF verification failed. Request aborted). After some digging, I found this to be because even though Django sends Set-Cookie headers with the CSRF token, it isn't being set in my browser. I have the following headers in my client request: Host: backend.example.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0 Accept: application/json, text/plain, */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Origin: https://frontend.example.com Connection: keep-alive Referer: https://frontend.example.com/login And this is the server response: HTTP/1.1 200 OK Connection: keep-alive Server: … -
How to join a table that is not subject to a foreign key constraint to an outer join
I would like to know how to join a table that is not subject to a foreign key constraint to an outer join with Django. from django.db import models class Member(models.Model): name = models.CharField(max_length=50) class Meta: db_table = 'member' class GroupMember(models.Models): group_id = models.IntegerField() member = models.ForeignKey(Member, on_delete=models.CASCADE) class Meta: db_table = 'group_member' class Profile(models.Model): type = models.IntegerField() member = models.ForeignKey(Member, on_delete=models.CASCADE) profile = models.CharField(max_length=50) class Meta: db_table = 'profile' In a model such as this one, after externally combining group_member of a specific group_id and profile of a specific type by member_id, the result of writing an SQL statement is select * from group_member left outer join profile on group_member.member_id=profile.member_id and type=1 where group_id=1; and type=1 where group_id=1; we want to get the result we got with res = GroupMember.objects.filter(member__groupmember__group_id=1).filter(member__profile__type=1) to join via member, but SELECT "group_member"." id", "group_member"." "group_id", "group_member"." member_id" FROM "group_member" INNER JOIN "member" ON ("group_member"." member_id" = "member"." id") INNER JOIN "group_member" T3 ON ("member"." id" = T3. "member_id") INNER JOIN "profile" ON ("member"." id" = "profile"." member_id") WHERE (T3. "group_id" = 1 AND "profile"." type" = 1) and it didn't work. Please tell me how to resolve this problem. Thank you very much. -
How can I sum in html table?
I want to create a table dynamically and i have to refresh the rowspan every time, so i want to sum the length of each key with 1, I prefer avoid using Javascript/Jquery enter image description here that's my code -
Is there a library for emoji tooltip in Django?
So I'm a newbie in Django, and wondering if there is a library that has emoji tooltip. (I'm not even sure you call it 'tooltip') The best example I think is the one that Notion has. As you may know, you can freely use emoji (may be from getemoji.com?) in Notion. What I eventually want is to let user select appropriate emoji that best expresses his/her feeling in diary app. I have no idea on how it works and would very much appreciate your advice. Thank you very much in advance. :) -
how I can properly get the aggregation of these fields
models class Joint(models.Model): welder = models.ManyToManyField(Employee, related_name='welders') inch_dia = models.FloatField(blank=True, null=True) views context['welder'] = Joint.objects.values('welder__first_name', 'welder__last_name') .order_by('welder__first_name') \ .annotate(total_inch=Sum(F('inch_dia'))/Count(F('welder__first_name')) , output_field=IntegerField()) gives me the following error QuerySet.annotate() received non-expression(s): <django.db.models.fields.IntegerField> -
Nothing happens when I use: python manage.py command
I'm a beginner in coding and I just started watching a django tutorial by net ninja and it got to a point that I have to use "python manage.py runserver" and it does just nothing but I did everything exactly like in the video. I searched the internet and found some people that have the same problem but no answer to it. Here is the video that I learn from https://www.youtube.com/watch?v=jAE94gzgQvI&t=223s . -
How to render something in React only if a link has been clicked?
I am learning how to use Django and React together, and I state that I don't know if what I am trying to do is best practise (if not, please let me know what is the best way to achieve this, as I am quite sure this is a design pattern). So I have managed to render some data in the frontend by fetching it from my backend API (built with Django Rest Framework). What I would like to do is to render a list of objects only if the user clicks on a tag. How can I achieve that? Obviously I don't want to redirect to 'api/....' but rather redirect the user on the same page, which based on that link being clicked should display the list. Just to make it clear here is a screenshot: When I click on the 'Your Assessments' link I would like the list (in this case 'Test1', 'Test2', 'Test3') to be displayed. How can I implement this? Is a link the better choice for what I want to achieve or should I rather use a button and watch for an 'onClick' event? Or do I have to write Django views into 'frontent/views.py'? Here … -
sharing a (django-channels 1.x) channel_session variable between 2 users?
I wrote a lot of code with the assumption that a channel_session variable defined inside of a Group would be shared by all the users inside of that Group. I was wrong -- it is only defined for the one user. I need both users in a Group to be able to access one class instance. I am using attrs+cattrs for serialization so that is not a problem. I am storing this class instance in the channel_session variable. This class instance contains the game state (the app is a game): creator/opponent x,y history, current direction, etc. It's a very simple game. Tron lightcycles, but to move, the user must answer a math problem. Please help. Thanks. -
Django PayPal and dynamic price
I'm using Django PayPal for subscriptions for users in my app which also has coupons. Coupons are created by the admin, with coupon code, and discount value which gets calculated and results a total price. And I was wondering, since im new to PayPal with django - how can I change the price dynamically depending on the users coupon validation? I'm using jQuery to change the price depending on the coupon, and the price changes in the html page, but not on the server side. The price gets loaded at the same time as html page where the coupon input is, and where the PayPal form is, so PayPal dict takes the default price the moment page gets loaded, which I don't wont. As I said, regarding the front end, price gets changed on click(to apply button), but I can't send the data back to the server, since the request already passed because. This is my jQuery and coupons fetching code: views.py def get_coupon(request): if request.is_ajax(): try: plan = Subscription.objects.get(pk=request.session.get('plan_id')) coupon = Coupon.objects.get(code__iexact=request.GET.get('coupon', None)) discount = coupon.discount total = plan.sum_price - (plan.sum_price * discount / 100) data = { 'total': total, 'discount': discount, 'coupon': coupon.code } return JsonResponse(data, safe=False) except … -
Python Django request.GET.get('usernname') always returning 'None'
views.py def login(request): context = { "login_view": "active" } if request.method == "POST": username = request.GET.get('username') password = request.GET.get('password') print(f"username ===== {username}") print(f"password ===== {password}") user = auth.authenticate(username = username, password = password) if user is not None: auth.login(request, user) messages.success("you are successfully logged in") return redirect('dashboard') else: messages.error(request, "Invalid credentials") return redirect('login') else: return render(request, 'accounts/login.html', context) -
Django Templates not showing Views.py variables
I have a django project running on Linux server (via digitalocean) The problem I am experiencing is peculiar, everything works, but the communication between the templates and the views.py file seems to not be working. for example : the app name is 'gaapp' If I add <h1>This heading is to test if changes to the templates are picked up</h1>, in the gaapp/templates/gaapp/dash.html file, then it works successfully (I can see the heading on the site) But if I add a variable <h2>This {{variable}} should show on the site</h2>, then nothing shows. Any ideas? myprojectdir/gaapp/urls.py: #!/usr/bin/env python3 from django.urls import path from . import views urlpatterns = [ path("", views.dash, name='dash'), path("pages", views.pages, name='pages'), path('users/', views.users, name='users'), ] myprojectdir/gaapp/views.py: bunch of imports def dash(request): variable = "This is the variable that should be displayed, as in the example" return render(request, 'gaapp/dash.html', {"variable": variable})