Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Two Factor Authentication Custom Login
After a quick search and reading documentation I implemented Django - Two Factor Authentication in one of my Django project [Reference Link]. It works great I am using Google Authenticator for token based login. The problem arises when I want to extend login methodology of the library. I want to enforce my every user to use 2-Factor-Auth as compulsion. I am not using any signup measures so there has to be a check at the time of Login for a user. The problem is to design a custom login mechanism but I am unable to incorporate this library with the custom login. PS: I have a custom user model and currently I am using default Login that came with Django Two Factor Authentication. I did not though the code was necessary so I did not posted it but I can share it if needed. -
Strategy for handling recursive template display in Django
I'm rewriting a family tree app in Django that I previously wrote in Laravel. There's an 'outline view' page where I start with the 'original families' at the top of the tree, and show an outline of their children, their children's families/kids, those kids' families/kids, etc. First I've generated a big nested list with all the info (in the controller for laravel, and in views.py in my Django rewrite). Then I give that list to a couple of views to display the lists for each original family. (Code included below) Testing the logic a couple levels at a time it works, but when I let it call recursively and load my outline page, it gives me a recursion error: maximum recursion depth exceeded while calling a Python object. Reading around, it sounds like python has a known limitation that it doesn't handle tail recursion, and I saw some posts saying that showing recursive views isn't good practice in Django. Do I need to do something very different (maybe generate the html in advance so I can pull it up statically, and just update when I add new records)? Or is there a better way to approach this recursive problem in … -
How to create your own interactive map from any image?
I want to create an interactive process flowchart for my company. This process flowchart lives on the browser and will have pins and markers on top of the products, where users can hover to reveal more information, similar to how this Zelda video game map was overlayed with pins and markers : https://zeldamaps.com/?game=BotW However, I have no clue where to even start. I think i need to convert my image to zoomable tiles. Can someone guide me what are the general steps required to achieve this interactive map? -
How to create form with context processor in Django?
I want to create a form in my navigation bar. I am using a context processor for that. I created themeChoice field in my UserProfile model. What I want to is when user click submit button, form will be save. I tried something but it did not work, my view prints nothing. How can I do that? Note: my context processor is working. views.py def approval_context_processor(request): ... if request.method == 'POST': form_theme = UserThemeChoiceform(request.POST) if form_theme.is_valid(): user_who = request.POST.get('user_who', None) user = UserProfile.objects.get(id=user_who) print(user_who) form_theme.save() return redirect('home') context= { ... 'form': form_theme, } return context navigation.html <form method="POST" id="theme" action="#"> {% csrf_token %} <input type="hidden" name="user_who" value="{{ request.user }}" > <button type="submit" class="btn btn-success">Send</button> </form> -
How do you format numbers called from an API in Django?
I have some values called from an API in a course I'm doing which I would like to format improve visibility. What is the best way to code this? Thanks. Example code is below: ${{list_item.marketCap}} {{list_item.ytdChange}}% Where, the first one I would like to add a comma for thousands and 2dp, and the second times by 100? -
How to work with Django ajax "GET method"
I want to do an ajax GET and POST method in django. MY post method is working well, but the GET method isn't. see my codes below; Urls path("getupdates/",views.getupdates,name="getupdates") views def getupdates(request): if request.user.is_authenticated: if request.method == "GET": user_instance = User.objects.filter(username=request.user.username)[0] info = userinfo.objects.filter(username=user_instance.username) game = spinwheel.objects.filter(user=info[0]) get_value= request.body data = {"info":info} print(data) return render(request,'spin.html',{"info":info}) Js-ajax $.ajax({ url: 'getupdates/', //datatype: 'json', data : data, type: 'GET', sucess: function(data) { console.log("refreshed!") } }); I wish to have the ajax GET method update some parts of my HTML. -
why email sent by normal users but not sent by superusers?
I need to use forgot password link to reset the password to a new one, the function works perfectly with me the problem is that: when I send the new request if that email was a superuser the request won't send, although, a normal user can send the request except the superuser so, anyone can help me in that? def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(email=data) try: usr = User.objects.get(email=data) except User.DoesNotExist: messages.error(request, "%s Does not exists" % data, extra_tags='user_error') return redirect('accounts:reset_password') if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('accounts/password_reset_subject.txt') htmltemp = template.loader.get_template('accounts/password_reset_email.html') c = { "email": user.email, 'domain': '127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [user.email], headers={'Reply-To': 'admin@example.com'}) msg.attach_alternative(html_content, "text/html") msg.send() except BadHeaderError: return HttpResponse('Invalid header found.') messages.info(request, "Password reset instructions have been sent to the email address entered.") return redirect("accounts:password_reset_done") password_reset_form = PasswordResetForm(None) return render(request=request, template_name="accounts/password_reset_form.html", context={"form": password_reset_form}) -
Export react app to static and separate html files, for use in django
I have a Github repo (https://github.com/cupliz/medical-calculators) with some components (calculators) that I want to integrate into my Django app, without having to do a SPA; I want to take advantage of Django's templating system. Integrating the React app as a Django app did not succeed (I tried a dozen tutorials based on Webpack and babel). I figured out the easiest way may be exporting the react app to static HTML files. I have tried the following: npm run build command (but this didn't work presumably because of the routing). react-snap module react-snapshot module react-static module (this requires the app to be built with react static from the start). What is the easiest way to export an existing react app, with routing, to static HTML files that can be served without any node.js on the hosting server? -
How does cookiecutter django create database in docker container/image
How does running docker-compose -f local.yml up create the postgres database in the postgres container with configurations in .envs/.local/.postgres. I have looked through the Dockerfiles and cannot seem to find a command such as createdb except in the maintenance/restore file. Cookiecutter-django: https://github.com/pydanny/cookiecutter-django -
Python django, How can I retrieve location by using the geolocation search API
I am doing a project which one of the function should be searching the location by using the location search, but how can I do that? How can I retrieve the location by using the searching APi which is https://geodata.gov.hk/gs/api/%5Bversion%5D/locationSearch?q=%5Bvalue%5D Hope that I can get some ideas from you guys. -
django returning 'AnonymousUser' object has no attribute '_meta' error
I am developing a feature, when a user registers it automatically logs the user in but i get 'AnonymousUser' object has no attribute '_meta' error. but when i use the same code to login the user it works fine. my forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from .models import * class RegisterForm(forms.Form): fname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"fname entry", "placeholder":"First Name"}), required=True) lname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"lname entry", "placeholder":"Last Name"}), required=True) phone = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"phone entry", "placeholder":"Phone Number"}), required=True) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Password", "autocomplete":"off"}), required=True) password2 = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Confirm Password", "autocomplete":"off"}), required=True) def clean(self, *args, **kwargs): fname = self.cleaned_data.get("fname") lname = self.cleaned_data.get("lname") phone = self.cleaned_data.get("phone") password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if phone and password and fname and lname and password2: try: user = User.objects.get(phone=PhoneNumber.objects.get(number=phone)) if user: raise forms.ValidationError("user exists login instead") except ObjectDoesNotExist: pass if password!=password2: raise forms.ValidationError("passwords didn't match") else: if len(password)<8: raise forms.ValidationError("short password! password should be longer than 8") in my forms i have a registration form which does not inherit from django's user creation form. my views.py: def registerView(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): fname = form.cleaned_data.get("fname") lname = form.cleaned_data.get("lname") username … -
How to add a model instance through another model
Guys I was looking at how I can add a model instance that can be added through another model. like how tags are done. If a model instance doesn't exist add it. if It does exist, don't add, just use the existing one. I wanted to do that with a Category model where if the category exists use the existing one and vice versa. #Models class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Company(models.Model): name = models.CharField(max_length=120, help_text='Name of your company', ) slug = models.SlugField(unique=True, blank=True, null=True) categories = models.ManytoManyField(Category, related_name="company", blank=True, null=True, on_delete=models.PROTECT) #Views class CompanyCreate(CreateView): model = Company form_class = CompanyForm template_name = 'company/form.html' So when one adds a company can add many categories but use the one that already exists. Thanks in Advance -
Using Django views to redirect the user to the page they took the POST action on:
A user could be at one of three pages: For this argument let's call them page1, page2 or page3. On each of those pages, they can take the same actions essentially, with subtle differences. So if the user is on page1 and they take a POST action, then after the post action is done, the redirect should just "refresh" the page so they remain on page1 and can conduct other business from there. In the view, how do I call the URL and then return redirect(that_url)? -
how to tell a django view what are the parameters when i am not using a template
I am creating a library management system where a user sends a borrow request to a librarian who will approve it. I created the requisite pages as I understood it but I am unable to make two return statements. Fairly new to django, I dont know about restful uri. my views.py @login_required def send_borrow_request(request, pk,userID, bookID): from_user=request.user to_user =User.objects.get(id=userID) book_id=BookInstance.objects.get(id=bookID) borrow_request, created= Borrow_Request.objects.get_or_create(from_user=from_user, to_user=to_user, book_id=book_id) if created: return HttpResponse('borrow request sent') else: return HttpResponse('borrow request was already sent') @login_required @permission_required('catalog.can_grant_decline_request') def process_borrow(request,pk): book_instance=get_object_or_404(BookInstance,pk=pk) if request.method == 'POST': data={'bookinstpk':book_instance.id} form = GrantRequestForm(request.POST, initial=data) if form.is_valid(): book_instance.status__exact='o' book_instance.due_back=datetime.date.today() + datetime.timedelta(days=7) book_instance.borrower=form.cleaned_data['name'] book_instance.save() return HttpResponseRedirect(reverse('all-borrowed')) else: form=GrantRequestForm() context={ 'form':form, 'book_instance':book_instance, 'borrower':book_instance.borrower, } return render(request,'catalog/process_borrow.html',context) bookinstance model class BookInstance(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID') book=models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) due_back=models.DateField(null=True, blank=True) borrower=models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) @property def is_overdue(self): if self.due_back and date.today()>self.due_back: return True return False LOAN_STATUS=( ('m','Maintenance'), ('o','on loan'), ('a', 'Available'), ('r', 'Reserved'), ) status=models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering=['due_back'] permissions = (("can_mark_returned", "Set book as returned"),) def __str__(self): return f'{self.id}({self.book.title})' class Borrow_Request(models.Model): from_user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="from_user") to_user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="to_user") book_id=models.ForeignKey('BookInstance',on_delete=models.CASCADE,related_name="bookinst") class Meta: # ordering=['self.bookinst.due_back'] permissions = (("can_grant_decline_request", "Grant or decline a Request"),) def __str__(self): return f'{self.borrower.username}({self.book_id.book.title})' def get_absolute_url(self): return reverse('borrow-detail', args=[str(self.id)]) urls.py A particular bookinstance … -
What is the use of django rest framework
Please bear with me I am new in the world django. I am using django rest framework, but what is its use... Is it for fetching data directly in the template, or something else. And is it good to directly use javascript fetch method to get data? Another question, do websites like github, use there own api to render data on the template or they fetch data directly from database? Your help is appreciated! Thank you. -
Django how to remove the ForeignKey in the template
I want to remove ForeignKey in the forms and in the template and it generates it automaticallyenter code here the models and the forms are there: from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class PostProduit(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) titre = models.CharField(max_length=255) categorie = models.CharField(max_length=255) description = models.TextField(max_length=255) prix_en_FCFA = models.CharField(max_length=255) Whatsapp = models.BooleanField(max_length=255) photo_1 = models.ImageField(upload_to="image/") photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) photo_1 = models.ImageField(upload_to="image/", null=True, blank=True) date = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user} ===> {self.titre}" class PostProduitForm(ModelForm): class Meta: model = PostProduit fields = '__all__' -
How to update a Django html element with javascript and Ajax
I am trying to update an html element on web page with javascript. When the home page loads, it works perfectly, but when I click on New Product link just the context string is displayed on the home page html <!-- product/home.html --> {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <title>Test context</title> </head> <body> <h1>Test context</h1> <div class="container"> {% block content %} Product: <span id="product-code"></span> <p><a href="{% url 'new-product' %}">New Product</a><p> {% endblock content %} <script type="text/javascript" src="{% static 'js/product.js' %}"></script> </div> </body> </html> urls.py # cardplay/urls.py from django.urls import path from .views import HomePageView, NewProduct urlpatterns = [ path('', HomePageView.as_view()), path('new-product', NewProduct.as_view(), name= 'new-product'), ] views.py # /product/views.py import random from django.views.generic import View from django.shortcuts import render from django.http import JsonResponse class HomePageView(View): template = 'product/home.html' def get(self, request): context = {} return render(request, self.template, context) class NewProduct(View): def get(self, request): code = random.choice(['A123','M456', 'X789']) context = { 'code': code, } return JsonResponse(context) product.js $(document).ready(function () { getNewProduct(); }); function getNewProduct() { $.ajax( { type: "GET", url: 'new-product', cache: false, success: function (context) { displayNewProduct(context); } } ); } function displayNewProduct(context) { var productCode = document.getElementById('product-code'); productCode.innerText = context.code; } What … -
Not able to use the collectstatic command while deploying to pythonanywhere
I am trying to collect all my static files into one folder using the python manage.py collectstatic command but it throws me this error error image notice the address '/home/vatsalp/django3-personal-portfolio/portfolio\static\portfolio' has mixture of forward and backward slash which might be the issue but do not know how to resolve it and also i am on a windows computer please help me fix this! -
Django doesn't update static files, clearing browser cache doesn't work
I stumbled into a problem with my Django & React app. I am changing the look of a component and Django doesn't update it when I refresh, I tried deleting the cache, didn't work. To be sure that it's not my browser I accessed the site from my phone and the updated content wasn't there. As a final check I used my other machine and fresh install of everything related and copied my project there and the changes finally showed. What could be the cause of the problem on my main machine? Does django itself store some cached older version and use that instead? -
How do I align fields in html from django forms?
I have a form with which I intend to capture student marks. I have an issue lke I don't know the best way to put it so that I have student name and markfield beside it for all the students. calling {{ form }} brings the form with select dropdown items(not what I want). Specifying form fields do not populae anything.i.e {% for field in form %} {{ field.student }} {{ field.marks }} {% endfor %} This is the form class AddMarksForm(forms.ModelForm): def __init__(self, school,klass,term,stream,year, *args, **kwargs): super(AddMarksForm, self).__init__(*args, **kwargs) self.fields['student'] = forms.ModelChoiceField( queryset=Students.objects.filter(school=school,klass__name__in=klass,stream__name=stream[0])) class Meta: model = Marks fields = ('student','marks') This is how I tried the html rendering <form method="post" enctype="multipart/form-data" action="{% url 'add_marks' %}"> {% csrf_token %} {% if form %} <table> <tr> <td>Student</td> <td>Marks</td> </tr> {% for field in form %} <tr> <td>{{ field.student }}</td> <td>{{ field.marks }}</td> </tr> </table> {% endfor %} <button class="btn btn-outline-primary">Save</button> </form> My view. class AddMarksView(LoginRequiredMixin,CreateView): model = Marks form_class = AddMarksForm template_name = "feed_marks.html" success_url = reverse_lazy('search_m') def get_context_data(self, *args, **kwargs): class_name = self.request.session.get('class_name')#From session storage context = super(AddMarksView,self).get_context_data(*args, **kwargs) context["student_subjects"] = Students.objects.filter(school=self.request.user.school,klass__name = class_name,stream__name='South') return context def get_form_kwargs(self): kwargs = super(AddMarksView, self).get_form_kwargs() year = self.request.session.get('year_input')#From session storage print(year) term … -
Messages Error in Django doesn't appear to the user when registering
I have a problem with my user registration function. My goal is to have the code check in the database to see if the username is already taken or not, and let the user know in case it's already taken. For now, the code is working fine for the first part, but the second doesn't work. The message "Something is wrong" appears but not the one specific to the username "This user already exists". I tried to do the following options that I found on stack, but nothing is working: first to change the form and raise a ValidationError and check for error in the front second to verify in the function "user_register" if the user is already taken and raise a message.error, this is the option in my code bellow third, try if the user exists and bring an error in the context Would someone knows what is wrong with my code? It could be something really stupid. Here is my view.py def user_register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = User.objects.create_user(username=username, password=password) group = Group.objects.get(name='Stroller') group.user_set.add(user) user.save() login(request, user) messages.success(request, "New account successfully created" ) return redirect('accounts:dashboard') else: … -
how to block direct access from staticfiles in django
Anybody can access static files in my django website by just putting the location of that particular file like css,js & img inside the url(for example:- https://example.com/static/css/style.css). I want block direct access from them so nobody can get access to any css code or any js code which makes website more vulnerable(easly hackable). I have seen in websites like EA, etc you can't have access to their static & media files as well as all their static & media files location are hidden when inspect on browsers like chrome, etc. Also I want to hide locations of these files from the inspect section in browsers like chrome, etc. -
Real time Django
I'm learning django so I'm doing Facebook clone Is there a way to make notifications by real time? I tried using ajax but it only updates for the same user not others, and for channels, i can rarely find a tutorial and even if i did it's old and they only build chat apps and for documentation it's difficult to understand Even react is only used with rest framework is there any other way to do it? I did friend request and notification system but I can't make them in real time i just need to reload to find new ones -
How can I get the profile image from Postgres DB (Django REST) to Android Studio
I try to get user's image profile from django (it's saved in postgres db as ImageField) This is my model: class User(models.Model): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, db_column='username') password = models.CharField(max_length=100, db_column='password') profile_image = models.ImageField(upload_to='', null=True, default=None) class Meta: db_table = 'User' This is my Serializer class ProfileImageSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('profile_image',) And this is my request method (view): @api_view(['GET']) def image(request, pk): if request.method == 'GET': user = User.objects.filter(user_id=int(pk))[0] try: dict_user = {"profile_image": user.profile_image} user_serializer = ProfileImageSerializer(data=dict_user) if user_serializer.is_valid(): return JsonResponse(user_serializer.data, status=status.HTTP_200_OK, safe=False) return JsonResponse(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False) except Exception as e: return JsonResponse({'error': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) If I try GET method above it returns the image url But if I want to see the picture in browser it doesn't work This is the settings: MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' And the urls: urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('filmdb.urls')), url(r'^$', index, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Why didn't work? -
How to get total duration with minuts and second?
I am trying to display duration time for an particular work. For example 15:20:30 min Hence 15 is hour, 20 is minutes and 30 is second. class UserData(models.Model): uid = models.CharField(max_length=100) email = models.CharField(max_length=100) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(auto_now=True) @property def duration(self): if not (self.start_date and self.end_time): return None a,b=self.start_date, self.end_time return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60) It's giving me datetime.date' object has no attribute 'tzinfo' error. How can i get the duration from this property please?