Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Wizard Skip Multiple Steps with Conditional Logic
Is there some way to skip multiple steps in Django's Form Wizard (i.e. SessionWizardView)? I know it is possible to use condition_dict to produce the following form display logic: Page 1 -> Page 3 #urls.py path('main/', MyWizard.as_view(set_of_forms, condition_dict={'1': view_condition} )) What I would like to do is the following: Page 1 --> Page 4 Presumably, adding a condition_dict based on the content of Page 1 should work to skip Page 3, but it doesn't work. For example: #urls.py path('main/', MyWizard.as_view(set_of_forms, condition_dict={'1': view_condition, '2': view_condition2,} )) I am truly stumped on how to crack this nut. Any guidance that you can provide would be GREATLY appreciated. -
DRF API limit&offset list index out of range
I'm writing a simple API to get data from models and with LimitOffsetPagination the API show count the total number of record is 7127 But when I try to move to next page, it will show list index out of range error here is my Pagination setting: class LimitOffsetPagination(LimitOffsetPagination): default_limit = 10 default_offset = 10 offset_query_param = "offset" limit_query_param = "limit" it run correctly when limit=10&offset=60, however when click on next (limit=10&offset=70) it will show the out of range error. Whats going on? -
Not able to load multiple blocks in base template in Django
I am having a problem in my templates. I am trying to add two blocks in the base template, it works when I include them but when I try to extend the base template it won't work and won't even throw an error. -
django save a new instance of object
I am trying to update a user "karma points" whenever a user posts something. For this, i first created a new model called Myuser that allows for points property: class Myuser(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) points=models.IntegerField(default=1) And then in my view.py post_new() function, I tried to update the score: u=User.objects.get(username=request.user.username) u.myuser.points=u.myuser.points+5 u.save() but then i notice that rather than update the points field, it just saves a new instance with the same user id but updated score. I thought .save() is supposed to update exisiting copy. -
Pls help me, File "C:\Python39\lib\os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DJANGO_ENV'
mau ngejalanin program Python Framework django. pas mau runserver app saya terdapat error seperti ini File "C:\Python39\lib\os.py", line 679, in getitem raise KeyError(key) from None KeyError: 'DJANGO_ENV' enter image description here mohon d bantu -
Django 3.1 - "OperationalError: no such table" when using an ORM Class Model before making or applying a migration
The Problem Whenever I create a new model class inside products/models.py (products is the name of my Django app), I cannot reference such model (e.g. Product model) in any method or class before having made and run the migrations. Otherwise, if I reference the new model in the code and then I run any of the following commands/procedures, I receive the OperationalError: no such table error: python manage.py runserver python manage.py makemigrations [appname] python manage.py migrate python manage.py showmigrations Delete all existing migrations and try to regenerate them with python manage.py makemigrations [appname] Delete current db.sqlite3 file; delete all existing migrations and try to regenerate them with python manage.py makemigrations [appname] The error looks like this: ... File "/Users/my_user/Work/django_proj_1/config/urls.py", line 21, in <module> path('', include('products.urls')), ... File "/Users/my_user/Work/django_proj_1/products/urls.py", line 1, in <module> from products.api_views import ProductList3 File "/Users/my_user/Work/django_proj_1/products/api_views.py", line 7, in <module> class ProductList3(ListAPIView): File "/Users/my_user/Work/django_proj_1/products/api_views.py", line 8, in ProductList3 queryset = get_products() File "/Users/my_user/Work/django_proj_1/products/data_layer/product_data_layer.py", line 4, in get_products all_prods = list(Product.objects.values()) ... File "/Users/my_user/.local/share/virtualenvs/django_proj_1-a2O6RBaf/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: products_product ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Real Question This behavior may seem normal, but if you think about it, how would a developer make a release … -
How to filter the objects related to foreign key model in django Views.py
I have models.py as like this: class Subject(models.Model): sub = models.CharField(max_length=200) slug = models.SlugField(unique=True) created_on = models.DateTimeField(auto_now_add=True) class Post(models.Model): sub = models.ForeignKey(Subject, on_delete=models.CASCADE) file_name = models.CharField(max_length=50,blank=True) url = models.CharField(max_length=800, unique=True) urls.py path('view/<subj>/', views.PostDetail, name='post_detail'), views.py def PostDetail(request, subj): content = Post.objects.get(sub=subj) But I'm getting this error when i pass subj as sig from url, invalid literal for int() with base 10: 'sig' How to get all the objects related to the query subj i.e "sub" in Post model? -
how to use Authentication in django with prodection
I am using django JWT for permission and rest_framwork. there is one question. if one user uploads one post and wants to modify/delete post OR wants to change own's profile, definitely user requests restAPI. and in the http(s) request maybe there is some information about user, like "localhost:8000/data/change/userid/" OR exists in post body. point is i think if someone(like hackers) catch others id(or ID number) and pretending them server doesn't know that who is real owner does it? how can i protect or encrpt? -
How to upload file image to server using multipart/form-data [flutter to django server]
I have an api using django python and I am using camera package of flutter to take a picture and I would like to send the file picture to server using api post request, so far I have been trying using dio and http package to send it, but the image file is not recognise in server, here is the code for dio package String fileName = file.path.split('/').last; FormData formData = FormData.fromMap({ "file": await MultipartFile.fromFile(file.path, filename: fileName), }); var response = await dio.post( "http://xxx/xxx/", data: formData); print(response); and here is the code when using http package sending(List<int> myFile){ Map<String, String> headers = { "Content-Type": "multipart/form-data" }; var url = Uri.parse("http:xxx/xxx"); var request = new http.MultipartRequest("POST", url); request.headers.addAll(headers); request.files.add(new http.MultipartFile.fromBytes('file', myFile, contentType: new MediaType('application', 'octet-stream'), filename: name)); var response = await request.send(); final respStr = await response.stream.bytesToString(); print(respStr); } this question is a duplicate from this How to upload images and file to a server in Flutter? is there a way to upload file image to server ? -
No 'Access-Control-Allow-Origin' header is present on the requested resource. - Django & React
I have a ReactJS & Django application. I have a cors issue that I try to solve with Django cors header. However, when I try to add localhost:3000 to my whitelist, I receive a cors error claiming: Access to fetch at 'http://localhost:8000/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. However, when I click on submit, my user still registers successfully. I also notice when I replace CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:8000", ] to CORS_ORIGIN_ALLOW_ALL = True my cors issue is solved. Is there's something that I am doing wrong? I am not trying to exempt my cors. I can pass the CSRFToken successfully from react to Django. Please take a look at the images below to get a better understanding of what I am doing. -
How to obtain a list of scheduled Django-Q tasks from a Django View
All, I've implemented Django-Q and Redis and it works great if I use Django Admin to manage everything. Now I'm ready to reproduce the functionality that Django Admin provides from within my app. I'm able manage a schedule tasks but I can't figure out how to obtain a list of what's been scheduled as well as what has successfully ran and failed. Any thoughts on how I can access a list of what's been scheduled? -
Django Bootstrap Carousel 4 items at a time
Good day SO. I want to use Bootstrap Carousel with Django and display 4 items per carousel-item. (With a maximum of 20 items) First on my views, I have created a view: items = AllItems.objects.all().order_by('-id') context['items'] = items Next, on my template I believe I need to loop through my items like this <div class="carousel-inner"> {% for item in items%} {% if forloop.counter|divisibleby:4 == 1 or forloop.first %} // Add the opening div <div class="carousel-item"> {% endif %} <div class="item">{{item.item_title}}</div> // Add the items {% if forloop.counter|divisibleby:4 == 0 or forloop.last %} // Add the closing div </div> {% endif %} {% endfor %} </div> But reality is different. Hoping to ask your logic on this type of scenario. -
How to insert Django data on Nginx logs?
Im thinking on retrieve Django user data on the user authetication class and pass it to Nginx session variables, then on the nginx logging settings use that data to create a Nginx log that contains the Django user that create such a request. I have found these ideas: Get current request by Django's or Python threading https://gist.github.com/vparitskiy/71bb97b4fd2c3fbd6d6db81546622346 https://nedbatchelder.com/blog/201008/global_django_requests.html Set a session variable: How can I set and get session variable in django? And then log the cookie variable via a Nginx configuration like: https://serverfault.com/questions/223584/how-to-add-recently-set-cookies-to-nginxs-access-log https://serverfault.com/questions/872375/what-is-the-difference-between-http-cookie-and-cookie-name-in-nginx Any better idea?. I'm reinventing the wheel? -
Problem with ImageField in ModelForm Django, request.FILES empty
I have a problem with django working with FormView, and forms.ImageField This is my models.py class Product(models.Model): [...] image = models.ImageField( 'Imagen', upload_to='Productos', ) price = models.IntegerField('Precio del metro cuadrado') content = models.ForeignKey(Content, on_delete=models.CASCADE) objects = ProductManager() class Meta: verbose_name = ("Producto") verbose_name_plural = ("Productos") def __str__(self): return self.product_name forms.py class ProductForm(forms.ModelForm): [...] form_type = forms.CharField( required=False, widget=forms.HiddenInput() ) image = forms.ImageField() class Meta: model = Product fields = ( 'product_name', 'subtitle', 'price', 'description', 'image', 'form_type', ) def clean(self): cleaned_data = super(ProductForm, self).clean() product_name = self.cleaned_data.get('product_name') form_type = self.cleaned_data.get('form_type') products = Product.objects.all() for p in products: if p.product_name == product_name and form_type != 'Update': self.add_error('product_name', 'El nombre de este producto ya existe') return self.cleaned_data My views.py class ProductCreateView(LoginRequiredMixin, FormView): form_class = ProductForm template_name = 'producto/product-form.html' success_url = reverse_lazy('product_app:product-list') login_url = reverse_lazy('usuario_app:login') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) print(request.FILES) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print('Entra') response = super(ProductCreateView, self).form_valid(form) response.delete_cookie('error') return response This is my html with enctype="multipart/form-data" <form action="{% if product == None %}{% url 'producto_app:product-create' %}{% else %}{% url 'producto_app:product-update' product.product_id %}{% endif %}" id="productForm" method="POST" enctype="multipart/form-data" > <div class="modal-body"> {% csrf_token %} <div class="form-group"> <label for="product_name"> <span class="text-danger">*</span> Nombre del … -
Django - Iteration in two lists of multiple values returning only one set of iteration
I have an issue in relation to zip() and iteration. nutritional_info_quantity_per_user = [] if related_profiles: for r in related_profiles: r_perc = round((r.kcal/self.request.user.profile.kcaltotal)*100) for intake in intakes: intake_quantity = intake.amount intake_custom_quantity_per_user = myround_two((intake_quantity/menu_kcal) * (kcal)*(r_perc/100)) nutritional_info_quantity_per_user.append(intake_custom_quantity_per_user) (...) nutritional_infos_per_user = zip(intakes, nutritional_info_quantity_per_user) (...) Queries are good as they are returning the full list of values. But when I loop through "nutritional_infos_per_user" in the template as follows: {% for t, i in nutritional_infos_per_user %} {{t.type.name}} {{i}} {% endfor%} I only get the first iteration (however I have two or more "related_profiles"). Clearly I am doing something wrong and I would be very grateful if someone could help ! Many thanks. -
Using django_property_filter but PropertyChoiceFilter failing to match on Inactive
I can't figure out what I'm doing wrong here. I'm using django_property_filter to add a filter to my list of employees. I have an Employee model to extend the User model. It has a property of is_active to return the user model's is_active value. class Employee(models.Model): """Model representing an employee - one-to-one with user""" user = models.OneToOneField(User, on_delete=models.CASCADE) @property def is_active(self): """Property to return active status of user to employee model""" return self.user.is_active I have a propertyfilter using django_property_filter class EmployeeFilter(PropertyFilterSet): ACTIVE_CHOICES = ( (True, 'Active'), (False, 'Inactive'), ) active = PropertyChoiceFilter(choices=ACTIVE_CHOICES,field_name='is_active',lookup_expr='exact',label='Active') class Meta: model = Employee fields = ['locations'] I'm using a function based view to list all employees. def EmployeesList(request): employee=getemployeefromuser(request) if employee: emp_list = Employee.objects.filter(hotel__exact=employee.hotel).order_by('user') f = EmployeeFilter(request.GET, queryset=emp_list) emp_list = f.qs paginator = Paginator(emp_list, 20) page = request.GET.get('page', 1) try: emps = paginator.page(page) except PageNotAnInteger: emps = paginator.page(1) except EmptyPage: emps = paginator.page(paginator.num_pages) context = { 'filter':f, 'emps':emps, } return render(request, 'staffapp/employee_list.html', context=context) The filters display as expected. The location filter works correctly. The active filter works correctly for ----/None and Active/True but when I select Inactive it just returns the same results as Active. The URL correctly appends "?Active=False" but the resulting employee records are … -
Using Django urls and Vue routes in the same project
I'm creating a Django app and i already made the whole authentication layer using Django templates and Django urls, in order to handle authentication i used django-allauth. Since the app requires a lot of interactivity and heavy use of real time features, i realized i need to use VueJS and i already have some Vue components ready. The big problem is that if i add Vue and turn my application in a SPA, i'm going to have to rewrite this whole authentication layer from Vue, which is quite difficult and not exactly my field, so would it be possible to have the authentication part handled by Django urls and Django templates rendered by standard Django views and the rest of the app as a Vue SPA that uses Vue routes? So basically i have: from django.urls import path, include from . import views from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('login/', LoginView.as_view(), name='login'), ... path('', views.index, name='index') ] After logging in from a template rendered by a django view, the user is redirected to the Vue app, where urls are handled by Vue routes. What happens if i do this? If the route is handled by Vue, … -
How to preserve whitespace in a create form in django
I just wanted to know how to preserve whitespace while creating forms in Django. So if I had a create form, and i just created a post on my site, the whitespace needs to be preserved. for example. text text the space in the middle is what i want preserved. But for now, it just groups them. text text it returns that. So please let me know how. forms.py class AnnouncementsSectionCreateForm(forms.ModelForm): is_pin = forms.BooleanField(label="pin announcement post", required=False) class Meta: model = AnnouncementsSection fields = ('title', 'description', 'is_pin') widgets = { 'title': forms.TextInput(attrs={ 'class': 'form-control' }), 'description': forms.Textarea(attrs={ 'class': 'form-control', }), } so my model, views, and my template don't seem to be important for this. I am pretty sure, all the work is in forms.py. So please let me know how. Thanks! -
How to change design of a form in template? Django
I am trying to customize my form design and there are some things I dont know how to delete/ change. forms.py class UserProfileAvatarForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['avatar'].widget.attrs.update( {'class': 'form-control', 'type': 'file', 'id': 'formFile'}) This is what I get: How can I get rid of "Currently" and "Change:"? This is the html output: I can give display:none to a tag to make it disappear, but "Currently" and "Change:" dont have a tag. Is there any solution? It has to do with css or with forms.py? -
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?: Heroku/Django
I've been struggling over this for days now and none of the numerous threads I've come across have worked for me. I have a Postgresql DB with postgis extention that I access with pgadmin4 for my Django app. I semi-successfully deployed my application to Heroku, except anything that needs data from the psql DB does not work, I get the error mentioned in the title. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'geospatial': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geospatial', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', } } error: OperationalError at /facility/ could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Request Method: GET Request URL: http://lessmedtxt.herokuapp.com/facility/ Django Version: 3.1.5 Exception Type: OperationalError Exception Value: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? adding the below code to my settings.py does nothing either: import dj_database_url geodbtest = dj_database_url.config() DATABASES['geospatial'].update(geodbtest) DATABASES['geospatial']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' django_heroku.settings(locals()) I've run heroku run python manage.py migrate but it says I have no migrations to apply. Please help me, I've spent days over trying … -
Django templates - request in url problem
I've got a quite a problem with solving some {% url %} issue in django. Im currently creating small e-commerce website where you can check other people's profiles. Im currently using navbar which is included in every template via {% inclue 'navbar.html' %}. Here is the most important fragment of it: Navbar.html {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'view_profile' username=request.user.username %}">My Profile</a> </li> {% endif %} </ul> </div> {% if user.is_authenticated %} <a href="account_settings.html"><span class="hello-msg">Hello, {{request.user.first_name}}</span></a> <a href="{% url 'logout' %}"><span class="hello-msg">Logout</span></a> {% else %} <a href="{% url 'login' %}"><span class="hello-msg">Login</span></a> <a href="{% url 'register' %}"><span class="hello-msg">Sign up</span></a> {% endif %} Everywhere except "view_profile" view, it works as intended. When I'm logged off I don't see "my profie" href or "logout" href etc. But the problem is appearing when I try to enter view_profile path without being logged in. Even though I'm checking if user is logged in Navbar.html {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'view_profile' username=request.user.username %}">My Profile</a> </li> {% endif %} It gives me: Keep in mind, this problem doesnt appear ANYWHERE (navbar is in all templates) except profile view, even though the link is correct and is providing username, … -
django heroku build can't find config vars
I have a staging app which is deployed but have some disturbing logs when trying to import the config vars from heroku. Here is a sample: -----> Exporting application config values -----> Loading environment information cat: /tmp/d20210317-55-vc7xqe//tmp/d20210317-55-vc7xqe/ALLOWED_HOSTS: No such file or directory /tmp/codon/tmp/buildpacks/9f6bae6fc2432740f5d76d23e8fbcb5e7b35afaa/bin/compile: line 11: export: `/tmp/d20210317-55-vc7xqe/ALLOWED_HOSTS=': not a valid identifier cat: /tmp/d20210317-55-vc7xqe//tmp/d20210317-55-vc7xqe/COMPRESS_ENABLED: No such file or directory any idea why this is happening? -
Django Model Validation. How would I check to see if the users inputs match a Users in the database table
// Model class that displays the fields for the different models class Users(models.Model): // Possible department choices departmentChoices = ( ('MD', 'Math department'), ('ED', 'English department'), ('HD', 'History department'), ('GD', 'Geography department'), ('FD', 'Finance department'), ) username = models.CharField(max_length=20) password = models.CharField(max_length=25) department = models.CharField(max_length=23, choices=departmentChoices, primary_key=True) // views login function def login(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] department = request.POST["department"] user = auth.authenticate(username=username, password=password, department=department) if user is not None: auth.login(request, Users) # return the home page as the login was succesfull return redirect("home.html") # User doesnt exists return render(request, 'login.html') //return the login page again if the users login details don't match a record from the models database table -
Does Django allow you to take in user input and run it through a custom method?
I am fairly new to Django and am attempting to build a web application in which I can ask for user input and run it through a method. I used twint and wrote some code that allows a user to input either a stock ticker or a username within a date range and it will pop out all the tweets that either contain either the ticker or the username. Being that I am still new at Django (I've built a basic blog following a tutorial and that's about it), I was wondering if 1) it was possible to build what is described above and 2) suggestions on where to start. Thank you -
Issues with printing bytea data from PostgreSQL in python, but always get <memory at 0x> address
So I am having some troubles getting access the bytea binary data from PostgreSQL using Python. So this is the model for Images: class Images(models.Model): image_code = models.BinaryField() caption = models.CharField(max_length=100,default='IMG_CAPTION') Here is the data table from PostgreSQL | id |image_code (bytea) | caption (char var) | | ---|---------- | ------- | | 1|[binary] | DEFAULT CAPTION | So in my project I have following store_length = len(Images.objects.all()) image_shown = Images.objects.all()[store_length-1] code_string = image_shown.image_code print(code_string.image_code) The output I get is memory address <memory at 0x7ff5ae03a888>. The output is supposed to be string. What should I do here?