Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django interaction between two projects deployed in azure in two different ports
In django I am having two projects project1 will take care of user registration, login, authentication(token based authentication) and project 2 have one application running in it. Now my problem is for project2 I am unable to provid security if someone know the url anyone can use for free. In project1 by using some code i am sending request to project2 and returning response Now i need an approach to protect project2 from unauthorised usage(for security reasons) Note: I can't club both as a single project(for some reason) -
Pandas read_csv function to handle both utf-8 and utf-16 issue
User can upload both UTF-8 and UTF-16 CSV file which is the attendance file of Microsoft teams that they download from there. To handle the case I have written the following code but there is some strange issue that I am not able to fix. excel_file = request.FILES['excel-file'] try: print('try case') df = pd.read_csv(excel_file) csv_type = 'a' print(df) except UnicodeDecodeError: print('except case') from io import BytesIO df = pd.read_csv(BytesIO(excel_file.read().decode('UTF-16').encode('UTF-8')), sep='\\') csv_type = 'b' print(df) except Exception as e: print("Incorrect CSV file format", e) Here first 'try case' handle the UTF-8 and 'except case' handle the UTF-16 CSV file. Both case work fine if I run them separately, But when I put them in try except block then the code fails. Here in the above code UTF-8 case works but UTF-16 gives No columns to parse from file error. Now if I move the except code to try then UTF-16 will work but it will also run for UTF-8 giving wrong data. So how can I handle this case haven't found any way to get file encoding also. -
Docker Django services not communicating
I am trying to get my listener service to POST at an API in the app service. The app service is running at 0.0.0.0:8000 and the listener service is trying to post at this address but the data isn't getting added to the db. I am not sure if I have configured this correctly, help would be much appreciated. docker-compose.yml services: db: image: postgres:13.4 env_file: - ./docker/env.db ports: - 5432:5432 volumes: - db_data:/var/lib/postgresql/data app: build: context: . dockerfile: ./docker/Dockerfile env_file: - ./docker/env.db - ./.env volumes: - .:/opt/code ports: - 8000:8000 - 3000:3000 depends_on: - db command: bash ./scripts/runserver.sh listener: image: scooprank_app env_file: - ./.env container_name: listener command: npm run listen depends_on: - app restart: always -
Django with Aws Application load balancer
What is the deployment flow to achieve load balancing using multiple Ec-2 instances? do I have to configure my project with both ec2 manually first and then use them with the App Load balancer? -
Key Error while trying to register user Django
Imm getting a key error "password" on serializer.py while validating the data. Imm using Django's built in User model and Token Authentication to register a user. here's how my serializer.py looks like. from django.contrib.auth.models import User from rest_framework import serializers class RegistrationSerializer(serializers.Serializer): password2 = serializers.CharField(style={"input_type" : "password"}, write_only=True) class Meta: model = User fields = ["username", "email", "password", "password2"] extra_kwarg = { "password": { "write_only": True, } } def validate(self, data): if data["password"] != data["password2"]: return serializers.ValidationError("Your password must be same!") if data.objects.filter(email=data["email"]).exists(): return serializers.ValidationError("This Email is already registered!") return data views.py from rest_framework.response import Response from user_app.api.serializer import RegistrationSerializer from rest_framework.decorators import api_view @api_view(["POST",]) def register_user(request): if request.method == "POST": serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return serializer.error_messages()``` Errors serializer.py", line 22, in validate if data["password"] != data["password2"]: KeyError: 'password' -
Can't import models in Python shell
I'm doing the Django official tutorial (documentation). I've created two database models (Question, Choice). I'm trying to import them by first entering the python shell by using python manage.py shell Then I run from polls.models import Question,Choice and nothing happens, it just enters an empty line. In the documentation, it's showed that I'm supposed to see some information regarding the database. I've done the migration and also put the app config in settings.py -
why it is not displaying slug field on the address bar?
I am new to Django. I encountered an error while practicing on the slug field adding to the model. it is not working after I run the program. The browser is not displaying any error. I have written the code below please have a look and anybody help me out? feel free to ask me if you have any questions. Thank you for your help. models.py from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify import string,random from temp1.util import unique_slug_generator STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, null = True, blank = True) text = models.TextField() published_at = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') class Meta: ordering = ('-published_at', ) def __str__(self): return self.title @receiver(pre_save, sender=Post) def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) urls.py from django.urls import path from .views import detail urlpatterns = [ path("posts/",detail,name="home") ] util.py import string, random from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): return … -
home.html isn't displaying tags
The tags aren't showing in the home page. but it appears in post_detail.html. Its not working as I want it to work. Can anyone fill me up with mistakes here and solutions? blog/views.py: def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) context={ 'posts': posts, #introduces the content added in Post Class 'tag':tag, } return render(request, 'blog/home.html', context) class PostListView(ListView): model=Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name= 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model=Post blog/urls.py: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('tag/<slug:tag_slug>/',views.home, name='post_tag'), templates/blog/base.html <div class="col-md-4"> <div class="content-section"> <h3>Sidebar</h3> <p class='text-muted'>Informations <ul class="list-group"> <li class="list-group-item list-group-item-light" style="text-align:center"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a> {% endfor %} </div> </div> </li> </ul> -
Django Class Based View (FormView)
class ReviewView(FormView): form_class = ReviewForm template_name = "review/review.html" success_url = "/thank-you" def form_valid(self, form): form.save() return super().form_valid(form) this is the error how can I fix it AttributeError at / 'ReviewForm' object has no attribute 'save' -
Dynamic Dropdown values django
I want to create a dropdown Course of Trainee where only options of values in CourseName of Course model would be shown. Currently I have tried some soulutions after browsing. But its not working. My course dropdown disappeared after editing in forms.py. If i remove this line Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') Then the dropdown would show but with no options model.py class Course(models.Model): CourseID = models.AutoField(primary_key=True) CourseName = models.CharField(max_length=20) class Meta(): db_table = "Courses" def get_course_name(self): return self.CourseName class Trainee(models.Model): Name = models.CharField(max_length=50) Course = models.CharField(max_length=40) class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): course_obj = Course() Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') ........................ edit.html <form method="post" class="form-group" type="multipart/form-data"> {%csrf_token%} {% for Name in form.Name %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Name.label }}</label> {{ Name }} </div> {% endfor %} {% for Course in form.Course %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Course.label }}</label> {{ form.Course }} </div> {% endfor %} The Page appears like this -
django summernote how to limit the number of images or total image size
I'm touching a Django summernote. But there's a problem. I can limit the size of one image, but how do I set the total number of images per post or the total image size? plaese help me -
How to avoid 'callback' error page in django-allauth( GoogleAuth)?
I am developing some django app and implemented authentication via Google. Everything works fine, but if user logins via Google, goes back to Google-login page with browser`s 'previous page' button, hi might login again and see this error page: Page I don`t want users to see that. How can I avoid this 'error' page? -
How can I serve staticfiles in Django in Railway app when Debug is False
When I set DEBUG to False on Railway's variables my images from uploads are not loading. How can I fix that? my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / "uploads" MEDIA_URL = "/uploads/" my urls.py has + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and I used python manage.py collectstatic -
The terminal gives me as error a path that I don't have in my code with Django
I'm working on Django, developing a site This gives me an error: Not Found: /plans/investment_per_plan_chart Not Found: /plans/active_running_plans I have searched with VSC but I can't find anything in my code that looks like this error. Please help me I'm lost -
Why is my Django FormModel is not submitted when I click submit button?
I am working on simple login and signup pages on Django. This is how they work: You create an account in the signup page. After the process is complete, it redirects you to the login page. However, when you click a button to submit information on the signup page, it is not submitted. Here are the codes: urls.py from django.urls import path, include from . import views urlpatterns = [ path('account/login', views.login_page, name='login'), path('account/signup', views.signup_page, name='signup') ] models.py from django.db import models class User(models.Model): username = models.CharField(max_length=30,) password = models.CharField(max_length=255) firstName = models.CharField(max_length=255) lastName = models.CharField(max_length=255) emailAddress = models.EmailField(max_length=255) def __str__(self): return self.username forms.py from .models import User from django.forms import ModelForm, TextInput, PasswordInput, EmailInput class UserForm(ModelForm): class Meta: model = User fields = ['username', 'password', 'firstName', 'lastName', 'emailAddress'] widgets = { 'username': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': 'signup_input', 'placeholder': 'Password' }), 'firstName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'First Name' }), 'lastName': TextInput(attrs={ 'class': 'signup_input', 'placeholder': 'Last Name' }), 'emailAddress': EmailInput(attrs={ 'class': 'signup_input', 'placeholder': 'Email Address' }) } labels = { 'username': '', 'password': '', 'firstName': '', 'lastName': '', 'emailAddress': '' } views.py from django.shortcuts import render, redirect from .forms import UserForm def login_page(request): return render(request, 'Account/login_page.html') … -
Firebase Cloud Messaging not working for programmatically sent messages using Python
If I go into my firebase console and setup a campaign my end devices receive the notification just fine, but for messages to specific devices using the device's registration token, sent from django/python, I get no notification on my mobile devices. Not sure if this matters but my app is still in development, it is not in production, so if this matters please let me know. My frontend is flutter, here is the flutter code I am using to get the registration token and send it to the backend: Future<StreamedResponse> AddProductPut(context, pk, name, quantity, cost, selling, XFile? chosenImage) async { String id_token = await FirebaseAuth.instance.currentUser!.getIdToken(); late String? fcm_token; await FirebaseMessaging.instance.getToken().then((token) async { fcm_token = token!; }).catchError((e) { print(e); }); print(fcm_token); var url = backend + "/pm/createproduct/" + pk.toString() + "/"; var request = http.MultipartRequest('PUT', Uri.parse(url)); print("FCM TOKEN"); print(fcm_token); request.headers["Authorization"] = "Token " + id_token; request.fields["name"] = name; request.fields["quantity"] = quantity.toString(); request.fields["cost_price"] = cost.toString(); request.fields["selling_price"] = selling.toString(); request.fields["barcode"] = "11111"; request.fields["token"] = fcm_token!; request.files.add( await http.MultipartFile.fromPath( 'image', chosenImage!.path ) ); return await request.send(); } Here is the python code in my django serializer to send the notification message: registration_token = self.context['request'].data["token"], print(registration_token[0]) print(type(registration_token[0])) # See documentation on defining a message payload. … -
change text content (like, unlike) Django Like Button
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I created a model that saves the likes by saving the liked post and the user that liked the post. I want to make a like button in the HTML page that has its inner text(like) if the user hasn't liked the post and unlike if the user liked the button by using arrays in models.py: class likes(models.Model): liked_post = models.ForeignKey("posts", on_delete=models.CASCADE) like_user = models.ForeignKey("User", on_delete=models.CASCADE) in views.py: def index(request): allposts = posts.objects.all() m = ['empty'] aa = [0] for post in allposts: postid = post.id print(postid) aa.append(int(postid)) liked__post = posts.objects.get(id = postid).id if likes.objects.filter(like_user = request.user, liked_post = liked__post).exists(): f = 'unlike' m.append(f) c = 'liked__btn' else: t = 'like' m.append(t) c = 'like__btn' print('like') print(m[0]) print(aa) return render(request, "network/index.html",{"allposts": allposts, 'm':m, 'c':c, 'aa':aa}) @csrf_exempt def like(request, post_id): liked__post = posts.objects.get(id = post_id) if request.method == 'PUT': print('we\'ve hit put') data = json.loads(request.body) if data.get('like') is not None: print('in like') # Note: [User Obj Itself] # follower = request.user (is: <User Obj>) # following = x (is: <User Obj>) likes.objects.create(liked_post=liked__post, like_user=request.user) elif data.get('unlike') is … -
Django block user from modifying a form input
I have a instance Form that is showing the user his Profile Data, the user can update some of his profile settings by modifying the input and clicking the update button. But I don't want the user to be allowed to change all the profile data, such as the subscriptions Charfields. How can I do that? models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) telegramusername = models.CharField(max_length=50, default=None) subscription = models.CharField(max_length=50, default=None) numberofaccount = models.CharField(max_length=50, default=None) def __str__(self): return self.telegramusername forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile labels = { "telegramusername": "Telegram Username", "subscription": "Subscription Plan", "numberofaccount": "Number of MT5 Account" } fields = ["telegramusername", "subscription", "numberofaccount"] views.py def dashboard(request): profile_data = Profile.objects.get(user=request.user) profile_form = ProfileForm(request.POST or None, instance=profile_data) if profile_form.is_valid(): print("worked") profile_form.save() context = { 'profile_form': profile_form } return render(request, "main/dashboard.html", context) -
Choice_set and id members are unknown
I'm getting started with django, I've been following the official tutorial and I've run into an issue. I have this block of code: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render( request, "polls/detail.html", { "question": question, "error_message": "You didn't select a choice.", }, ) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) The code works perfectly fine, however, for some reason VS Code highlights the ID and CHOICE_SET attributes. Here's my models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self) -> str: return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self) -> str: return self.choice_text I suppose that there's an issue with VS Code because as I said the code works just fine and I can run it. I just really wanna remove the red highlighting and fix it. -
Debugger does not start in VSCode for Django
I'm trying to debug my Django project, but whenever I hit the play button on the run and debug window in VSCode, it thinks for a second, and then completely stops. My project runs completely fine when I run it with the "runserver" command. I've tried restarting VSCode, and restarting my computer. here is my launch.json file { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver", "9000" ], "django": true } ] } -
why does the image not appear in the template when I run Django
List item Tried several ways in all available ways to show the image in the template, but it did not appear, but in django - admin add and show List item Tried several ways in all available ways to show the image in the template, but it did not appear, but in django - admin add and show modles.py class Delivery(models.Model): # order = models.ForeignKey(Order, on_delete=models.CASCADE) ddesign = models.CharField(max_length=50,null=True) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE, null=True) dcolor = models.CharField(max_length=50,null=True) courier_name = models.CharField(max_length=120) frist_name = models.CharField(max_length=120,null=True) scand_name = models.CharField(max_length=120,null=True) therd_name = models.CharField(max_length=120,null=True) ford_name = models.CharField(max_length=120,null=True) fifth_name = models.CharField(max_length=120,null=True) dimg = models.ImageField(null=True, blank=True ,upload_to='media/') created_date = models.DateField(auto_now_add=True) def __str__(self): return self.ddesign forms.py > class DeliveryForm(forms.ModelForm): > class Meta: > model = Delivery > fields = '__all__' > > widgets = { > > 'ddesign': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'ddesign' > }), > 'buyer': forms.Select(attrs={ > 'class': 'form-control', 'id': 'buyer' > }), > 'dcolor': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'dcolor' > }), > 'courier_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'courier_name' > }), > 'frist_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'frist_name' > }), > 'scand_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'scand_name' > }), > 'therd_name': forms.TextInput(attrs={ > 'class': 'form-control', 'id': 'therd_name' > }), > 'ford_name': … -
CSS Is Not Rendering Correctly
So my project is running on a django backend with React for the frontend. The issue I am having is that my react components are rendering, but they are not structured correctly (margins messed up, no borders, components overlapping) even though my CSS is correct. I think the cause is in the base.html in the django portion of the project, as webpack is bundling through that. I tried adding link references to no avail. Note* I am importing Dashboard as a const into the UserApp class which, while I don't think is the cause of the issue, could be the culprit, not sure. How its supposed to look: https://postimg.cc/TKKtL00S How it looks: https://postimg.cc/qhwsZ6Qy Base.html: {% block css %} {% compress css %} <!-- <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> --> <link rel="stylesheet" href="{% static 'css/font-awesome.css' %}"> <link rel="stylesheet" href="{% static 'css/LineIcons.css' %}"> <link rel="stylesheet" href="{% static 'css/materialdesignicons.min.css' %}"> <link rel="stylesheet" href="{% static 'css/fullcalendar.css' %}"> <link rel="stylesheet" href="{% static 'css/fullcalendar.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <!-- <link rel="stylesheet" href="../../../rsm-app-react/Dashboard.css"> --> {% endcompress %} {% compress css %} <!-- <link href="{% static 'css/app.css' %}" rel="stylesheet"> --> {% endcompress %} {% endblock %} {% block css_extra %} <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css"> {% … -
django REST framework - allow only list of IP addresses to access?
I am trying to figure out the correct way to limit access to an API endpoint using IP address. I went through the docs, blocking is mentioned but limiting the call to API endpoint is not. What is the correct way to do this? -
How to see auto generated Primary Key of a model and to use it like FK in Django?
How I know that models in Django have by default auto incremented id, but I want to see it in Django Administration and to take this id in order to put it in other model like FK class Customer(models.Model): customer_id = #TO BE auto incremented PRIMARY KEY user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) def __str__(self): return self.name class Wallet(models.Model): customer_id = #to take customer_id (by default django generate it, but how to introduce here like fk) usd = models.FloatField(null=True) -
Output is not rendered on Django template for the same model whose output is rendered on another template
I am really new to Django and I am building a website while learning it. As per requirements, I have to show some news articles on both the home page and on another page that I navigate from the navbar. I have shown the articles list and individual details with the loop in my template files. Problem is, although I have written the for loop for rendering the news article on the home page, nothing is showing up. Following are my models.py, views.py, app/urls.py, and project/urls.py files : #models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager from ckeditor.fields import RichTextField class News(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) news_title = models.CharField(max_length=250) # slug = models.SlugField(max_length=250, unique_for_date='nw_publish', unique=True, null=True) slug = models.SlugField(max_length=300, unique_for_date='nw_publish') news_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_posts') news_body = RichTextField() image_header = models.ImageField(upload_to='featured_image/%Y/%m/%d/', null=True, blank=True) nw_publish = models.DateTimeField(default=timezone.now) nw_status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') news_tags = TaggableManager() class Meta: ordering = ('nw_publish',) def __str__(self): return self.news_title #views.py from django.views import generic from django.views.generic import ListView, DetailView from django.http import Http404 from .models import Post, Report, News, Member, Project class NewsListView(ListView): …