Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save data from telegram session - django
I have a telegram bot that sends a link to let the user authentificate with twitch, obviously when twitch send a response only gives me information about the twitch user that logged in, how can i get information like who is the telegram user that clicked the link? I asked a similar question here but now i realize that i didn't understand what to do (anyway probabily the answer i received is more useful to you). views.py @csrf_exempt def telegramBot(request): #function that handles telegram messages request.session['telegramID'] = "telegramID" return telegramBotFunction(request) #return a http response #the user is redirected here after login with twitch, how can i get the telegram id? def verify(request): telegramID = request.session['telegramID'] #ERROR! print("telegramID", telegramID) return gestioneVerificaAuth(request) #return HttpResponse("<h2> Twitch user is subscribed/or not to streamer X <h2>) this gives an error because doesnt find the key ['telegramID'], how can i save the telegramID? Any help or also a small hint is appreciated -
Trying to update Django model with dynamic variable
I am trying to update a Django model with dynamic data, like so: MyModel.objects.filter(pk=id).update(key=None) key here is a string variable, based on the key from some array. However when I try to run this, I get this: django.core.exceptions.FieldDoesNotExist: MyModel has no field named 'key' Which makes sense, it is looking for a field key. How do I tell it I want to use the actual value of the string variable for the key, rather than key? -
How should i structure my Django apps for a learning management system
I'm creating a learning management system in django(python). What's the best way for me to structure my apps and how many apps should I have?? I haven't started writing codes yet and i don't need anyone to tell me to go to my settings folder. All I need is from creating a project, how many apps do I need to create and what would be their function I just want to design a mockup where I understand what every aspect of the website. I would also like my apps to be structured in a way that I can reuse them. All opinions matter. -
Django Custom Queryset Using Listview if Parameters Exist in URL
I have a listview for my blog: #views.py class BlogListView(ListView): model = Blog template_name = 'blog/index.html' context_object_name = 'blogs' ordering = ['-date_posted'] paginate_by = 5 #urls.py path('', BlogListView.as_view(), name='blog-index'), In my model I have different type of blogs, such as video blog or text blog. my model is like this: class Blog(models.Model): TYPE = ( ('Video', 'Video'), ('Text', 'Text'), ) type = models.CharField(max_length=10, choices=TYPE, default='Text') Now I want to use request.GET.get('type') to query different types. For example if I go to the url, 127.0.0.1:8000/?type=video I want only blog that are the type video to show. Is it possible to do this with only this listview, or do I have to create others. I need help to make this feature. -
Django Timezone Middleware Problems
I am trying to work with the Django Timezone Middleware which I took from the offical documentation, but it doesn't seem to work. I have a middleware.py file like this: import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') print('DJANGO TIMEZONE', tzname) if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) Where I output the "tzname" to the console, it is set to None which must be the problem, but why isn't it set? My settings file has the following: USE_TZ = True TIME_ZONE = "UTC" MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myproject.middleware.TimezoneMiddleware', ] My template looks like this: {% load tz %} {% get_current_timezone as TIME_ZONE %} {{ TIME_ZONE }} {% localtime on %} <p>{{ room.open_date }}</p> {% endlocaltime %} The result is that {{ room.open_date }} will show in UTC. {{ TIME_ZONE }} displays 'UTC'. I have tried without the TIME_ZONE setting in settings. I believe I have implemented it according to the documentation, but am obviously missing something. My Django version is Django version 3.2.5. Please can someone help. My goal is to display the dates in the timezone that the browser has. -
Attribute Error When Clicking Model in Admin Section of Django
I'm using Django and I'm getting the error AttributeError at /admin/network/post/ 'Post' object has no attribute 'user' The strange thing is this error happens when I'm looking at the admin section, and clicking 'Posts.' I only have models for users and posts. Not sure how to fix this error because so far I've never gotten an error like this when clicking it in the admin section of the site: http://127.0.0.1:8000/admin/ I think the issue is in my model because the view for creating a post works totally fine. models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username class Follow(models.Model): target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') views.py def make_post(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "network/make_post.html", form_for_post) else: form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] new_post = Post.objects.create( text=text, username=request.user, ) return render(request, "network/make_post.html", { "new_post": new_post, }) -
how to show two models data in one template - django
I need to get two models data in one template. If I loop without union this two models in one tuple or list, I get too much looped info as you know, so I need your help there. This is what I tried, but it did not work... @login_required def my_hotels(request): hotels_info = AddHotelStep1.objects.all() hotels_info_2 = AddHotelStep2.objects.all() info = dict() info['hotels_info'] = hotels_info info['hotels_info_2'] = hotels_info_2 context = {'info':info,} return render(request, 'myhotels.html', context) This is my template: {% for hotel in info %} {% if user.is_authenticated and hotel.customer == user %} {{hotel.hotel_name}} {% with ''|center:hotel.star as range %} {% for i in range %} <span class="fa fa-star checked"></span> {% endfor %} {% endwith %} {{hotel.hotel_type}} {{hotel.short_description}} {% endif %} {% endfor %} This is my models: class AddHotelStep1(models.Model): customer = models.ForeignKey(Account, on_delete=models.CASCADE) hotel_name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/default.jpg", blank=True) class AddHotelStep2(models.Model): hotel_name_2 = models.ForeignKey(AddHotelStep1, on_delete=models.CASCADE) HOTEL_TYPE = ( ('Single', 'Single'), ('Double', 'Double'), ) hotel_type = models.TextField(max_length=10, choices=HOTEL_TYPE) I would get any advice to solve it. -
How to create models dropdown menu in djngo
i created two model name categories and subcategories by which if i create a category name merch so under that i can create sub categories name t shirt, hoddies, shirt so i linked categories with foreign key in subcategories so i want to render a dropdown menu in which on top categories will show up and under that all the sub categories related to categories but i am unable to achieve that i tried this my models.py class Categories(models.Model): name = models.CharField(max_length=100, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() return render (request, 'home.html', {'category_list': category_list }) and my html <ul class="navbar-nav m-auto"> {% for category in category_list %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle category" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ category.name }} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item text-white" href="#"></a></li> </ul> </li> {% endfor %} my urls.py path('',home.as_view(),name='home' ), what it does it load the categories name but unable to subcategories name under the dropdown menu here is the pic for you better understanding -
PostgreSQL models efficiency to store asset prices - Django
I want to store prices of assets in different currencies. I'm wondering which one of these 2 way below (using Django models) is the most efficient for my PostgreSQL database. 1st way: class CurrentPrice(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... class AthChangePercentage(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... class MarketCap(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... Here you can see I use table rows to add different currencies price. 2nd way: class Currency(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=100) class CurrentPrice(models.Model): currency = models.ForeignKey(Currency) price = models.FloatField() #... class AthChangePercentage(models.Model): currency = models.ForeignKey(Currency) ath_change_percentage = models.FloatField() #... class MarketCap(models.Model): currency = models.ForeignKey(Currency) market_cap = models.FloatField() #... I cropped the classes because in reality I have around 50 different currencies to handle. Of course there will be multiple assets too. Which one do you think is the fastest, efficient and less power consuming? Or is there any better way to do this ? -
Django Field 'id' expected a number but got '.....'. getting this error if forward slash missing from end of url
I am facing this error after added delete function in my views. if forward slash missing from end of any url like this "http://127.0.0.1:8000/blog" then I am getting this error Field 'id' expected a number but got 'blog'. If I type http://127.0.0.1:8000/blog/ then it taking to me blog page. For example I am trying to access my admin page like this http://127.0.0.1:8000/admin then it will give me same error Field 'id' expected a number but got 'admin'. This error happening for my all url. After adding this delete function in my views I am getting this error: def DeleteNotificaton(request,noti_id): user= request.user if user.is_authenticated: author = Blog.objects.filter(author=user) if not author: Notifications.objects.filter(id=noti_id,receiver=user).delete() Notifications.objects.filter(id=noti_id,sender=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify') if author: Notifications.objects.filter(id=noti_id,receiver=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify_author') return redirect('http://127.0.0.1:8000/admin/') how to solve this any idea?? my urls.py from django.urls import path,include from notifications import views from .views import * app_name = 'notifications' urlpatterns = [ path('notifications/',views.ShowNOtifications,name='notify'), path('author-notifications/',views.ShowAuthorNOtifications,name='notify_author'), path('<noti_id>',views.DeleteNotificaton, name='delete-noti'), ] -
How to display html table using django python pyspark
I am very beginner in all of them. So my HTML code looks like this --> <table id="myTable" class="table table-dark table-striped"> {% for item in tnames %} <tr> <th scope="col">{{ item }}</th> </tr> {% endfor %} {% for values in datas %} <tr> <td scope="row"> {{ values }}</td> </tr> {% endfor %} </table> code for django to get lists for html is like that --> tnames = [] for n in df.columns: tnames.append(n) datas=[] for i in df.collect(): datas.append(tuple(i)) and output is like this How to fix it ? Yes I am doing something wrong. So what is right way to display them correctly. Thank you in advance. -
Defining an arbitrary function in Django class-based view and calling it from the frontend
I am making a React-Django web application, during which I had to call a function at the backend and get the returned value (namely, compute the average grade of all students in the database). However when I tried to define my own function in Django views.py, I ran into a problem. class TodoView(viewsets.ModelViewSet): model = Todo def head(self, request, path, *args, **kwargs): all_grades = self.get_queryset().values_list('grade', flat=True) all_units = self.get_queryset().values_list('units', flat=True) result = sum(all_grades) / sum(all_units) response = HttpResponse( headers={'gpa': str(result)}, ) return response This is my code on the frontend: axios .head("/api/todos") .then(res => { console.log(res.headers); }) .catch((err) => console.log(err)); I believe it is not a problem in the urls.py because in other parts of my code, axios.get on the same model works fine but not axios.head. Also I believe it may not be a problem in the "head" function since removing the def head function in views.py gives the same error. If there is any other way to define and call an arbitrary function from a class-based view on the Django backend (without using HEAD, for example), I would be thrilled to learn it. After days of search I didn't find anything that looks workable. Or would switching to … -
Django keeps redirecting to https in local environment
I'm trying to run my project in django in local without using https. I have added the following to the settings I'm using: SECURE_SSL_REDIRECT = False DEFAULT_HTTP_PROTOCOL = 'http' SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') (commented) I'm running the serve with the following command: python3 manage.py 0.0.0.0:8000. If I browse to 0.0.0.0:8000, it works (it uses http). Nonetheless, if I use localhost:8000 then it always redirects to https and the following error appears: I do not know if it helps, but I'm using django 1.11 version inside a docker container. -
Celery Django runing periodic tasks after previus was done. [django-celery-beat]
I want to use django-celery-beat library to make some changes in my database periodically. I set task to run each 10 minutes. Everything working fine till my task takes less than 10 minutes, if it lasts longer next tasks starts while first one is doing calculations and it couses an error. my tasks loks like that: from celery import shared_task from .utils.database_blockchain import BlockchainVerify @shared_task() def run_function(): build_block = BlockchainVerify() return "Database updated" is there a way to avoid starting the same task if previous wasn't done ? -
DateField bigger than most recent record
I have this DB table: models.py class Payment(models.Model): date = models.DateField(blank=False,verbose_name="Data") description = models.CharField(max_length = 300,blank=False,verbose_name="Descrizione") course_subscription = models.ForeignKey(CourseSubscription,null=True,on_delete=models.CASCADE,verbose_name="Sottoscrizione Corso") payment_method = models.CharField(max_length = 4,blank=False,verbose_name="Modalità di pagamento",choices=PAYMENTS) value = models.DecimalField(max_digits=7, decimal_places=2,blank=False,verbose_name="Importo") receipt= models.FileField(blank=False,verbose_name="Ricevuta") How can I add a constraint in model or form which allows the insertion of new payments only if the date is more recent than the most recent record? In other words, I want a new payment has always a more recent date than the last inserted one. I tried with: forms.py class AddPaymentForm(forms.Form): def __init__(self, max_value, min_date, *args, **kwargs): super(AddPaymentForm, self).__init__(*args, **kwargs) self.fields['value'] = forms.DecimalField( max_digits=7, decimal_places=2, required=True, label="Importo", min_value=0.01, max_value=max_value, help_text= f"Valore Massimo: {max_value}", widget = forms.NumberInput() ) self.fields['date'] = forms.DateField( required=True, label="Data", min_value=min_date, help_text= f"Data minima: {min_date}", widget=forms.TextInput( attrs={'type': 'date'} ) ) .... and views.py ... payments = Payment.objects.all().order_by('-date') initial = { 'date': datetime.date.today().strftime("%Y-%m-%d"), 'member':member, 'description': description, 'value': 1.00, 'subscription_type' :subscription_type, 'subscription_id' :subscription_id } if len(payments)>0 : min_date = payments[0].date.strftime("%Y-%m-%d") initial["date"] = min_date else: min_date = None form = AddPaymentForm( initial= initial, max_value = remaining_fee, min_date = min_date ) ... This way works with 'value' field, but forms.DateField doesn't have "min_value" attribute. -
Is there a reason I am not getting any Django output from gunicorn in Heroku?
I have a django project deployed to Heroku in a worker using gunicorn. I have included all flags/configurations that I am using below. The issue is that the logging in Heroku does not display any output from Django, and my project is running into some issues in the backend. I can access the logs, but there are no logs, just the message from gunicorn initialization. Procfile: release: python manage.py migrate backend web: bin/boot worker: gunicorn backend.wsgi:application -b 0.0.0.0:$PORT -c /app/gunicorn.conf.py --log-file - gunicorn.conf.py # gunicorn.conf.py # Non logging stuff workers = 3 # Whether to send Django output to the error log capture_output = True # How verbose the Gunicorn error logs should be loglevel = "debug" -
Raw SQL in order by in django model query
I've a simple query like this (I want 1 BHK to come first, then 2BHK, then anything else) select * from service_options order by case space when '1BHK' then 0 when '2BHK' then 1 else 2 end, space In Django, how to do it? I've a model named ServiceOption I tried this but no luck. ServiceOption.objects.order_by(RawSQL("case space when '1BHK' then 0 when '2BHK' then 1 else 2 end,space"), ()).all() I don't want to execute raw query with something like ServiceOption.objects.raw("raw query here") Any input will be appreciated. Thank you in advance. -
related name of a many to many relationship django
I have a model of user like this: class User(AbstractUser): following = models.ManyToManyField('self', related_name="followed") I'm trying to make a many to many relationship from a user to a user. I eed to access who the user is following, and who is following the user. the first requirement works nicely, but when I try to see who is following the user, with user.followed.all(), I see an error, AttributeError at /user/1: 'User' object has no attribute 'followed' How would I fulfill my second requirement? TIA, Ishaan -
I keep getting an "ModuleNotFoundError" with Django in Python
I know, this is a common problem, but no solution has yet worked for me. I have set up Django with an Virtual-Environment in Python (OS is Windows) but everytime I try to run django-admin startproject mysite I get an error Traceback (most recent call last): File "C:\Users\Max\Desktop\django_app\venv\Scripts\django-admin.py", line 5, in <module> from django.core import management ModuleNotFoundError: No module named 'django' Does anybody know a solution for this. Thanks in advance. -
How to get count of objects in database for a particular user
Right now my dashboard looks like this: The white box should show the number of complaints that are registered by the user. But right now it shows the number of complaints registered by all users. What should I do to only get the count for a particular user? views.py: def dashboard(request): count = Complaint.objects.all().count() context = {'count':count} return render(request, 'dashboard.html', context) template: <p>{{count}}</p> What should I do?? -
User should not be able to pay until he selects an address
I am Building an eccomerce webiste. So, the issue is that i wanna allow a user to pay only after he selects an address. I have tried required field of html but it seems like it didn't worked. When a user selects an address only then he will be able to pay. But currently when i click on pay button it directly redirects me to payment. This is buy now page {% extends 'app/base.html' %} {% load static %} {% block title %}Buy Now{% endblock title %} {% block main-content %} {% load humanize %} <div class="container"> <div class="row mt-5"> <div class="col-sm-4 offset-sm-1"> <h4>Select Shipping Address :</h4> <hr> <form action="/payment_done/"> {% if address %} {% for add in address %} <div class="card"> <div class="card-body"> <h5>{{add.name}}</h5> <p>{{add.locality}}, {{add.city}}, {{add.state}} - {{add.zipcode}}.</p> </div> </div> <div class="form-check mt-2 mb-5"> <input class="form-check-input" type="radio" name="custid" id="custadd{{forloop.counter}}" value="{{add.id}}" required> <label class="form-check-label fw-bold" for="custadd{{forloop.counter}}"> Address: {{forloop.counter}} </label> </div> {% endfor %} <!-- Paypal button --> <div class="text-end"> <div id="paypal-button-container"></div> </div> {% else %} <p class='mx-2 fw-bold'>Please add an <a href="/profile/">shipping address</a></p> {% endif %} </form> </div> </div> </div> {% endblock main-content %} {% block payment-gateway %} <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // … -
No 'Access-Control-Allow-Origin' error - font-awesome
Within the past couple of weeks, I've started to get an error that I haven't seen before. My project has not materially changed and so I believe that this may be a change that font-awesome has implemented. Access to CSS stylesheet at 'https://use.fontawesome.com/releases/v5.3.1/css/all.css' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Any thoughts on which CORS settings in Django I have to change in order to prevent this from happening? When I hit Ctrl+F5 to refresh the page, the error goes away. When I visit another page in my project, I get the error again. Thanks! -
Use PixiJS with Django
I'm new to django and didn't have the time to fully understand it so I'm hoping someone can help me fix this. I am using this page: Generative UI - Orb Animation [pixi.js] + Frosty Elements ❄️ with the same Javascript file in it. I can use it properly without django by typing <script type="module" src="script.js"></script> in my html file but when it comes to django, I don't actually know what to do. I tried to put it in static folder and load it. It works, but there is no animation! I guess it has something to do with the applications in the script, but again I'm a newbie so I don't know what to do. Any suggestions? -
Django: Return all nested Sub Model from a given Model (which isn't directly linked to given model)
I have my models.py as shown below: from django.db import models # Create your models here. class Category(models.Model): categoryType = models.CharField(max_length=100,blank = False, unique = True, null = False) def __str__(self): return self.categoryType class SubCategory(models.Model): subcategoryType = models.CharField(max_length=100) categoryType = models.ForeignKey(Category,on_delete=models.CASCADE, null = True, related_name='category_type') def __str__(self): return f'{self.categoryType} :: {self.subcategoryType}' class Product(models.Model): productName = models.CharField(max_length=50,blank = False, null = False) subCategoryType = models.ForeignKey(SubCategory,on_delete=models.SET_NULL, null=True,related_name='product_subcategories') #categoryType = models.ForeignKey(Category,on_delete=models.SET_NULL, null=True,related_name='product_categories') def __str__(self): return f'{self.productName} : {self.subcategoryType}' I have created a serializer to get all products within a given category as shown below: class ProductSerializerSpecific(serializers.ModelSerializer): class Meta: model = Product fields = ('id','productName') class SubCategoryProductsSpecific(serializers.ModelSerializer): products = ProductSerializerSpecific(source='product_subcategories', many=True) class Meta: model = SubCategory fields = ['products'] class CategoryProducts(serializers.ModelSerializer): products = SubCategoryProductsSpecific(source='category_type', many=True) class Meta: model = Category fields = ('id','products') My View goes like this: class ListAllCategoryProducts(viewsets.ReadOnlyModelViewSet): queryset = Category.objects.all() serializer_class = CategoryProducts And finally I registered by route like this: router.register(r"category_products", views.ListAllCategoryProducts, basename="categories_products") When I do a GET request to get all products with a given ID as shown below: GET http://localhost:8000/category_products/1 HTTP/1.1 The output comes as shown below: { "id": 1, "products": [ { "products": [] }, { "products": [] }, { "products": [] }, { "products": [ { … -
How to save MultipointField in django rest framework using createAPI View
Im using django Rest framework to make an api at some point I would like to save a multipointfield , Im expecting the frontend to send an array of point but that format is not supported by django-restframework how am I supposed to do it?