Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extracting charts of xlsx using python
I want to extract the charts in an xlsx file and save them as an image using python. I know how to do that by win32com.client and importing Dispatch. But I am asking this to implement by django and I am working on a Linux based server, the method based on win32com.client doesn't work. Could anyone guide me how can I do that? -
Django: How to return a clean list from db for charts.js?
I would like to update charts.js with info from my database. To do that in my view i have this: def processCharts(request): process = ProcessInfo.objects.values_list('process_name') process_list = list(process) context = {'process_list' : process_list, } return render(request, 'process/charts.html', context) i would like to retrive a list i can put into charts.js and that looks like this labels: ['Option1', 'Option2', 'Option3', 'Option4', 'Option5', 'Option6', 'Option7'], When i render process_list on charts.js i get a messy list like the one below: labels: [('Accounts Recivabel',), ('dsas aasdasds',), ('Test user 2',), ('Accounts Recivabel',), ('Test user 2',), ('Accounts Recivabel',), ('Test user 2',), ('Test user 2',), ('Recivabel',), ('Accounts Recivabel',), ('Accounts Recivabel',), ('Cash app v 123',), ('Recruiting',), ('Accounts Recivabel',)], How can i clean my querryset or the objects from the database to get a clean list for charts.js ? -
How to create a comment-creation page related to a single blog-style post in Django
I am trying to create a comment creation page related to a single post on a blog-style site using Django. The home page has a list of posts, each with a "comment" button. Ideally this "comment" button would then take you to a page that would have the original post listed at the top with the comment creation form underneath it. I've been trying to figure out a way to access the data I'm looking for using primary keys but am not sure how to tie everything together. Here are the 2 models I am trying to access (Post and Comment): class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField() image = models.ImageField(upload_to='post_pics', blank=True) date_posted = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_created = models.DateTimeField(default=timezone.now) And the urls.py: from django.urls import path from .views import PostCreateView, PostListView, VehicleListView, CommentCreateView from . import views urlpatterns = [ path('', PostListView.as_view(), name='home'), path('comment/new/<int:pk>', CommentCreateView.as_view(), name='comment-create'), ] This is my current HTML for the home page (currently adds the post id to the end of the HTML on linked "comment-create" page): {% for post in posts %} … -
CORS Allow not working - Django and Vuejs [duplicate]
I am using Django with Django rest framework to host my api's (localhost:8000), and use vue js running on node js server (localhost:8080) to call the apis to view it. when I try to use vue axios to call a rest api I get this response: Access to XMLHttpRequest at 'http://localhost:8000/api/getJobs' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. My Django setting.py is (I installed cors headers / allow all origins) but no luck, here is my code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app_dashboard', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True Any solution? -
Django admin page ManyToManyField displays all rows from database
I have the following models: class OrderItem(models.Model): item = models.ForeignKey(FoodDish, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" def get_total_item_price(self): return self.quantity * self.item.price class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) order_date = models.DateTimeField(blank=True, null=True) ordered = models.BooleanField(default=False) total_price = models.FloatField(blank=True, default=0.0) def __str__(self): return f"{self.user.username} ordered on {self.order_date}" Inside the administration page I want to see the items related to a certain order. When entering the page for a certain order however, the field that contains the ManyToManyField displays all the OrderItems in the database (with the entries that are related to the current order highlighted). Why does the datafield in the administration page display all those entries? -
How to selectively specify a django model field value when creating different model objects?
I have the following models in my django app: from django.db import models class Parent(models.Model): my_attribute = models.CharField(max_length=255, blank=True) my_attribute2 = models.CharField(max_length=255, blank=True) class Child(Parent): tracking = models.CharField(max_length=255, blank=True) Then I have another file where I am trying to make instances of these two models. What I intend to do is invoke the create method, based on a parameter, something like this: from .models import * class BaseObjectCreator: model = Parent def createModelObject(trackingEnabled=False): instance = self.model.objects.create( my_attribute = 'value1', my_attribute = 'value2', tracking = 'value3' if trackingEnabled ) class ChildObjectCreator: model = Child def createModelObject(trackingEnabled=True): super().createModelObject(trackingEnabled) But this is not working and throwing error for this line tracking = 'value3' if trackingEnabled. I need something like this for refactoring a large code which involves models like the ones defined above. Can you suggest the correct strategy? -
Django Channels 2: How Many Users Is In The Specific Room
I am using django-channels>=2.0.0 and I want to find how many users in "room1". I don't know how to find total connections. -
Add CSRF in Fetch JS for Django
I have the following JS code in my django template: fetch("http://127.0.0.1:8000/api/endpoint", { method: "POST", body: $("#form").serializeArray(), }).then(function(data) { }); In the api/endpoint, I just get: Forbidden (CSRF token missing or incorrect.): /api/endpoint How do I add the csrf token in the fetch? -
Django or Asp.Net Core? That is the problem
As a medium level .Net programmer, due to implementing a website I tried to go through the Asp.Net Core. I found some tutorials on the web and started learning; however, there was a problem I faced. Despite the fact that I have been working with .Net and C# (mostly with unity game engine, which led to a mobile game) for 2 years or even more, by start learning Asp.Net Core, I found out that I do not know .Net as much as I expected. There were somethings I should have learned before. I searched for other frameworks and Django was a popular one. Besides, I have planned to learn python for machine learning. The website I want to make (with a small team) is nearly similar to KhanAcademy.(We are going to use react for front-end) So, what should I do? Continue .Net core with its amazing new features, or start getting into the python and Django? Your helps accompanied by reasons will be greatly appreciated! -
How Can I upper the word 'i' to 'İ'?
in my project there is a profile that name is "İsmet". When Django try to search it with the following code, return empty. Profile.objects.filter(name__icontains='i') But when I try this return correctly; Profile.objects.filter(name__icontains='İ') is there a way to search with like this? By the way, I try to search with 'i.upper()' but this convert 'i' to 'I'. So this is not work for me. -
Django and Postgres: greater than for tuples
How can I compare tuples in the Django ORM? Say I have a Postgres query like: SELECT * FROM my_table WHERE (last_updated, id) > (1575452913, 123) ORDER BY (last_updated, id) LIMIT 50 How can I express this in Django? Looking at https://docs.djangoproject.com/en/3.0/ref/models/querysets/#gt nothing leaps out. The field_name__gt=something method doesn't really seem to be compatible with this. -
Why do I still get the old values for ManyToManyField comparison?
I found many ways to do it, but it seems that nothing work. I have a model that has a manytomanyfield to another model, I want to be able to compare old values from the manytomany field, and the new ones. class A(models.Model): registers = models.ManyToManyField('B',blank=True) def save(self,*args,**kwargs): try: old_registers = self.__class__.objects.get(pk=self.pk).registers.all() print(old_registers) print(old_registers.difference(self.registers.values_list())) except Analyseur.DoesNotExist: old_registers = None if (old_registers != None) and old_registers.difference(self.registers.values_list()): print("Values changed") class B(models.Model): name = models.CharField(max_length=32) Note that I interact with the models in Django Admin. When I save the instance, I always get the old values for self.__class__.objects.get(pk=self.pk).registers.all() and self.registers.all(). -
How to include multiple context elements in render()
I'm new to Django. My views.py file looks like this - from django.shortcuts import render from django.http import HttpResponse import twitterData # Create your views here. def home(request): profiles = twitterData.getTwitterProfileData() return render(request, "blog/home.html", profiles) This code works fine, profiles is simply a dict of user profile names gathered from Twitter api. Only thing is I want to put this also {"Title": "Home"}. This would allow the page to display the correct title. I try and write the code like this - # Create your views here. def home(request): profiles = twitterData.getTwitterProfileData() return render(request, "blog/home.html", {profiles, "title": "Home"}) and it doesn't run. How can I use multiple items to send to page? -
Django form not saving email
My views- from django.shortcuts import render, redirect from .AuthForms import registerUserForm from django.contrib import messages from django.contrib.auth import login, authenticate def registerUsers(request): if request.method == 'POST': ucf = registerUserForm(request.POST) if ucf.is_valid(): ucf.save() new_user = authenticate(username = ucf.cleaned_data['username'], password = ucf.cleaned_data['password1']) login(request, new_user) return redirect('content') else: ucf = registerUserForm() return render(request, 'LoginAndSignUp/SignUpPage.html', {'ucf': ucf}) My form - I have extended the usercreationform from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm , PasswordResetForm from django import forms class registerUserForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Email', 'autocomplete':'off'})) username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off',})) password1 = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'})) password2 = None class meta: model = User fields = ['username', 'email', 'password1'] class userLoginForm(AuthenticationForm): username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off'})) password = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'})) class userPasswordResetEmailForm(PasswordResetForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Enter your email', 'autocomplete':'off',})) class Meta: model = User fields = '__all__' The email field is not saving the email to database wherease the username and password is correctly being saved. Someone please help -
Inserting database search result into multiple rows not one in an excel file by django
I have written some django codes to read and save users xlsx data to database. each row in my database is one entry. Now, I want to write a function in views.py that can receive a word from the user and search it on that data base the rows containing that word, and write all of those rows to an excel file. I prefer to return it as an .xlsx file but it can be csv if xlsx is not possible. I have written this code but it has three problems: 1. The main problem: All of the found rows are saved in one row of the output. 2. the labels of them are saves at the same cell, but I prefer to have labels as the title. 3. The output is a csv file not xlsx my code: #views def download(request): try: assert request.method == 'POST' form = data_DownloadForm(request.POST) assert form.is_valid() data_types = form.cleaned_data.get('data') data = list(dataFields.objects.filter(data__contains=data_types).values()) except AssertionError: error = 'Your request has some problems.' data = error attachment = 'FoundData.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment;filename="{}"'.format(attachment) response.write(data) return response This is the output of my code in which two rows are written in one This is what … -
Render relationship model in template
I am trying to render a model with a relationship but I am not able to do so. class LogBook(models.Model): name = models.CharField(max_length=50, verbose_name="Nom du registre de maintenance") members = models.ManyToManyField(User) class LogMessages(models.Model): logbook = models.ForeignKey(LogBook) message = models.CharField(max_length=200, verbose_name="Détail du problème") class LogDone(models.Model): logmessage = models.ForeignKey(LogMessages) message = models.CharField(max_length=200) My view: log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessages.objects.filter(logbook=log_id) My template {% for logmessage in logmessages.all %} {{logmessage.logdone.message}} {{% endfor %}} But the logdone object is not showing, any idea ? -
How to seralize a MethodField with more than one object in Django?
I want to serialize a method that checks if the author of a story is the currently logged in user, if so returns true, if not false. However, the Docs of Django state that the Serliazer method requires only one argument besides self. So how can I access the user model in addition to the story (object)? I was thinking about something like that: class StorySerializer(serializers.ModelSerializer): story_owner_permission = serializers.SerializerMethodField('check_story_owner_permission') class Meta: model = Story fields = ['story_owner_permission'] def check_story_owner_permission(self, story, request): story_author = story.author.id current_user = request.user.id if (story_author == current_user): return True else: return False But it doesn't work. check_story_owner_permission() missing 1 required positional argument: 'request' -
'styles\bootstrap4\bootstrap.min.js.map' could not be found
I am new using Django and my web page is not rendering my bootstrap.css file because it simply cannot find it. This is my setting.py file: My Index.html My file structure MyProject/static/styles/bootstrap/bootstrap.min.cssstrong text Getting these errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/styles/bootstrap4/bootstrap.min.js.map 'styles\bootstrap4\bootstrap.min.js.map' could not be found -
How to add a specific level of access to a custom action in viewset in Django Rest Framework?
I have a ModelViewSet in Django Rest Framework with all crud functions and set the permissions to IsAuthenticated, but I made a custom action and want it to be public, but I have no clue on how to do that since the documentation only shows how to do that with an @api_view(), here's my ModelViewSet class UserViewSet(viewsets.ModelViewSet): """User viewset""" queryset = User.objects.all() serializer_class = UserModelSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @action(detail=False, methods=['post']) def signup(self, request): """Sign Up users without profile. """ serializer = UserSignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() data = { 'user' : user, } return Response(data, status=status.HTTP_201_CREATED) @action(detail=False, methods=['post']) def login(self, request, *args, **kwargs): """ Handle logins request. """ serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user, token = serializer.save() data= { 'user': user, 'access_token' : token } return Response(data, status=status.HTTP_201_CREATED) I want to make the login @action public, I hope you guys can help me -
Can I associate a file uploaded to a model with a session id for anonymous users in Django?
With my web app visitors should click a button which generates a unique video file - stores it in a model - and display it to them. I'm having trouble understanding how to associate the video file with the visitor without making them sign in which I don't want to do. Can I do this with sessions a bit like how a shopping cart works for guests? -
Why is Javascript not working with Django HTML?
I am trying to put some javascript code in my Django website. The javascript code is supposed to check if the buttons are being pressed and alert the user if they are. This only works for the first button, however. Because I am looping over all the buttons to display them, I think javascript is not seeing it as HTML code. Here is the javascript code. const card = document.querySelector('.card'); card.addEventListener('click', e => { if (e.target.classList.contains('btn')) { alert('hi') } }) Here is the HTML/Django code : {% extends "/Users/marco/Documents/codes/Python/Django/vracenmasse/templates/base_generic.html" %} {% load static %} {% block content %} <center><h1>Nos Produits</h1></center> <hr> <div class="row" style = "border: 50px solid white;"> {% for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="../../../media/{{ product.product_picture.name }}" alt="{{ product.product_picture.name }}"> <div class="card-body"> <center> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.product_price|floatformat:2 }}$ / unité</p> <p class="card-text">Catégorie : {{ product.type_of_product }}</p> {% if product.new_product == "yes" %} <b><p class="card-text"><font size="3.5" color="Orange">Nouveaux!</font></p></b> {% endif %} {% if product.availability == "Out Of Stock"%} <b><p class="card-text"><font size="1.5" color="red">En rupture de stock</font></p></b> <hr> <button type="button" class="btn btn-primary" disabled>Ajouter au Panier</button> {% else %} <p style="font-size:15;">Quantité : </p><input type="number" step="12" min="0" /> <span class="validity"></span> <hr> <button type="button" class="btn btn-outline-primary" id='realbutton'>Ajouter … -
Django rest framework throttling on basis of API response
I using DRF and using it's throttling feature. All is working fine. But I want to implement throttling in my Register API in such a way that only requests with a successful response should count. Below is my code. class createUser(generics.CreateAPIView): permission_classes = (AllowAny,) throttle_scope = 'register' @transaction.atomic def post(self, request, *args, **kwargs): user_data = request.data.get('user') email = user_data.get('email') email_ser = verifyEmailSerializer(data={'email_id': email}) if email_ser.is_valid(): return errorResponse('USER_EXISTS') else: # do something Please suggest the way to achieve it. -
Django-import-export get auto generated id during import
I am trying to import an excel without an ID field specified and the ID is being auto genetrated by django. I need to access this auto generated ID field but i cannot figure out how to do it. accessing the entire row doesnot give the auto generated ID. Any ideas on how to access the auto generated ID field? -
How to run python code at the background without impacting rendering of html template?
Concept that I want to achieve: A web application that listens to user's speech at the background and do what the user wants. What I have: A Python - Django application with Speech Recognition enabled with the following two files. speechrecognition.py (This is where speech recognition related logic is) index.html Note: speechrecognition.py goes on a loop repeatedly listening to user's input. What I tried: I tried calling speechrecognition.py class before rendering index.html in views.py from SpeechRegApp.speechrecognition import SpeechRecognition def index(request): SpeechRecognition() return render(request, "index.html", {}) Problem that I'm facing: Since I'm repeatedly listening to user's input in speechrecognition.py, index.html doesn't get rendered. How to fix this issue? -
sign up with email instead username
i want the user to sign up with his email instead of registering with a username forms.py class ExtendedUserCreationForm(UserCreationForm): email= forms.EmailField(required=True) class Meta: model=User fields=('username','email','password1','password2') def save(self ,commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user views.py: candidat here is just a model with a OneToOneField with user for more information in the sign up form def register(request): if request.method == 'POST': form = ExtendedUserCreationForm(request.POST) candidat_form = CreateCandidat(request.POST) if form.is_valid() and candidat_form.is_valid(): user = form.save() candidat = candidat_form.save(commit=False) candidat.user = user candidat.save() username= form.cleaned_data.get('username') password= form.cleaned_data.get('password1') user = authenticate(username=username ,password=password) login (request, user) return redirect('profil') else: form = ExtendedUserCreationForm() candidat_form = CreateCandidat() context= {'form' : form , 'candidat_form' : candidat_form} return render(request, 'registration/register.html',context)