Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no file unable upload to DB in Django
I have a form want to upload file to object by id but there has no file upload even show succeed. Did I go wrong? views.py: def upload_page(request, id): order = get_object_or_404(Order, id=id) form = Upload_payment(request.POST or None, request.FILES or None, ) if request.method == 'POST': if form.is_valid(): form.payment_img = form.cleaned_data.get('file') order.payment_img = form.payment_img order.save() messages.success(request, 'Succeed') return redirect('user_info') else: form = Upload_payment() context = { 'form': form, } return render(request, 'payment_upload.html', context) forms.py class Upload_payment(forms.Form): payment_img = forms.FileField(widget=forms.FileInput( attrs={'class': 'd-block w-100 mt-3 mb-3', 'name': 'file', 'type': 'file'})) class Meta: models = Order fields = ('payment_img', ) models.py class Order(models.Model): ..... payment_img = models.ImageField(upload_to='payment_ref/', blank=True, null=True) template <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.payment_img }} <button class="form-group btn btn-success" type="submit">Upload</button> </form> -
Not able to get ldap user group name in django group after authentication through ldap
I have configured free jumpcloud ldap service to test user authentication and group information. I can see ldap user info in django user on django admin but unable to copy the ldap group to django group. import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, LDAPGroupQuery, PosixGroupType AUTH_LDAP_SERVER_URI = "ldap://ldap.jumpcloud.com:389" AUTH_LDAP_BIND_DN = "uid=testuser,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com" AUTH_LDAP_BIND_PASSWORD = "Admin@12345" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_MIRROR_GROUPS = True IS_SUPER_USER_FLAG = ( LDAPGroupQuery("cn=Group1,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com") ) IS_STAFF_FLAG = ( LDAPGroupQuery("cn=Grroup2,ou=Users,o=5f4536f3d939d05ab35b66ef,dc=jumpcloud,dc=com") ) AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': IS_SUPER_USER_FLAG, 'is_staff': IS_SUPER_USER_FLAG , 'is_superuser': IS_SUPER_USER_FLAG, } AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=groups,dc=jumpcloud,dc=com,o=5f4536f3d939d05ab35b66ef', ldap.SCOPE_SUBTREE, '(objectClass=top)', ) # Tried also with (objectClass=groupOfNames) #Also #AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn') #AUTH_LDAP_GROUP_SEARCH = LDAPSearch( # 'ou=groups,dc=jumpcloud,dc=com', # ldap.SCOPE_SUBTREE, # '(objectClass=posixGroup)',) -
passing django file as input of requests library
how can I pass django request.FILES["example"] as requests.post() files argument? something like piping -
How to get certain fields in database from different models to template in django?
I am trying to show cities in country in cities_lits pages, but haven´t been able to figure out how to do it. I ma able to show countries and go through the link to cities pages which shows all cities, but not able to show only cities which belong to one certain country. City model has a foreign key relationship with Country model. Is it better to add logic under views by example under CitiesListView where I filter out cities in one country and add these cities to template? Or try to add it on template by filtering through objects with template tags and for and if loops? What is the best approach and why? I tried to add to CitiesListView context class CitiesListView(ListView): template_name = "cities_list.html" model = City context_object_name = "cities" country = Country.objects.get(id=1) def get_context_data(self,**kwargs): context = super(CitiesListView,self).get_context_data(**kwargs) context['cities'] = City.objects.filter(country=country) return context but wasn´t able to render it to template got an error that name 'country' is not defined even though I added it to CitiesListView. Where I go wrong and what do I miss? Any help is appreciated. models.py from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class City(models.Model): country = … -
Django DRF serializer method field on many to many running 2n queries
I'm using Django 2.2 and Django REST Framework. I have the following model structure class MyModel(models.Model): name = models.ChartField(max_length=200) class Tag(models.Model): name = models.ChartField(max_length=50, unique=True) class MyModelRelation(models.Model): obj = models.ForeignKey(MyModel, related_name='relation') user = models.ForeignKey(User) tags = models.ManyToManyField(Tag) def tag_list(self): return self.tags.all().values_list('name', flat=True).distinct() I want to get the tags list with the MyModel instance and for that, the serializer is class MyModelSerializer(serializers.ModelSerializer): tags_list = serializers.SerializerMethodField(read_only=True) def get_tags_list(self, obj): return obj.relation.tag_list() class Meta: fields = [ 'name', 'tags_list' ] and the view is class ObjListView(ListAPIView): serializer_class = MyModelSerializer def get_queryset(self): return super().get_queryset().select_related('relation').prefetch_related('relation__tags') But to get 58 records, it is running almost 109 queries. The my_app_mymodel`, `my_app_mymodelrelation_tags is repeated multiple times -
On a route that handles both GET and POST, which one is best to handle first?
I am writing a Django application and I have a view that is designed to handle both GET and POST requests. Is there a reason why any of the below snippets would be better than the other? def foo(request): if request.method == "POST": ... else: ... vs. def foo(request): if request.method == "GET": ... else: ... -
How to integrate Faust with Django?
I am trying to integrate Faust with Django to publish the messages to Kafka. Here is the example in Faust repo: https://github.com/robinhood/faust/tree/master/examples/django I modified it a bit, and created views to push data to Kafka via Faust. from django.shortcuts import render from asgiref.sync import async_to_sync from accounts.agents import AccountRecord, add_account async def send_data() -> None: print("sending..data") print(await add_account.ask(AccountRecord(name="tesst", score=10.9, active=False))) def index(request): async_to_sync(send_data)() return render(request, "accounts/index.html") But, I get this error now: RuntimeError at / Task <Task pending name='Task-1' coro=<AsyncToSync.main_wrap() running at /Users/mysuer/.pyenv/versions/3.8.3/envs/faustdjango/lib/python3.8/site-packages/asgiref/sync.py:204> cb=[_run_until_complete_cb() at /Users/mysuer/.pyenv/versions/3.8.3/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop I am running this Django app using development server. What am I doing wrong? -
How to style the choose file button only?
Using django I am using django to upload post on my website. I can do that but i want to style that choose file button too like in Facebook -
Next parameter in url not showing but is printing correctly in django
This is my signup view: def signup(request): next = request.GET.get('next', '') print(next) if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": first_name=request.POST['first_name'] email=request.POST['email'] password=request.POST['password'] cpassword=request.POST['cpassword'] signup_uri = f'/signup?next={next}' if password==cpassword: if User.objects.filter(email=email).exists(): messages.info(request,'Email already in use') return redirect(signup_uri) elif User.objects.filter(mobile=mobile).exists(): messages.info(request,'Mobile Number already in use') return redirect(signup_uri) else: user=User.objects.create_user(first_name=first_name,email=email,password=password) user.save(); return redirect(f'/login?next={next}') else: messages.info(request,'Passwords not matching') return redirect('signup_uri') else: return render(request,'signup.html') The problem I am facing is that when I am printing next under def signup it is printing it correctly but when it has to redirect it redirects without showing anything as next in url. That is signup_uri = f'/signup?next={next}' and return redirect(f'/login?next={next}') are showing the {next} as empty.What could be the reason?Any help would be appriciated. -
Django circular import error - how to debug it?
I tried to follow this tutorial https://blog.nicolasmesa.co/posts/2018/10/saas-like-isolation-in-django-rest-framework/ using: Django 3.1 Python 3.6 Everything I did including 'The User Messages App' paragraph worked perfectly right before the 'Refactoring the views' passage and then I got the error when running manage.py runserver django.core.exceptions.ImproperlyConfigured: The included URLconf 'saas_django.urls' does not appear to have any pa tterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import I tried different types of import but I can't figure out where the cirular import happens My steps to find a bug: the saas_django/urls.py refers to user_messages app: path('api/v1/user-messages/', include('user_messages.urls')), user_messages/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.UserMessageList.as_view(), name=views.UserMessageList.name), path('<uuid:pk>', views.UserMessageDetail.as_view(), name=views.UserMessageDetail.name), ] It seems like something is wrong with the imported user_messages/views.py from rest_framework import permissions from rest_framework import generics from . import serializers from .models import UserMessage class UserMessageList(generics.ListCreateAPIView): name = 'usermessage-list' permission_classes = ( permissions.IsAuthenticated, ) serializer_class = serializers.UserMessageSerializer queryset = UserMessage.objects.all() def perform_create(self, serializer): user = self.request.user company_id = user.company_id # Added from_user serializer.save(company_id=company_id, from_user=user) def get_queryset(self): # Changed this to use the UserMessageManager's method return UserMessage.objects.get_for_user(self.request.user) class UserMessageDetail(generics.RetrieveAPIView): name = 'usermessage-detail' permission_classes = ( permissions.IsAuthenticated, ) … -
Twilio TaskRouter in Django / React JS
I'm building a simple contact center app using Twilio. I'm creating the TaskRouter Worker capability token in my backend like so: Serializer: class TwilioTokenSerializer(serializers.BaseSerializer): def to_representation(self, instance): return { 'token': instance, } View: class TwilioWorkerView(generics.RetrieveAPIView): serializer_class = TwilioTokenSerializer def get_object(self): current_user = self.request.user.worker worker_sid = current_user.worker_sid # Returns a Twilio Worker token for current agent capability = WorkerCapabilityToken( account_sid=TWILIO_ACCOUNT_SID, auth_token=TWILIO_AUTH_TOKEN, workspace_sid=TWILIO_WORKSPACE_SID, worker_sid=worker_sid ) capability.allow_fetch_subresources() capability.allow_update_activities() capability.allow_update_reservations() token = capability.to_jwt() token = capability.to_jwt(ttl=28800) return token In react: import { Worker } from 'twilio-taskrouter'; componentDidMount(){ axios.get('https://myURL.com/api/twilio-worker-token') .then(res =>{ console.log(res.data.token) const worker = new Worker(res.data.token) }).catch(error =>{ console.log(error) }) but I'm getting the 403 web socket error: index.window.js:24 WebSocket connection to 'wss://event-bridge.twilio.com/v1/wschannels?token=(here the token)&closeExistingSessions=false&clientVersion=0.5.2' failed: Error during WebSocket handshake: Unexpected response code: 403 createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 index.js:1 WebSocket error occurred: Event {isTrusted: true, type: "error", target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …} console.<computed> @ index.js:1 <computed> @ index.window.js:17 webSocket.onerror @ index.window.js:24 error (async) createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 setTimeout (async) webSocket.onclose @ index.window.js:24 index.window.js:17 Uncaught n {_errorData: {…}, name: "GATEWAY_CONNECTION_FAILED", message: "Could not connect to Twilio's servers."} r.emit @ index.window.js:17 (anonymous) @ index.window.js:17 r.emit @ index.window.js:17 webSocket.onerror @ index.window.js:24 error (async) createWebSocket @ index.window.js:24 (anonymous) @ index.window.js:24 setTimeout (async) … -
Difference between form class attribute "fields" and "declared_fields" in Django
I was looking into a way to change the fields of a form dynamically in Django and came across the fields attribute. This attribute makes sense to me and worked as expected. However I also just came across the class attribute declared_fields and I cant wrap my head around what this does differently and why its there. I also cant find an explanation online for it. Can someone please explain the difference between the two? -
How to count how many times foreignkey object can be used
My models.py class Timing(models.Model): time = models.CharField(max_length=250) count = models.IntegerField(default=0) # max=20 class Ticket(models.Model): username = models.CharField(max_length=50) no = models.ForeignKey(Timing, on_delete=models.CASCADE) Is there a way I can increment the value of count variable in class Timing by 1 whenever I use no variable to connect object of Timing class (whenever I use the ForeignKey variable)? -
Can't Retrieve Data from MongoDB in django application
I am trying to develop a website in Django. I am using MongoDB as a database for the first time. I used Djongo to develop the connection between django and MongoDB. I have created a database in the Robo3T and the connection is also developed between django and MongoDB. The data is saving fine in the database I have seen in the robo3T. But when I am trying to retrieve the data back from the MongoDB to dispay on the Django Template, its not shoiwng the data and show the template tag like this {{post.tile}} {{post.content}}. Here is my code: Setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'test', 'HOST':'localhost', 'PORT':27017 } } view.py from django.shortcuts import render from django.views.generic import View,TemplateView from .forms import FormName from .models import Post # Create your views here. class MainPageView(TemplateView): template_name='main.html' class LoginView(TemplateView): template_name='login.html' def RegistrationView(request): form=FormName() if request.method == 'POST': print("In Post") print(request.POST) form=FormName(request.POST) if form.is_valid(): form.save(commit=True) else: form=FormName() return render(request,'registration.html',{'form':form}) # template_name='registration.html' def main(request): post=Post.objects.all() return render(request,'main_temp.html',{'Post':post}) models.py from django.db import models # from OnlineJobPortal.settings import DBNAME # # Create your models here. # # connect(DBNAME) class Post(models.Model): title=models.CharField(max_length=250) content=models.CharField(max_length=250) forms.py from django import forms from .models import Post class … -
Docker container doesn’t starts after changing host directory
I have a django app which i’m dockerizing. Below is the docker-compose.yml file (Only django part is given here). web: build: . command: python ./webapp/server.py restart: always volumes: - .:/code - ./webapp/static:/static networks: - nginx_network - couchserver_network - dummyapi_flaskapp_network when i change the name of the host directory from where it is run, i’m getting the following error : python: can't open file './webapp/server.py': [Errno 2] No such file or directory I have copied the host directory to image using : RUN mkdir /code WORKDIR /code COPY . /code/ So after renaming my host directory why python is unable to find the server.py file as it is available in containers code directory. I’m novice in docker and have little or no knowledge in volumes. Any help is really appreciated. How can i run this computer in another machine where the host directory wont be available -
How to filter django serializer fields?
I have question about Django REST FRAMEWORK. user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usert', null=True, blank=True) question = models.ForeignKey(Question, related_name='userque', on_delete=models.CASCADE, null=True, blank=True) option = models.ForeignKey(Option, related_name='opt', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username + ' - ' + self.question.question ``` ** This is my model for UserTest. And when ever user gives test. The user will see all questions in drop down as well as all options. But I want only the options of which question user choose. But now i get all of the options. ** ``` class TestSerializer(serializers.ModelSerializer): question = serializers.SlugRelatedField(queryset=Question.objects.all(), slug_field='question') option = serializers.SlugRelatedField(queryset=Option.objects.all(), slug_field='option') class Meta: model = UserTest fields = ('question', 'option') ** This is my Test serializer.** I hope you got the question i m trying to ask. When user selects the question. I want to display only the options of that questions in drop down. Thanks in advance !!!! -
Is the a way to fix form from model not saving to database in django?
Its a bit confusing why this doesn't save to Django admin database. I have the followings class User(AbstractUser): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) I also have in model.py class Student(models.Model): email = models.EmailField(max_length=60, default='type here', help_text='Only valid email') town = models.CharField(max_length=50) phone_number = models.CharField(max_length=10) photo = models.ImageField(upload_to='photos') profile = models.TextField() def __str__(self): return self.user Forms.py class Student(models.Model): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email = models.EmailField(max_length=50, default='type here', help_text='Only valid email') town = models.CharField(max_length=50) phone_no = models.CharField(max_length=12) photo = models.ImageField(upload_to='photos') profile = models.TextField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.firstname = self.cleaned_data.get('firstname') user.lastname = self.cleaned_data.get('lastname') user.save() st_student = Student.objects.create(user=user) st_student.email = self.cleaned_data.get('email') st_student.town = self.cleaned_data.get('town') st_student.phone_no = self.cleaned_data.get('phone_no') st_student.photo = self.cleaned_data.get('photo') st_student.profile = self.cleaned_data.get('profile') st_student.save() return user Views.py class StudentSignUpView(CreateView): model = User form_class = StudentSignupForm template_name = 'accounts/student_signup.html' def form_valid(self, form): user = form.save() user_login(self.request, user) return redirect('topropage') I don't know why I can't save this form to a database. Please could you check? -
How can i constrain or choose between one or other foreign key?
The problem is conceptual (databases relationships), so the language isn't the focus here, but I'm using Python and Django. I have 3 models/tables: Company Customer Address Eg. class Company(models.Model): name = models.CharField(max_lenght=100) #example class Customer(models.Model): name = models.CharField(max_lenght=100) #example class Adress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example # here i want the adress owner # i could put something like this: company = models.ForeignKey(Company, on_delete=models.PROTECT) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) I want the address to belong to the customer or the company, but not both. I know that i can simply create 2 Address classes, eg, CustomerAddress, CompanyAddress, each one with its correct foreign key: class Company(models.Model): name = models.CharField(max_lenght=100) #example class Customer(models.Model): name = models.CharField(max_lenght=100) #example class CompanyAdress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example company = models.ForeignKey(Company, on_delete=models.PROTECT) class CustomerAdress(models.Model): country = models.CharField(max_lenght=100) #example state = models.CharField(max_lenght=100) #example customer = models.ForeignKey(Company, on_delete=models.PROTECT) But i don't want to for two reasons: The duplicated code and the fact that in django admin panel I will have two separeted address lists, wich doesn't makes much sense, since all address are structurally indentical. I can fix the duplicated code creating a base class, inheriting from it and etc, but i … -
Django. How to fill model attribute in view?
When I save Achivement model, I want to set current user as user_owner. user_owner = request.user my view.py def create(request): if request.method == 'POST': form = AchievementForm(request.POST) form.user_owner = request.user if form.is_valid(): form.save() return HttpResponseRedirect('/cabinet/achievement/') else: form = AchievementForm() return render(request, 'achievement/create.html', {'form': form}) my models.py class Achievement(models.Model): name = models.CharField(max_length=10, unique=True) description = models.CharField(max_length=255, blank=True) requirement = models.TextField(blank=True) status = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) user_owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True,) category = models.ForeignKey(Category, on_delete=models.CASCADE) accept_type = models.IntegerField() img = models.CharField(max_length=255, blank=True) my form.py class AchievementForm(forms.ModelForm): name = forms.CharField(widget=TextInputCustom()) description = forms.CharField(widget=TextInputCustom()) requirement = forms.CharField(widget=TextareaCustom()) status = forms.ChoiceField(choices=Achievement.statusList, widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) accept_type = forms.ChoiceField(choices=Achievement.acceptTypeList, widget=forms.Select(attrs={'class': 'form-control select2bs4 select2-hidden-accessible', 'style': 'width: 100%'})) class Meta: model = Achievement fields = ['name', 'description', 'requirement', 'status', 'category', 'accept_type', 'img', 'user_owner'] When I set form.user_owner = request.user in views, validaiting is failed. user_owner This field is required. How to save curent user as owner? -
CSRF Forbidden in firefox but when I send same request form chrome it is working
When i am running my website on chrome its working properly but when i am running it from firefox its showing "csrf cookie not set" This is form from where i made the request import React, { useContext } from 'react'; import './form.css' import CSRFtoken from '../csrftoken' // eslint-disable-next-line import { UserContext } from '../../contexts/UserContext' // componentDidMount(){ // } const Login = (e) => { // eslint-disable-next-line // const [user,setUser]=useContext(UserContext); const log = () => { localStorage.clear() var formdata = new FormData(); formdata.append("username", document.getElementById('username').value); formdata.append("password", document.getElementById('password').value); formdata.append("csrfmiddlewaretoken", document.getElementById('csrftoken').value); var requestOptions = { method: 'POST', body: formdata, // redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/bookdetails/login/", requestOptions) .then(response => response.json()) .then(result => { if (result.user == 'exist' && result.password == 'invalid') { document.getElementById('error').innerHTML = 'Incorrect Password'; } else if (result.user == 'invalid' && result.password == 'invalid') { document.getElementById('error').innerHTML = 'Incorrect Username'; } else if (result.user == 'exist' && result.password == 'valid') { localStorage.setItem('data',JSON.stringify(result)); window.location.href='/'; } }) .catch(error => console.log('error', error)); } return ( <div id="focus_form"> <div className="section" id="login_section"> {/* <button onClick='form_out("login_section")' id='close' >X</button> */} <h1 align='center'>Login</h1><br /> <center> <p id='error'></p> <form id='login_form' > <CSRFtoken></CSRFtoken> <input type='text' id='username' name='username' placeholder='usermame' autoComplete="off" required /><br /> <input type='password' id='password' name='password' placeholder="password" required /><br /> <center> <input type='button' onClick={log} … -
Why my date_of_birth not show up in template django?
I have a date of birth field in my model but why it's not showing up in the template when I render it? The date_of_birth is inside Teacher model. And Do you have any good idea on date_of_birth field? Because right now I'm using charfield for that so I need to convert the DateInput to string so that I can add it into charfield. here is my models.py class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) date_of_birth = models.CharField(max_length=100) def __str__(self): return self.user.email my forms.py class TeacherRegisterForm(UserCreationForm): date_attr = {'class': 'form-control', 'id': 'dateofbirth-register', 'type': 'date'} date_of_birth = forms.DateField(widget = forms.DateInput(attrs=date_attr)) class Meta(UserCreationForm): model = CustomUser fields = ['date_of_birth', ..] def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True user.save() teacher = Teacher.objects.create(user=user) teacher.date_of_birth += str(self.cleaned_data.get('date_of_birth')) return user views.py @login_required @teacher_required def teacherInfoView(request): template_name = "attendance/content/teacher/teacher_info.html" teacher_info = Teacher.objects.filter(user=request.user) context = {'teacher_info': teacher_info} return render(request, template_name, context) template {% for info in teacher_info %} <!-- firstname --> <div class="row"> <div class="ml-5 mr-auto"> <h5>Name : {{ info.user.first_name }} {{ info.user.last_name }}</h5> </div> <div class="ml-5"> <h5>Email : {{ info.user.email }}</h5> </div> </div> <div class="row"> <div class="ml-5"> <h5>Date Of Birth : {{ info.date_of_birth }}</h5> </div> <div class="ml-5"> <h5>Gender : {{ info.user.gender }}</h5> </div> </div> {% … -
login_required Django redirect next not working
Hello. I try to redirect user to the page he wants before he login, by login_required but the page doesn't redirecting! I have searched a lot but I found nothing. Here my main codes for login_required: I summarized them to the related subject. If need to add something else, tell me. Thank you in advance. VIEW: from django.contrib.auth.decorators import login_required def user_login(request): next_url = request.GET.get('next') print(next_url) if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request, username=cd['username'], password=cd['password']) if user is not None: login(request, user) messages.success(request, 'Login Successful', extra_tags='success') if next_url: return redirect(next_url) return redirect('post:all_posts') else: messages.error(request, 'Wrong Username Or Password', extra_tags='warning') else: form = UserLoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request, user_id): users = get_object_or_404(User, id=user_id) posts = Post.objects.filter(user=users) context = {'user': users, 'posts': posts} return render(request, 'account/dashboard.html', context=context) Settings: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Post.apps.PostConfig', 'Account.apps.AccountsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'SocialNetworkP.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
I can't access my XAMPP localhost through internet
I have setup my Django project on my XAMPP server. After doing this i can connect my server through localhost and through my ip on LAN. But i can't access it through internet. I have done the port forwarding on my router and i have even tried to access it through my static ip, but it doesn't connected. Can you guys, please help in fixing the problem? -
How to Display/Fetch Data on button click using AJAX in Python - AJAX
I am new to both ajax and django. I want to fetch phone number from database and want to display on template when click user the contact button. But in my case I am getting all the phone numbers in first button itself which is not correct. Because different persons have different phone numbers. Please help me. Thanks in advance. views.py: from django.shortcuts import render, redirect from .models import listing_model from .forms import listing_form from django.http import HttpResponse def submissions(request): tasks = listing_model.objects.all() form = listing_form() if request.method =='POST': form = listing_form(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('submissions') context = {'tasks':tasks, 'form':form} return render(request, 'submission.html', context) #ajax def contact(request): numbers= listing_model.objects.values('phone') return HttpResponse( numbers ) home.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Home{% endblock %} {% block body %} <div class="container"> <div class="row"> <form method="GET" class="mx-auto" ><br> {{ user_filter.form }}<br><br> <button type="submit" class="btn btn-info" style="margin-left:250px">Search</button> </form> </div> </div> <div>&nbsp; &nbsp;</div> <div class="container"> <div class="row"> {% for task in tasks %} <div class ="col-md-4"> <div class="card" style="width:300px"> <div class="card-body"> <h4 class="card-title">Title : {{ task.title }}</h4> <div>Address : {{ task.address }}</div> <div>City : {{ task.city }}</div> <img src="{{ task.image.url }}" style="max-height:200px"> <div>&nbsp;</div> <button class="btn btn-primary" id="request-btn">Contact</button> <script … -
Quality of image drops when encoding an Image in Python
I am trying to create Barcodes in a Django app using python-barcode library and show them on the django template but it reduces the quality of the image when printing it. Is there a way to keep the resolution same or maybe fix the column size on template such that it doesn't pixelate Views.py def PrintGRNsv1(request, pk): ... for item in items: EAN = barcode.get_barcode_class('code128') d = {'module_width': 0.15, 'module_height': 2.5, 'quiet_zone': 0.5, 'text_distance': 0.5, 'font_size': 6, 'text_line_distance': 5} w = ImageWriter(d) ean = EAN(item['bar'], writer=ImageWriter()) a = ean.save(item['bar'], options=d) print("a ", a) with open(a, 'rb') as image: img = image.read() encoded_string = base64.b64encode(img).decode('utf-8') alist.append({ 'image': encoded_string , **item}) os.remove(a) alist = grouper(alist, 7) return render(request, 'grn/printgrn.html', {'imglist':alist}) template: <div class="grid-col"> <span style="text-align: center"> <br> <br> <img src="data:image/png;base64,{{ row.image }}" alt="" srcset=""> <br> {{ row.label }} <br> {% if row.lname %} {{ row.lname }} {% else %} _____ {% endif %} </span> </div>