Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use another website's login system to authenticate my users?
I am trying to build an app with Django and React, and I would like to use this login flow: User goes to my app's login page Once they are on my app's login page, they click a button that redirects them to another website's login page Important note: I do NOT want to use Google, Facebook, or any other social provider for this authentication. I want to use a specific website Once the user has logged in on that website, they are redirected to the pages on my website that require authentication I have looked into SSO and its various solutions to solve my problem, but it is a bit convoluted - does anyone have any advice to send me down the correct, general direction? -
Django Rest Framework serializer check if exists in related Many to Many fiield
I have a custom User model with a blocked field as class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] blocked = models.ManyToManyField("User", related_name="blocked_by", blank=True) and I'm trying to have a serializer where I can look up a user by their ID and find out if they are blocked or not by the logged in user my current is serializer class UserSerializer(serializers.ModelSerializer): is_blocked = serializers.BooleanField() # need to populate this class Meta: model = User fields = ['id', 'email', 'user_type', 'is_blocked'] and my view class UserDetail(generics.RetrieveAPIView): authentication_classes = (authentication.JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = UserSerializer queryset = User.objects.all() I'm just not sure how to populate that value such that it'd be true if the inquiried user is in the blocked manyToMany field of the logged in user or not -
Django/DRF backend not receiving complete data from POST request
I'm trying to send data to my Django/DRF backend via Axios POST requests. Some of them have been working, but some of them haven't been. This snippet, for example, works fine: axiosInstance.post( `/api/notes/`, { title, content: serialize(editorContent), } ) This one, however, has been causing problems: axiosInstance.post( `/api/notebooks/`, { name: newNotebookName, user, } ) In the second snippet, the name attribute gets through to the backend, but for some reason the user attribute does not. I tried using console.log to see if user is undefined at the moment it's sent off to the backend and it isn't. I tried to change the way I define the keys in the object I send to the backend so that they're not dynamic like in this answer and the result hasn't changed. The user variable is a string containing an email address, like 'foobar@gmail.com'. I thought maybe Django blocked it by default for security reasons, but I split the string at the @ and tried sending the first part only and it didn't work either. I also tried defining a new variable so that the type of user is string rather than string | undefined and it still doesn't work. The value of … -
A complex Django QuerySet query using ForeignKey
I'm using Django. I created 3 models: Category, Feature, Question. class Category(models.Model): category_name = models.CharField(max_length=300) category_order = IntegerRangeField(default=0, min_value=0) category_visible = models.BooleanField(default=True) def __str__(self): return self.category_name class Meta(object): ordering = ['category_order'] class Feature(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) feature_name = models.CharField(max_length=300) feature_code = models.CharField(max_length=50, unique=True) feature_predictable = models.BooleanField(default=False) def __str__(self): return self.feature_name class Question(models.Model): feature = models.ForeignKey(Feature, on_delete=models.CASCADE, unique=True) question_order = IntegerRangeField(default=0, min_value=0) question_text = models.CharField(max_length=300) question_visible = models.BooleanField(default=True) def __str__(self): return self.question_text class Meta(object): ordering = ['question_order'] I want to write a function that will return me a list of categories with category_visible == True and the value of feature_predictable for at least one instance of the Feature model in that category is True, and for at least one Question question_visible == True. Currently, I managed to create something like this: category_queryset = category_queryset.filter(category_visible=True) category_ids = [] for category in category_queryset: for feature in category.feature_set.all(): if feature.feature_predictable is not True: continue for question in feature.question_set.all(): if question.question_visible is not True: continue if category.id not in category_ids: category_ids.append(category.id) return Category.objects.all().filter(id__in=category_ids) But this is probably not the most efficient way. How to write it better? Thank you in advance for your help. -
Remove focus ring & border from Django forms using TailwindCSS
Goal: No border or focus ring in Django form. Current: I can currently only change certain attributes like text color & rounded corners but not border or focus. I am using django-widget-tweaks to assign class attributes to the form. I am using django-tailwindcss to use tailwind in Django. Attempted: I am using the tailwind ring-0 & border-0 tailwind attributes but they are not functioning at all. Code: {% load widget_tweaks %} <form action="{% url 'marketing:subscribe' %}" method="post"> {% csrf_token %} {{ form.email|add_class:"bg-black rounded-lg border-0 ring-0 focus:ring-0" }} <button class="text-green-300" type="submit">Subscribe</button> </form> -
Django Crispy Forms not working as fully intended
currently learning how to use Django and following Corey Shafer's videos to learn. So far I am able to follow along pretty easily but I am running into a formatting error when trying to use crispy forms. Right now when using it, it works to an extent but not fully. Here is what I am currently getting Here is what is expected from the videos As you can see, some of it works as intended with proper feedback and the descriptions formatted a little more clearer. But as you can see the text isn't formatted to be smaller and the feedback text isn't red but just bolded. I included below what I added to html template to implement crispy. Also for my settings.py I made sure to add CRSIPY_TEMPLATE_PACK = 'bootstrap4' and included it under my INSTALLED APPS list. This is my first time posting so if there is any information I am missing please let me know, thank you for your time! {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content%} <div class = "content-selection"> <form method = "POST"> {% csrf_token %} <fieldset class = "form-group"> <legend class = "border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div … -
Why can't I use third party database in Heroku? (If can, how?)
I am using Django+React stack and trying to use Mongo Atlas, but I can't use it because Heroku uses Postgresql by default as a free add-on. To fix this I detached the Postgres database and re-deployed the application But now it says, can't connect to the database And this is certainly the case with every other database like MySQL Please guide me "How can I use any other database in Heroku", BUT WITHOUT PAYING FOR ADD-ONS. (I mean, of course, I am using Atlas just so that I don't have to pay for the MongoDB add-on in Heroku) If there is no answer existing to this question, please at least tell me any service where I can deploy my Django application with the MongoDB database. (PS: I am a student that's why I can't pay :|) -
Retrieve particular field from my database
I would like to print the dates stored in my models.py. However, it seems like Django couldn't access them. Here you can have a look at the relevant pieces of my code: views.py from django.db.models.fields import DateTimeField from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.utils import timezone from datetime import datetime from .models import Aufgabenzettel # Create your views here. def index(request): now = datetime.now() Aufgaben_items = Aufgabenzettel.objects.all().order_by("-Geplant") #arrange objects in the correct order for Aufgabenzettel.Geplant in Aufgaben_items: #run through the loop and... print(Aufgabenzettel.Geplant) if Aufgabenzettel.Geplant == now: #...search for items in the database where the scheduled time ("Geplant") is equal to the current time return render (request, "aufgabenzettel/add.html") #response in any way e.g. by returning the add.html return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all(), #currently not used "Aufgaben_items":Aufgaben_items }) models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) Datum = models.DateTimeField(auto_now_add=True) Geplant = models.DateTimeField(auto_now_add=False, auto_now=False) def __str__(self): return f"{self.Aufgabeselbst}" Whenever I execute the index function it prints the data stored as CharField in Aufgabenzettel.Aufgabeselbst. If I change it to print(Aufgabenzettel.Datum) it prints as result <django.db.models.query_utils.DeferredAttribute object at 0x00000203BAD2A7C0>. My goal is to compare if Aufgabenzettel.Geplant == now and get … -
Django 'ListBlogPost' object has no attribute 'get_object'
here is my code. I am new in django. I am not understanding why I am getting this error 'ListBlogPost' object has no attribute 'get_object. anyone please help: #views.py class ListBlogPost(ListView,FormView): model = Blog template_name = 'blog.html' form_class = BlogFrom def get_success_url(self): return reverse('blog') def get_context_data(self, **kwargs): data = super(ListBlogPost, self).get_context_data(**kwargs) data['blog_admin_form'] = BlogFrom() return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ListBlogPost, self).form_valid(form) -
Django not logging and redirecting user
Please do not downvote, I know this question is probably easy to answer I just can't figure this out. I am creating a simple register and login system for my Django web application. I am able to successfully create a user and save it to the Django database, but I am struggling with logging a user in. I want to log a user in and redirect them to the dashboard.html page, but it won't work. All of my code is down bellow. Thank you to everyone who helps! Views.py def index(request,*args, **kwargs): return render(request, "index.html", {} ) def dashboard(request,*args, **kwargs): return render(request, "dashboard.html", {} ) def register(request, ): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('loginpage') context = {'form': form} return render(request, "register.html", context ) def loginpage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username =username, password = password) if user is not None: login(request, user) return redirect('dashboard') context = {} return render(request,"login.html") Urls.py urlpatterns = [ path('',views.index, name = 'index'), path('home/',views.index, name = 'index'), path('register/',views.register, name = 'register'), path('admin/', admin.site.urls), path('login/', views.loginpage, name = … -
Translating words in array in javascript file in django
I installed the JavaScript Catalog for translating text in javascript files as explained in the docs: https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#module-django.views.i18n That works well. I can create the PO translation files and als make and compile the translations. For example: gettext("my-translation") will work just fine. Now I want get an array from an API call which looks like this: let arr = ["red", "green", "yellow", "blue"]. I don't know how I can use gettext to create the translations for each word in the array. I tried to map it with arr.map(i => gettext( + i + ")"));. I also tried to add it to the whole array with gettext(arr), but no success. My websearches did not help me. I cannot change the representation of the array, so I need to do this in the frontend. Is there any trick for this? Thanks for any help and hints. -
How to enable a user to add something to a site on Django
I am trying to enable the user to add new hotel on site when he is logged in. I have made registration, login and also I can add something when user is logged in, but it is not added by logged user, it is added by superuser and that is what I want to do. There is my codes and I hope you will help me. views.py (accounts) def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1 == password2: if User.objects.filter(username=username).exists(): messages.warning(request,"username taken") return render(request, 'register.html') elif User.objects.filter(email=email).exists(): messages.warning(request,"email taken") return render(request, 'register.html') else: user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() messages.success(request,"Account successfully created, thank you for register.") createduser = True return render(request, 'register.html') else: messages.warning(request,"Password does not match, please, try again.") return render(request, 'register.html') else: print('Account has not created, please, try again.') return render(request, 'register.html') models.py from django.db import models class Hotel(models.Model): name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STARS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) stars = models.TextField(max_length=1, default=5, choices=HOTEL_STARS, null=True) pictures = models.ImageField(upload_to="images", default="images/default.jpg") created = models.DateTimeField(auto_now_add=True, null=True) def … -
Form not submitting unless submitting twice. Ajax, vanilla js, django
I am trying to submit a Django form with AJAX and Vanilla JavaScript however the form is not actually submitting unless I click the submit button twice. I have an event listener on the form that stops the default submission to avoid page reload and then I open a XMLHttpRequest. On the first submission I get a 200 response but the data hasn't actually been sent to the database. However if I click the submit button again I get the desired 201 (item created) response from the server and it reloads my posts and adds the new one perfectly. I am still a bit unfamiliar on working with asynchronous data and cannot figure out why it's not working. If I remove the e.preventDefault the form submits correctly and the new post shows up after the page reloads. relevant JS snippet: const postCreateFormEl = document.getElementById("post-create-form") const postsEl = document.getElementById("posts") const handlePostSubmit = function(e){ e.preventDefault() const myForm = e.target const myFormData = new FormData(myForm) const url = myForm.getAttribute("action") const method = myForm.getAttribute("method") const xhr = new XMLHttpRequest() xhr.open(method, url) xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.onload = function() { const serverResponse = xhr.response console.log(serverResponse, xhr.status) const postsEl = document.getElementById("posts") loadPosts(postsEl) } xhr.send(myFormData) } postCreateFormEl.addEventListener("submit", … -
Write a title that summarizes the specific problem(ERROR HOSTING DJANGO WEBSITE)
Hey everyone i m new to django , and trying to deploy django website on heroku but showing some errors plz help. ERROR:- import numpy ModuleNotFoundError: No module named 'numpy' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed here is my files:- https://github.com/Taranjeet105/TextAnalyzer Thank in advance -
Django Form validation Pseudo Code algorithm
I have always struggled with form validation in Django, I made some pseudo code to reference while reading through all the documentation, is my understanding of how validation works correct, any corrections or improvements to the below pseudo code? form.is_valid() or form.errors: # form.is_valid() is perferred way form.full_clean() = for field in form.fields: field_name = field.field_name field.clean() = try: form.cleaned_data[field_name] = field.to_python() = # Accepts raw value from widget and coerces it. E.g. A FloatField will turn the data into a Python float or raise a Validation Error. return cleaned_value := (coerce)value field.validate() = # *Override this # For custom field-specific validation that is not suitable for a validator (which tend to be generic). # Should not alter the value. if not custom_validation(): raise ValidationError() return # Does not return anything field.run_validators() = # Should not need to override this errors = [] try: for validator in field.validators: validator.validate() except ValidationError as e: errors += e form.cleaned_data[field_name] = form.clean_<field_name> = # *Override this # Custom field cleaning. # Must return a value, as it replaces the value in cleaned_data. cleaned_value = self.cleaned_data[field_name] custom_cleaned_value = custom_clean(cleaned_value) return custom_cleaned_value except ValidationError: continue form.clean() # *Override this # Place custom validation that depends … -
Drf token authentication password reset
I'm wondering whether Django rest framework token authentication has password reset property. I have a Django app where I'm using token authentication to register and login users. But I was told that in order for me to implement password reset in the Django app I have to switch to packages like JWT or Knox. But I would like to use drf token authentication without switching to jwt or Similar package. How should I go about this, is it possible? -
This is an online shopping program. I am getting some error while submitting . The serializer is not getting valid
The data is not getting submitted. I tried many trial and error methods. I want to submit some values which are user-defined and some by their calculations. models.py class Cart(models.Model): item_name = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) store_id = models.CharField(max_length=10) order_price = models.IntegerField() user = models.ForeignKey(CustomUser, on_delete= models.CASCADE) serializer.py class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = "__all__" views.py class AddToCartAPI(APIView): def post(self, request, *args, **kwargs): serializer = CartSerializer(data = request.data) email = request.data.get('email') user = CustomUser.objects.get(email=email) if serializer.is_valid(raise_exception=True) : store_id = serializer.data.get('store_id',None) quantity = serializer.data.get('quantity',None) item_name = serializer.data.get('item_name' ) item = Item.objects.get(item_name=item_name) total_price = (item.price) * int(quantity) serializer.save(user=user,order_price = total_price) return Response({"items added to cart"}, status=status.HTTP_200_OK) return Response({"message": "Invalid request?????"}, status=status.HTTP_400_BAD_REQUEST) -
Connecting IoT Device with HTTPS Endpoint (Django Web App) via AWS IoT Core
Web technology and aws are new to me. My goal is to send data from a device to Django web app via AWS IoT Core. In AWS IoT Core, there is an option to added HTTPS endpoint for Routing data directly from IoT Core to web services. I have been able to receive data from device to AWS IoT Core and add HTTPS endpoint (Django web app hosted on Heroku) by adding key received on Heroku log from AWS. In AWS, it shows endpoint enabled after adding the key. Now, whenever device sends payload, I am expecting the payload to be routed to web app. I am watching log to verify this, but I cannot see data. I am expecting that once payload appears in log, I should be able to read data using HTTP GET and display on html frontend. Is my expectation correct or am I missing something? -
Inconsistency Errors in kombu using celery and redis with the key '_kombu.binding.reply.celery.pidbox'
I have two Django sites (archive and test-archive) on one machine. Each has its own virtual environment and different celery queues and daemons, using Python 3.6.9 on Ubuntu 18.04, Django 3.0.2, Redis v 4.0.9, celery v 4.3, and Kombu v4.6.3. This server has 16 GB of RAM, and under load there is at least 10GB free and swap is minimal. I keep getting this error in my logs: kombu.exceptions.InconsistencyError: Cannot route message for exchange 'reply.celery.pidbox': Table empty or key no longer exists. Probably the key ('_kombu.binding.reply.celery.pidbox') has been removed from the Redis database. I tried downgrading Kombu to 4.5 for both sites per some stackoverflow posts and setting maxmemory=2GB and maxmemory-policy=allkeys-lru in redis.conf per celery docs (https://docs.celeryproject.org/en/stable/getting-started/backends-and-brokers/redis.html#broker-redis); originally the settings were the defaults of unlimited memory and noeviction and these errors were present for both versions of kombu I still get those errors when one site is under load (i.e. doing something like uploading a set of images and processing them) and the other site is idle. What is a little strange is that on some test runs using test-archive, test-archive will not have any errors, while archive will show those errors, even though the archive site is not doing … -
How would I automatically make models just by the information from uploading a CSV file in django? As opposed to manually making models in models.py?
Hello I would like to make an automatic model maker where it would parse through the csv file that is uploaded via form. It then would make a new model every time with their respective fields. Does anyone know how to do this? -
How to disable inline labels in django inline admin?
In my Django admin, I want to disable the below-shown paragraph. Please help me out. I am new to changing djano admin. Image Here Here is my current admin.py class ImageInlineAdmin(admin.StackedInline): model = Image max_num = 1 class BlogAdmin(admin.ModelAdmin): inlines = [ParagraphInlineAdmin, ImageInlineAdmin] list_display = ['heading','id'] Here are my models class Container(models.Model): heading = models.CharField(max_length=100, blank=True, default="") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.heading class Paragraph(models.Model): content = RichTextUploadingField() container = models.ForeignKey( Container, on_delete=models.CASCADE, blank=True) def __str__(self) -> str: return self.content P.S I am using Django CKeditor -
Dajngo admin ModelForm: how to get request and/or user loggin in my form to filter queryset?
I have a custom User class with a property that return a queryset And I have an Admin class that use a custom ModelForm with 2 ModelChoiceField and fone BooleanFields. I want to filter queryset of one ModelChoiceField using user property but my problem is that I do not have access to request or user in my ModelForm. I try to use method get_form_kwargs I use for 'normal CBV' but it doen't work as this method do not exist in ModelAdmin admin.py class User_TableAdmin(SimpleHistoryAdmin): def __init__(self, model, admin_site): super(User_TableAdmin,self).__init__(model,admin_site) self.form.admin_site = admin_site # capture the admin_site form = User_TableAdminForm **# How to request object to my form?** list_display = ('id','user','table','can_download') search_fields = ('user','table','can_download') forms.py class User_TableAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(User_TableAdminForm, self).__init__(*args, **kwargs) # add the 'green +' button to create a new user (green + button suppress when overidding field with ModelChoiceField) self.fields['user'].widget = RelatedFieldWidgetWrapper( self.fields['user'].widget, self.instance._meta.get_field('user').remote_field, admin_site) class Meta: model = User_Table fields = '__all__' # display only tables of study database that user workin: User property # tables = self.user.can_download tables = Table.objects.all() **#<- I would like to use something like request.user.can_download** user = forms.ModelChoiceField(queryset = User.objects.all(), label = "User", widget = forms.Select()) table = forms.ModelChoiceField(queryset = … -
What is the best technique for real time server-client communication?
I need to create a web site with Flask or Django where I can plot real time sensor (IOT) reading without loosing any information. is sockets the best solution ? or there exists another solution which serve better for this task ? -
Django Rest Framework pass value in dynamic url into queryset
I have have a dynamic url that will display the same page to the user but with specific data depending on the value that is in the url. I am trying to set up a REST serializer that will return the filtered data based on the value that is in the url. I am not sure how to pass this value in the url into the queryset class I have. urls.py urlpatterns = [ path('sets/<str:setCode>/sets-individual-data', SetsIndividualData.as_view(), name='sets-individual-data'), } view.py class SetsIndividualData(ListAPIView): serializer_class = SetDetailsSerializers def get_queryset(self): queryList = Card.objects.filter(code=setCode) return queryList -
Why I cannot see a error message from ValidationError Django?
I have done what is written on Django Documentation and I have tried several Youtube tutorials, including Stackoverflow's advice. However, I could not make the message "Validation Error" appear on the template. When I click the button to create a post whit bad_word, I redirect to the same page, the post isn't saved but the form doesn't show me the message. I tried to save in a print({{ form.errors }}) in the view and the terminal showed the message that I want to see in the template: contentError So I don't know what I'm doing wrong... #view.py if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] username = User.objects.get(username=f"{request.user}") new_post = Post(user=username, title=title, content=content, datetime=timezone.now()) new_post.writeOnChain() cache.expire("cache", timeout=0) return HttpResponseRedirect("/") else: form = PostForm() return render(request, "api/homepage.html", {'form': form, 'postList': postList}) > #forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'content',) def clean_title(self): title = self.cleaned_data['title'] if "bad_word" in title: raise forms.ValidationError("Error") return title def clean_content(self): content = self.cleaned_data['content'] if "bad_word" in content: raise forms.ValidationError("Error") return content #template <div class="p-3 forms m-3"> <form class="crispy" action="{% url 'homepage' %}" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn buttons" value="Create Post"> …