Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template add GET parameter after current URL
Previously, I handled my translation with GET parameter, by requesting the ?lang=<lang_code> on URL. <h6>{% trans "Translate" %}</h6> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <span id="language-icons"> {% for language in languages %} {% if language.code == 'id' %} <a href="?lang=id" title="Indonesia"> <img height="20px" src="{% static 'icons/flags/id.svg' %}"> </a> {% elif language.code == 'en' %} <a href="?lang=en" title="English"> <img height="20px" src="{% static 'icons/flags/us.svg' %}"> </a> {% endif %} {% endfor %} </span> When I handle with {{ request.META.QUERY_STRING }}, and the previous URL already included lang= param (like: /path/to/?page=2&lang=en). The next lang= will attempts multiple times (like: /path/to/?page=2&lang=en&lang=id). I want to replace the old lang=en param with new lang=id. So, the url should be /path/to/?page=2&lang=id. Here is what I was tried; {% with QUERY_STRING=request.META.QUERY_STRING %} {% if QUERY_STRING %} {% if 'lang' in QUERY_STRING %} <a href="?{{ QUERY_STRING|replace_with:"lang=id" }}"> <!-- something like `replacer` --> {% else %} <a href="?{{ QUERY_STRING }}?lang=id %}">...</a> {% endif %} {% else %} <a href="?lang=id">...</a> {% endif %} {% endwith %} I just think, the above problem maybe nice when handle with templatetags, like: @register.filter def cutoff_url(request, replacer='lang=id'): params = request.META.QUERY_STRING # 'id=1&lang=en' replacer_list = … -
How to delete a fk record in Django Rest Framework
My goal is to delete the fk record related with the record of the given id in the endpoint. my url path('car-pricing/<uuid:car_id>/', car_pricing), my model class Pricing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) car = models.ForeignKey(Car, related_name="pricings", on_delete=models.CASCADE) In other words I want to delete a specific Pricing record given the id of a Car in my endpoint. By requesting with an id of a Car record I can get more than one Pricing records. Is it somehow possible to choose to delete a specific Pricing based on the id? my view(here, I do not know how to deal with delete function) elif request.method == 'DELETE': pricing_data = request.data return Response(status=status.HTTP_204_NO_CONTENT) Here the requested data is an empty QueryDict and it is ok, since there is no way to give requested data to a delete action in django rest framework -
How to serializer an ImageField from another model in django rest framework
I know there are many similar questions but none of them solves my problem. I have a simple topic that has an image field, a topic title, a topic content, a topic slug and etc. That topic is associated with a user using the foreignkey. The serializer is doing fine until the serializer for the image field was added. serializers.py class TopicDetailSerializer(serializers.ModelSerializer): topic_author = serializers.SerializerMethodField('get_topic_author') topic_author_picture = serializers.SerializerMethodField( 'get_topic_author_picture') class Meta: model = Topic fields = ['id', 'topic_title', 'topic_content', 'created_date', 'topic_slug', 'thread_title', 'topic_author', 'topic_author_picture', ] def get_topic_author_picture(self, topic): return topic.owner.profile_picture def get_topic_author(self, topic): return topic.owner.username The output in the console when I request the data from frontend: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte Ain't I just storing the path to the Image rather than the image itself? I mean I have a user profile serializer which sends information to the requested user and it includes an image. But it works fine. -
How to solve "OperationalError at / Could not decode to UTF-8 column 'mainpic' with text '����'"?
I saw some several similar questions, but I couldn't find the answer. This is the successful image without BLOB image files. It works fine when there aren't any images, but when I put images at my DB browser for SQLite, it doesn't work like below. The picture of adding some pictures through SQLite3 DB browser. This is the error code How can I solve this problem? Should I change encoding from utf-8 to another? from django.db import models class Restaurants(models.Model): name = models.CharField(max_length=100, blank=False, null=False) location = models.CharField(max_length=10, blank=False, null=False) xco = models.FloatField(max_length=20, default='') yco = models.FloatField(max_length=20, default='') upinfo = models.CharField(max_length=500, default='') downinfo = models.CharField(max_length=500, default='') resnumber = models.CharField(max_length=16, default='') mainpic = models.ImageField(blank=True, null=True) menupic = models.ImageField(blank=True, null=True) respic = models.ImageField(blank=True, null=True) This is the django framework part. -
"action" in form not redirecting to django views
Im new to django and new to stackoverflow too. Im trying to create my personal blog, but its comment section is not working. i tried and found that its url is continuously matching with my 'posts/str:slug' url and giving me the same page instead of executing the views. its doesnt even add comments when i checked my admin panel. but i can manually add comments to it and can display it. i think something is messed up with my URLS. Please help. **[blog/urls.py(app)]** from django.urls import path from blog import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('postComments', views.postComments, name="postComments"), path('', views.home, name='home'), path('blog/', views.blog, name='blog'), path('contact/', views.contact, name='contact'), path('search/', views.search, name='search'), path('login', views.login, name='login'), path('logout/', views.logout, name='logout'), path('error', views.error, name='error'), path('posts/<str:slug>', views.posts, name='posts'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) **[main urls.py]** from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static admin.site.site_header = "BlueBlog Administration" admin.site.site_title = "BlueBlog Admin Panel" admin.site.index_title = "Welcome to BlueBlog Admin Panel" urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('blog.urls')), path('register/', include('register.urls')), path('error/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) **[views.py] here postComment is the view i am not redirecting to** … -
How to count values of many field for one object in Django?
Actually I'm stack in one thing. I'm learing a lot but I need your help... Django Models from django.db import models # Create your models here. class Car(models.Model): mark = models.CharField(max_length=180) model = models.CharField(max_length=180, unique=True) def __str__(self): return "Car mark : {} Car model {}".format(self.id,self.model) class Rate(models.Model): class Ratings(models.IntegerChoices): One = 1 Two = 2 Three = 3 Four = 4 Five = 5 grade = models.IntegerField(choices=Ratings.choices) car = models.ForeignKey(Car, on_delete=models.CASCADE,blank=True, null=True, related_name='rates') First of all - I would like to get avg value of rates assigned to one object. Secondly, I would like to count how many rates each object has. -
why I am not able to makemigrations to postgres DB?
My current Django project is binded to default SQLite DB. Now going forward I wanted to migrate to postgres. I have followed this link There's nothing wrong with the installation of the Postgres. I have followed exactly the same steps mentioned in the website: Login with the "postgres" user. sudo -u postgres psql Create a Database. CREATE DATABASE myproject; Create user and assign password. CREATE USER myprojectuser WITH PASSWORD 'password'; Grant privileges to the user. GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser; After this I added the below properties to my Django's settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_name', 'USER': 'new_User_name', 'PASSWORD': 'new_user_password', 'HOST': '', 'PORT': '', } } Now, when I do python manage.py makemigrations I get invalid password error. Going forward, when I execute some postgres commands to check the environment. I have below observation. In the Postgres shell, I execute '\l' to see the databases. I see below. Name | Owner | Encoding | Collate | Ctype | Access privileges -------------------------+----------+----------+---------+---------+-------------------------------- DB_Name | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =Tc/postgres + | | | | | postgres=CTc/postgres + | | | | | new_User_name=CTc/postgres Then I execute '\du' to see the … -
The record is not saved in the DJango-SQLite database
I am trying to save a record in the database of a model (Score) that is related to two other models (User and Exercise), I receive the form correctly or so I think, and using the save() instruction does nothing. I don't even get errors. Here the code: forms.py class ScoreForm(forms.ModelForm): #idUser = forms.IntegerField(widget=forms.HiddenInput(), label='idUser') idExercise = forms.IntegerField(widget=forms.HiddenInput(), label='idExercise') value = forms.FloatField(widget=forms.HiddenInput(), label='Value') class Meta: model = Score fields = ['idExercise', 'value'] views.py def save_exercise(request): if request.method == 'POST' and request.is_ajax: form_score = ScoreForm(request.POST, instance=request.user) if form_score.is_valid(): form_score.save() else: print('Tenemos un error') return HttpResponse('Respuesta') JavaScript document.getElementById('id_value').value = score; document.getElementById('id_idExercise').value = idexer // document.getElementById('id_idUser').value = iduser let data = new FormData($('#scores').get(0)); Swal.fire({ title: '<strong>Tu resultado: </strong>', icon: 'success', html: `<div class="progress" style="height: 30px;"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width:${number}%">${number}%</div></div>` + `Ganaste: ${score.toFixed(2)}`, focusConfirm: false, confirmButtonText: '<i class="fa fa-thumbs-up"></i> Okey!', preConfirm: () => { $.ajax({ type: "POST", url: "/polls/save/", data: data, processData: false, contentType: false, success: function(){ console.log('Funciona!') show_exercise() } }) } }) In html file <div class="row d-flex justify-content-center"> <form method="POST" action="" novalidate id='scores'> {% csrf_token %} {{ form|crispy}} </form> </div> All the inputs of the form are type hidden since after a couple of calculations I assign their respective values, the form … -
Passing parameters to template for NavBar menu in Django
I am trying to switch my head to start using MVC. I have a Base HTML template, with an include NavBar code: {% include "navBar.html" %} So far, so good. Now, I want to send information to it (to the navBar.html template) regarding the Menu buttons. I have some simple buttons, and others with drop-button behavior. My buttons are objects, they have information about name, href, position, etc, type (simple-button or drop-button) So, I created a nested list in this way: outer_list = [] for a in UserModule.objects.filter(user=user_id, is_active=True): inner_list = [] inner_list.append(UserModule(a)) for b in Submodule.objects.filter(module=a.module, is_active=True): inner_list.append(Submodule(b)) outer_list.append(inner_list) return {'outer_list': outer_list} So, my first element in every inner_list is the head of the possible drop-button, or a simple drop-button depending on his type attribute. The list is like at the end is like this: [0] Button-Simple-A [1] Button-Drop-A => [sub-button-1, sub-button-2, sub-button-3] [2] Button-Simple-B and so on. When I pass this outer_list to the template, the thing I have to do to arrange the buttons into the menu are crazy things. It has no sense to use MVC if I am going to write a lot of code in the template. Until now, I am doing this over … -
How to get the Django csrf token in a Vue js application
How do i get the csrftoken in Vue js application running on port 8080 from a Django application running on port 8000. From the docs i got know about the ensure csrftoken decorator and the getCookie function. But all this works when i do not seperate the front-end and the back-end. I want to use axios to transfer data between the Django and Vue app -
Django forms - FK QuerySet manipulation
I have a FK field and want to restrict the QuerySet. class KimEditForm(forms.ModelForm): class Meta: model= Kim fields = '__all__' exclude = ['order','customer','order_date', 'start_date'] def __init__(self, *args, **kwargs): kim = [veh.vehicle for veh in Kim.objects.filter(order_status = 'Active')] vehicle = [item for item in Vehicle.objects.filter(vehicle_status = 'KIM') if item not in kim] super(KimEditForm, self).__init__(*args, **kwargs) self.fields['vehicle'].queryset = vehicle what is wrong with my code I get a error. 'list' object has no attribute 'all'. -
Losing user input data due to heroku databse refresh (django backend)
So I made a django app and deployed it using Heroku - with s3 for file uploads and whitenoise for static files. So I use the admin page to add updates to the displayed sections, like new blog entries (for example or comments). The problem is that any database update using the admin page stays for a day at most and then refreshes, going back to the previous state and making me lose all the new data. I have tried some stuff, but I am totally out of my depth here. I even tried pulling the changes made back into my local copy and pushing again to repository but it shows no changes. Is it something to do with how Django takes in user input? If anyone could help me that would be amazing. If you guys need any code please tell me. -
I want to give some token to Anonymous User and store his data, if the user is registered back end should transfer the data
the 'token' is generated on back end as above def get(self, request): if self.user.is_authenticated: # the logged user's data is stored else: token = get_random_string() #this function was imported from other file here I am sending the token to requested url as Json file but can't take it on front end and send it to back end when the user is requested to the url before the user already requested! please help me out!!! here is the Vue file in front end searchProduct(keyword){ if(this.selectedCatId != '' && this.selectedCatId != 'all'){ this.$router.push({name: 'search', query:{ k:keyword, cpn: this.$route.query.cpn ? this.$route.query.cpn : 1, cid: this.selectedCatId} }) }else{ this.$router.push({name: 'search', query:{ k: keyword, cpn: this.$route.query.cpn ? this.$route.query.cpn : 1} }) } this.$axios.get('requested url'+this.searchKeyword+'&pagenum=1&productsPerPage=10', { params: { usertoken: localStorage.getItem('unregUserSearchToken') } }) .then(function (response) { localStorage.setItem('unregUserSearchToken', response.data.search_token) console.log(response); }) -
Can not solve Git error "refusing to merge unrelated histories"
When I tried to pull git pull https://myid@bitbucket.org/myid/abc.git error occurred branch HEAD -> FETCH_HEAD fatal: refusing to merge unrelated histories Then I tried this git pull origin master --allow-unrelated-histories error occurred fatal: 'origin' does not appear to be a git repository fatal: Could not read from remote repository. Then I tried this git mergetool error occurred This message is displayed because 'merge.tool' is not configured. See 'git mergetool --tool-help' or 'git help config' for more details. 'git mergetool' will now attempt to use one of the following tools: tortoisemerge emerge vimdiff No files need merging Check branch name git branch --contains=HEAD branch is only master master I can not figure out how to fix this problem, please teach me what I can do next?? -
Syntax Error when migrating a django server
I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something. I tried asking the original developer but he is busy with other stuff so haven't gotten a reply but as I have to get the project going, I'll try asking here. The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the modules. The code used in this project can be found here: https://github.com/HumanDynamics/openbadge-server Also the main … -
Django can't call custom django commands extwith call_command
This is probably a really basic question but I can't find the answer anywhere for some reason. I created a custom command which I can call from the command line with python manage.py custom_command. I want to run it from elsewhere but don't know how to do so. I have added pages to my INSTALLED_APPS in settings.py. This question: Django custom command works on command line, but not call_command is very similar but I'm not sure what the answer means and I think it's unrelated. My file structure is : ├── custom_script │ ├── script.py │ ├── __init__.py ├── project │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── pages │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── management │ │ ├── commands │ │ │ ├── __init__.py │ │ │ └── custom_command.py │ │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py content of script.py from django.core.management import call_command call_command('custom_command', 'hi') content of custom_command.py from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('message', type=str) def handle(self, *args, **options): print('it works') I want … -
APIClient vs RequestFactory (with coding example)
I am new to django, and i tried something this: from rest_framework.test import APITestCase, APIClient, APIRequestFactory from django.contrib.auth import get_user_model client = APIClient() User = get_user_model() factory = APIRequestFactory() class UserLoginTestCase(APITestCase): def SetUp(self): user = User.objects.create(email="test@gmail.com", password=utils.make_password("test@12345"), full_name="The User") user.save() def test_user_login(self): valid_data = {"email": "test@gmail.com", "password": "test@12345"} url = reverse('api:login') response = self.client.post(url, data=valid_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) Is this possible that can i use "APIRequestFactory" for above code? Please also tell how to use "APIClient" in more good way. -
How do I solve psycopg2 error when trying to run in local server?
So I have deployed my project using AWS EC2. I was trying to run the application in my local server as well, for testing. But then I got the error below. Traceback (most recent call last): File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\user\Envs\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError I have this in settings.py import os from .local_settings import PG_HOST DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME' : 'myDB', 'USER' : 'Manager', 'PASSWORD' : '###password###', 'HOST' : PG_HOST, 'PORT' : '', } } And this in local_settings.py. (NOT used in the AWS server) PG_HOST = '' What do you think is wrong? Thank you very much in advance. -
django valueError/ at /login/
The view XXX.views.loginPage didn't return an HttpResponse object. It returned None instead. i am having a value error on my redirect function below. i already refer some answer that other user ask on same error. but it still not working. I really need your help. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login def loginPage(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): user = form.get_user() login(request, user) if 'next' in request.POST: return redirect(request.POST.get('next')) else: return redirect('index.html') else: form = AuthenticationForm() return render(request, 'loginPage', {'form': form}) urls.py from django.urls import path from . import views from .views import redirect_view urlpatterns = [ path('', views.Index, name='index.html'), path('index/', views.Index), path('register/', views.register), path('login/', views.loginPage), path('/redirect/', redirect_view) ] -
I don't know how to which relationship to use between these 6 models Order, Item , OrderItem, SihippingAddress ,Payment and Coupon in django models.py
So these are the elements i want to store in these models. In Item: title, price , discount_price , label , category , slug, description In OrderItem : user , ordered , quantity , item In Order : user, items, create_date , order_date , ordered, shipping_address, payment, coupon In ShippingAddress : street_address , country , zip , user In Payment : stripe_charge_id , amount , timestamps In Coupon : code, amount As you have seen I want to create relationship between Order, OrderItem and Item, also in Order I want to refer to 3 models Payment, ShippingAddress and Coupon but I don't know which relationship to use between these models. -
python manage.py run server is not working
need help please "...can't open file 'manage.py': [Errno 2] No such file or directory" Im working on windows. I am trying to run the server but I keep getting this error. I tried every solution that is posted but no luck. what's the solution please ? thank you -
attributes field is not resolved and always returns null
I am practicing through saleor's product models and schema to be familiar on ariadne where I could get the list of products but I could not fetch the attributes associated with the product. Their schema is as follow schema.graphql type Product implements Node { id: ID!, productType: ProductType! name: String! slug: String! description: String! category: Category! price: Money attributes: [SelectedAttribute] variants: [ProductVariant] images: [ProductImage] collections: [Collection] } type SelectedAttribute { attribute: Attribute values: [AttributeValue] } type Attribute implements Node { id: ID! productTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection! productVariantTypes(before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection! inputType: AttributeInputTypeEnum name: String slug: String values: [AttributeValue] valueRequired: Boolean! } type AttributeValue implements Node { id: ID! name: String slug: String inputType: AttributeInputTypeEnum } resolvers.py query = QueryType() @query.field('products') @convert_kwargs_to_snake_case def resolve_products(obj, info, **args): products = models.Product.objects.all() if 'sort_by' not in args: args['sort_by'] = { 'field': category_sorting_field.values['NAME'], 'direction': category_direction.values['DESC'] } return connection_from_queryset_slice(products, args) product = ObjectType('Product') @product.field('productType') def resolve_product_type(obj, info): return models.ProductType.objects.get(products__id=obj.id) @product.field('attributes') def resolve_attributes(obj, info): print('obj', obj.product_type.product_attributes.all()) return obj.product_type.product_attributes.all() Here, the product type is resolved using @product.field('productType') but not for attributes. I keep getting "attributes": [ { "attribute": null }, { "attribute": null } ] This is what … -
how can i POST data from ant design form into Django Backed?
i trying to post data from ant design React.js into Python Django rest frame work. so I am using method OnFinish to send data, but its not working. MY big problem is , i don't know how can i Introduction Data i want to send them data from Form , by using React-redux or something else way , so please Help me . #react.js Form: import React, { Component } from "react"; import { Form, Input, Button, PageHeader, Select, DatePicker, message, } from "antd"; import "antd/dist/antd.css"; import { connect } from "react-redux"; import axios from "axios"; // defualt setting for django axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; // from layout setting const formItemLayout = { labelCol: { xs: { span: 24, }, sm: { span: 8, }, }, wrapperCol: { xs: { span: 24, }, sm: { span: 16, }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; // end fform layout setting // const onFinish = (values) => { // console.log(values); // axios.post("http://127.0.0.1:8000/api/create/", { // title: values.title, // manager: values.manager, // }); // }; // const title = event.target.elements.title.value; // const manager = … -
Can anyone show me some example project with details for the live chat on the website in Python, Flask?
I am going to add a live chat section for my website using flask or Django can someone show me some links or instruction which can direct me to the target? -
I'm calling another page on click button in Django Framework but it is not working
I'm trying to navigate to the result.htm from index.html on click button on "RUN" but the below code is not working to navigate to result.htm. index.html <ol> <li> <form method="POST"> {% csrf_token %} <input class="bg-yellow text-white" id="RUN" href={% url 'result' %} value="RUN" name="runModel" type="submit" onclick="sendValuesToBack()"> </form> </li> <input type="image" onclick="openSettingForm()" alt="submit" data-modal-target="#modal" class="img" style="width:80px;height:70px;" src="{% static 'AutoGenerateML/assets/img/Setting.jpg'%}"> </ol> result.html <!DOCTYPE html> <html> <head> </head> <body> <h1>Hello Result Page</h1> </body> </html> urls.py path('result/',views.result,name="result"), View.py def result(request): return render(request,"result.htm")