Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django object matching query: i am getting different object id in featured page and not getting the same object in index on click
Template Featured: <div class="container"> <div class="row"> <div class="col-lg-6 mb-5 animate"> <a href="{{ product_object1.image.url }}" class="image-popup"><img src="{{ product_object1.image.url }}" class="img-fluid" alt="Template"></a> </div> <div class="col-lg-6 product-details pl-md-5 animate"> <h3>{{ product_object1.name }}</h3> <div class="rating d-flex"> <p class="text-left mr-4"> <a href="#" class="mr-2">5.0</a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> <p class="text-left mr-4"> <a href="#" class="mr-2" style="color: #000;">100 <span style="color: #bbb;">Rating</span></a> </p> <p class="text-left"> <a href="#" class="mr-2" style="color: #000;">500 <span style="color: #bbb;">Sold</span></a> </p> </div> <span class="status">{{ product_object1.discounted_price }}%</span> <div class="overlay"></div> <p class="price">Price<span class="mr-2 price-dc">(${{ product_object1.price }}/Lb)</span><span class="price-sale">${{ product_object1.afterdiscount }}</span></p> <p>A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Text should turn around and return to its own, safe country. But nothing the copy said could convince her and so it didn’t take long until. </p> <div class="row mt-4"> <div class="col-md-6"> <div class="form-group d-flex"> <div class="select-wrap"> <div class="icon"><span class="ion-ios-arrow-down"></span></div> <select name="" id="" class="form-control"> <option value="">Small</option> <option value="">Medium</option> <option value="">Large</option> <option value="">Extra Large</option> </select> </div> </div> </div> <div class="w-100"></div> <div class="input-group col-md-6 d-flex mb-3"> <span class="input-group-btn mr-2"> <button type="button" class="quantity-left-minus btn" data-type="minus" data-field=""> <i class="ion-ios-remove"></i> </button> … -
Multiple images in a single detailed view
I'm working with a store website in Django, and I'd like to have a product-detail view to show (obviously) the product card with all of its images. The problem is that detail views only focus on one model, and here's what I have: class Bag(models.Model): title = models.CharField(max_length=30) description = models.TextField() previous_price = models.FloatField(null=True, blank=True) actual_price = models.FloatField() slug = models.SlugField() main_image = models.ImageField(upload_to='product_image', blank=True) def get_absolute_url(self): return reverse( 'product_page', kwargs={ 'slug' : self.slug } ) def __str__(self): return self.title class MoreImage(models.Model): Bag = models.ForeignKey(Bag, related_name='image', on_delete=models.CASCADE) image = models.ImageField(upload_to='product_image', blank=True) Any idea on how I can accomplish this? Thanks in advance! -
How to count the number of objects in a given foreign key in django inside the html template?
I have 3 models which are. class Category(models.Model): name = models.CharField(max_length=100) class Subcategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Item(models.Model): name = models.CharField(max_length=100) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE) In my Html template I want to access the number of items in each given category. I have tried using the _set method but it doesn't work on category.subcategory_set.course_set.count. How can I access the number of courses under each given category. I didn't include category as a foreign key in my Items models as it can lead to assignment of wrong category-subcategory pair for an item. -
Aggregation in Django viewset - Django Rest Framework:
I have a table with the following attribute- created_at = TimestampField(auto_now_add=True,auto_now_update=False, editable=False) updated_at = TimestampField(null=True,auto_now_update=True, editable=False) And one service is running there, first comes into the system and we capture created_at timestamp. And after some time on service completion, the script updates the table attributes and we capture updated_at timestamp. So now I want to find the AVERAGE of the service deployment time i.e. addition of (updated_at-created_at) divide by total services or we can say total rows in the table. So that query needs to be implemented in Django ORM and have to serialize to the endpoint. So that data can be fetched in frontend. Could you guys help me out here that would be highly appreciable? Thanks in advance! -
How to get IMSI number via link to my django webapp?
I have a web application accessible via a mobile browser. I need to detect a mobile device IMSI whenever a user clicks on the link in my app page accessible via web browser. The question is how to get unique device id/sim id via web browser for a specific mobile device. Focus of most of the ideas is, what is the kind of access a browser has over the phone and How can control it using python? Via webpage scripts we can store some data locally at client machine and retrieve it later. Is there a way to get a hook to webap app from the webpage and get the id details via scripts in my page? **Let me know if there is any other option without asking user to installing a local app or browser plugin on the device?**olm -
django forms and models by muxamedovr
I have such a situation I have 3 models Profil, Stimul_slov, Otvet, the participant must go to his login and password to the main part of the site there he must answer some questions questions are stored on the model Stimul_slov answers must be saved to the model Otvet I am new to my knowledge solve this problem please tell me how to solve this issue how can I make a form for this task for earlier thanks and forgive me if my level is English models.py from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=100, blank=True) age = models.DateField(blank=True) specialite = models.CharField(max_length=100,blank=True) language = models.CharField(max_length=100,blank=True) def __str__(self): return self.fullname class Stimul_slov(models.Model): stimulus = models.CharField(max_length=200, blank=True) def __str__(self): return "%s" % ( self.stimulus) class Otvet(models.Model): answer = models.CharField(max_length=200, blank=True) user = models.ForeignKey(Profil, on_delete=models.CASCADE) stimul = models.ForeignKey(Stimul_slov, on_delete=models.CASCADE) def __str__(self): return "%s: %s ----> %s" % (self.user ,self.stimul, self.answer) form.py from django import forms from .models import Profil, Otvet from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm 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 … -
Geoalchemy2 get mvt tiles from postgis database
I am trying to fetch MVT/geojson vector tiles directly from POSTGIS server using SQLAlchemy ORM but i am unable to find any examples. All the examples shown do not use ORM but instead use raw queries -
Django How to switch between Development, Stageing and Production Environment
I am new to Django. I used python manage.py runserver to run the server and I got: * Serving Flask app "application" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off The server is running production environment with DEBUG OFF. I want to run it in development environment with DEBUG ON. How can I change the running environment? My config file: class Config(object): DEBUG = True TESTING = False CSRF_ENABLED = True SECRET_KEY = 'this-really-needs-to-be-changed' SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True I am wondering how can I switch between defferent environment. -
Obtain the date from datepicker and send it to my backend - Django
I'm using the datepicker from jquery-ui and I need to pass the date to my python backend (I'm working with Django). Obtain the date in my JS it's not a problem, user_date = $("#datepicker").datepicker('getDate'); Then I have a function that pass this result using ajax to my python backend. function getUserDate(user_date){ var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: '/../../../getUserData/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'Date':user_date }, dataType: "json", cache: true, success: function(response) { var data = response.Data; } }); } But now, when I want to work with it in my python function, I don't know how to do it. I'm doing the following, try1 = request.POST['Date'] print('>>>>>>>>>>>> TRY1 >>>', type(try1)) But this is a string. My question is, how can I receive it as a dictionary, json, timestamp or something similar? That it's more manageable. Thank you very much! -
How to create a file using Celery/Django
I’ve set up a Django project with Celery and Redis(Broker, Backend). I need to bind file generation to the view, the task is marked as successful but file is not created. What am I doing wrong? from celery import shared_task @shared_task def create_task(task_type): f = open("example_file.txt", "a") f.write("Now the file has more content!") f.close() return True -
Django Rest Framework get params inside has_permission
I'm filtering real estates queryset dependent on user status and district (last one with GET param). In views.py I have this: class RealEstateView(APIView): serializer_class = RealEstateSerializer permission_classes = [RealEstatePermission] def get(self, request): district = self.request.query_params.get('pk') if district: serializer = RealEstateSerializer(RealEstate.objects.filter(owner_id=district), many=True) else: serializer = RealEstateSerializer(RealEstate.objects.all(), many=True) return Response(serializer.data) If user is superuser, he have access to all information. If user in not superuser, he can get access only to real estates from district which he is responsible. If user is responsible to district with id=1, but sends a get param with id=2, I need to raise an exception. But the problem is I don't know how to get access to get parameter in has_permission function. Doing this inside views get function seems not good idea. I already tried request.resolver_match.kwargs.get('id') and view.kwargs.get('id'), both of them are empty. in permissions.py: class RealEstatePermission(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: if request.user.is_staff: return True ## HERE I need something like request.user.district.id == kwargs('id') if request.user.role == 'district_municipality': return True Thank you for your help. -
How to join 2 attributes to create a name in Django model instance?
I have a model: class Subject(models.Model): level = models.CharField(choices=LEVEL_CHOICES, max_length=2) subject_name = models.CharField(max_length=50) teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE) total_seats = models.IntegerField() subject_details = models.CharField(max_length=100) subject_img = models.ImageField() I want to display each instance as level and then subject name. For example, if the instance has a level 'Advanced' and subject_name as 'Physics', I want the instance to be displayed as 'Advanced Physics'. I have tried using str method but it shows subject_name is not defined: def __str__(self): return self.level+ ''+ subject_name -
Pycharm - Django
Tengo el siguiente el problema pycharm no me detecta etiqueta django en los template, si alguien podria ayudarme gracias. -
How to check if a field/attribute is null and blank in Django?
My payment attribute has a ForeignKey relation. In my accounts.html, I want to show users if they have paid for their orders. So I was trying it like this: {% if order.payment is null or blank %} <td> x</td> {% else %} <td> Yes</td> {% endif %} But it didn't work out. What is the proper code for this? My orders.models.py: class Order(models.Model): payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank= True, null=True) My accounts.html: {% for order in user.order_set.all %} <tbody> <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ order.order_id }}</td> {% if order.payment is null or blank %} <td> x</td> {% else %} <td> Yes</td> {% endif %} <td>No</td> </tr> </tbody> {% endfor %} -
How to change navbar contents of the User Change page in Django admin?
I'm working on Django.And I wanted to change the navbar content in the User Change Page in the Django admin as marked with red color in the pic : And my admin file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) It is same as the default Django user model name so only I want to change it. So it can be changed or is it permanent?? Thanks in advance!! -
Django not taking timezone from Postgres
I have a postgres database with a local timezone (America/Bogota), so my timestamp column looks like this "2020-04-24 07:35:11.129-05" but when I call the data from Django it changes the timezone to 00 but keeps the same date-hour, (2020-04-24T07:35:11.129000+00:00) I'have tried changing the TIME_ZONE in the Django settings to America/Bogota but then I got no results, any ideas on how can a i fix this? This is the settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True views.py from datetime import datetime, timedelta from django.core.serializers import serialize def data(request): time = datetime.now() - timedelta(hours=8) hour = serialize('geojson',datatime.objects.filter(tiempo__gte=time)[0:100]) return HttpResponse(hour, content_type='json') -
how do i test django view when i have used referview?
def searchResult(request): check() query = request.GET.get('q') print(query) if request.GET.get('q') == '': messages.error(request, "Please type something to search") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: object_lists = Product.objects.filter(category=query) context = { 'object':object_lists } return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) how do I test the URL when testing this view. I have been using the following to test but : url = reverse("search") resp = self.client.get(url,data={'q':'Games'}) self.assertEqual(resp.status_code, 200) I am getting this error. ValueError: The view website.views.searchResult didn't return an HttpResponse object. It returned None instead. how do I do a proper test and not get this error? -
django channels custom token authenticated Websocket keeps disconnecting ERR_CONNECTION_RESET
i using react as my front end and django as my backend , as such , it requires me to use token based authentication with django channels. The method i am employing is by sending the authentication token as a cookie header. The methodology was taken from this git hub post here So far , i have gotten most of the working parts together , however i don't seem to be able to persist the connection , it will always return an error in my console: ERR_CONNECTION_RESET Here is my code: FRONTEND: Websocket.js class WebSocketService{ static instance = null; callbacks = {}; static getInstance(){ if (!WebSocketService.instance){ WebSocketService.instance = new WebSocketService(); } return WebSocketService.instance; } constructor(){ this.socketRef = null; } connect(token){ var loc = window.location var wsStart = 'ws://' if (loc.protocol === 'https'){ wsStart = 'wss://' } const path = wsStart + 'localhost:8000'+ loc.pathname // console.log(path) // console.log(path + "?token=" + token) document.cookie = 'authorization=' + token + ';' console.log(document.cookie) this.socketRef = new WebSocket(path) this.socketRef.onmessage = e => { console.log('in on message') this.socketNewMessage(e.data); }; this.socketRef.onopen = () => { console.log(this.props.token) console.log("WebSocket open"); }; this.socketRef.onerror = e => { console.log('error happ') console.log(e.message); }; this.socketRef.onclose = () => { console.log("WebSocket closed, restarting.."); this.connect(token); … -
Problem with linking ID of a task in DJANGO
I am working on to do app, and I cannot solve this problem. The problem is linking the tasks with ID or PK... i am getting this error: NoReverseMatch at / Reverse for 'update_task' with arguments '(1,)' not found. 1 pattern(s) tried: ['update_task/ and it is pointing that error is here (in template): <a href="{% url 'update_task' task.id %}">Update</a> views.py def updateTask(request, pk): task = Task.objects.get(id=pk) form =TaskForm(instance=task) context = {'form': form} return render(request, 'tasks/update_task.html',context) template <h3>To Do</h3> <form action='/' method="POST"> {% csrf_token %} {{form.title}} <input type="submit" name="Create Task"> </form> {% for task in tasks %} <div class=""> <a href="{% url 'update_task' task.id %}">Update</a> <p>{{task}}</p> </div> {% endfor %} URLS.PY from django.urls import path from tasks import views urlpatterns = [ path('', views.index, name='list'), path('update_task/<str:pk/', views.updateTask, name='update_task'), ] -
How to set Environment Varibales EC2 Ubuntu for Django App
I am EC2 to host a django app and now want the Database settings not to hard coded in the settings file rather set them as environment variables. I changed the /etc/environment and added the variables as .... DB_HOST="HOST VALUE" DB_NAME="DB NAME" .... The app is not reading them and rather acts like the variables are not present.I thought it was only problem with host and its user name and password so i put them directly in settings and left the name of db in the environment variables only. But It wasn't reading the environment variables at all and error came up: No Database Selected I want to set the database variables in such a way that i can use them in settings .... 'HOST':os.environ.get('DB_HOST'), .... and i get the value mentioned in the environments for DB_HOST. -
How to change header/page title of User change page in Django admin
I'm working on Django.And I wanted to change the header in the User change page in the Django admin as marked with red color in the pic : And my admin.py file is this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So what should be done to change this?? Thanks in advance!! -
How to solve IntegrityError (FOREIGN KEY constraint failed) in django?
I have this model system. The project contains entries. But when I try to delete Project I am getting this error. I am getting IntegrityError (FOREIGN KEY constraint failed) on deleting a project. How can I solve this error? Here are my foreign key relations from models.py class Project(models.Model): project_author = models.ForeignKey(User, on_delete=models.CASCADE) project_entry = models.ForeignKey(Project, on_delete=models.CASCADE) class Entry(models.Model): entry_author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Project, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, blank=True,related_name="replies", on_delete=models.CASCADE) class EntryComment(models.Model): post = models.ForeignKey(Entry, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) entryreply = models.ForeignKey('EntryComment', null=True, blank=True,related_name="entryreplies", on_delete=models.CASCADE) Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/lift/delete/ Traceback (most recent call last): File "D:\Projects\django_project\django_venv\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\contrib\auth\mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\views\generic\base.py", line 97, in … -
variable DJANGO_CONFIGURATION is undefined - Django + virtual env + apache
I try to deploy my Django App in my apache server. Despite all the tutorials and threads (including stackoverflow) I read, I'm still not able to find the solution. Just for the context, I made a Django App locally using virtual env and Django 3+. My next step is to put it in the Apache server. So after pulling from my github account, I have set up a virtual environment on the server using virtualenv env Then I run the following command line to install the requirements pip install -r requirements.txt So far so good. Basically, after configurating the virtual host, I have the following error : **django.core.exceptions.ImproperlyConfigured: Configuration cannot be imported, environment variable DJANGO_CONFIGURATION is undefined.** I precise (it will be included below) that everything is installed correctly and the environment variable has been set. Here my logs project_error.log : [Fri Apr 24 17:54:52.416771 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] mod_wsgi (pid=30069): Target WSGI script '/var/www/admin-dashboard/project/wsgi.py' cannot be loaded as Python module. [Fri Apr 24 17:54:52.416903 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] mod_wsgi (pid=30069): Exception occurred processing WSGI script '/var/www/admin-dashboard/project/wsgi.py'. [Fri Apr 24 17:54:52.417460 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] Traceback (most recent call last): [Fri Apr 24 17:54:52.417527 … -
How to make the django redirects a user to the page I need?
How to make the django redirects a user to the page I need? I have a web app. For example a user is on a page with an address local:8000/detail-order/18. This page is detail info of the order 18. On this page is link to edit this order. When a user clicks this link a order editing form shows up. When a user writes in this form and click the submit button, he has an error. I whould like that a user goes back to local:8000/detail-order/18. NoReverseMatch at /update-orders/18 Reverse for 'detail_order' with no arguments not found. 1 pattern(s) tried: ['detail\-order/(?P[0-9]+)$'] Request Method: POST Request URL: http://192.168.0.249:8000/update-orders/18 Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail_order' with no arguments not found. 1 pattern(s) tried: ['detail\-order/(?P[0-9]+)$'] Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 urls.py from django.contrib import admin from django.urls import path, include from .views import * from print import views urlpatterns = [ path('', views.home_page, name='index'), path('orders', views.OrderCreateView.as_view(), name='orders'), path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'), path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'), ] views.py class UpdateOrderView(CustomSuccessMessageMixin, UpdateView): model = Order template_name = 'orders.html' form_class = OrderForm success_url = reverse_lazy('detail_order')# HERE success_msg = 'Изменения сохранены' def get_context_data(self, **kwargs): kwargs['update'] = True return super().get_context_data(**kwargs) -
Error: The SECRET_KEY setting must not be empty - Django webdev
I developed a simpel web application in django and everything is working perfectly. I did push the code already to Heroku and no errors appeared. Now i'm trying to set my secret key and other vital settings to environment variables. I'm on a Windows and set everything correctly in the control panel. when i test the secret key with: SECRET_KEY = os.environ.get('SECRET_KEY_THIJS') print(SECRET_KEY) It prints out the secret key correctly. When i try to push the code to Heroku via Git is says: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Please help me out! *Note: excuse me for me English and i am a hobby programmer and did not have any education related to it (learned everything via Google and Youtube) :) Sincerely, Rick