Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What the proper way of uploading an image in Django
I have a REST endpoint for creating certain resource, but now I want to add the functionality of uploading an image when creating the resource. What's the proper way of doing such feature? Do you need to upload the file separately then do another POST request for creating the resource? -
Django: multiprocessing: multiprocessing in a module with windows?
I am using multiprocessing inside one of my views.py #current module is someapp.views #current file is someapp.views.py from someapp.models import ModelA. ModelB getScore(args): --get some data from ModelA and ModelB based on args --do some calculation with the args and models return a value def Getsomedata(request): arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) It keeps giving error Apps not loaded I tried def Getsomedata(request): if __name__ == "__main__": arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) the if statement does not quality because __name__ = someapp.views HOw to run the multiprocessing -
How to url encode in Django views
In Django, I want to do this <a href="{% url 'firstapp:create' %}?next={{ nextos|urlencode }}"> but in my views.py, when I render a page return render(request, 'create' + parameter next=nextos) Any ideas? -
How can I get the full URL from my request argument? [duplicate]
I have a method that resolves a get request that looks like this: import json import json_api_doc import requests from django.conf import settings from django.core.cache import cache from django.utils import timezone from rest_framework.response import Response from rest_framework.views import APIView class MyClassAPIView(APIView): def get(self, request): foo = request.query_params.get('foo', '') # url = request.url <-- this does not work, but is what I'm trying to accomplish ... return {...} As you can see, I am able to get the query_params, but I would also like to get the full URL that is coming in. For example, this is the URL I am trying to read: https://example.com?foo=bar I have tried print(dir(request)) to see what is available, but not seeing anything related to path or url. I am successfully getting the query_param -- how can I get the full URL? -
Can we make an android app using django and briefcae packaging?
Can we make an android app using django and briefcae packaging? I mean use django as its gui framework and make an android apk installer using briefcase. -
Django Models (dynamic?)
I am just starting Django Website; I have deciced to go with a model (with SQLite DB), which have the following properties: class Flow(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Owner", default="ADMIN") source = models.CharField(default='HTTP', choices=SOURCE_CHOICES, editable=True, max_length=12) name = models.CharField(max_length=50, default=" ") date = models.DateTimeField(verbose_name="Creation date") I want to add others fields to this model depending on the source field value. For example if the source field : 'File' is selected. I will create additionnal field (like file name, file directory ...) If 'Http' is selected, I will create a field URL. Thus depending on the source field, I will have differents field and type. I have read this kind of model is difficult to reprensent in Django; I am open minded to other kind of solution. My idea was to created as many model as the possible source value. -
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag?
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag? My homepage code {% extend "mainApp/wrapper.html" %} {% block content %} <p> Darbibas parbaude! </p> {% endblock %} My wrapper code <!<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <meta http-equiv = "X-UA-Compatible" content = "ie=edge"> <title></title> </head> <body> <body style media = "background:silver"> {% block content %} {% endblock %} </body> </html> -
Django i18n translation after changing default language
I have two languages on the website - en and ru. When the project started, the default language was en. So, in the template I type something like {% trans 'Hello' %} and make translations only for ru in the locale folder. But now I have changed the default language to ru. And now the website was in ru even if the language is en because I haven't translated anything for en (it's already in en however). How to fix it? how to make it so that in the absence of translation i18n doesn't translate anything and shows just the text as it is? Thanks. -
How to insert two user chat data into firebase database using Django?
i am new in Firebase. i want to implement chat module in firebase using django.i want insert users chat into firebase according to image structure, here is the image as mentioned in image , all the messages of user number 30 are under entry number "30" . how to insert data in above formet? -
Django 3: Passing slug in URLs to views?
I'm trying out Django for a webshop, I'm following the instructions of a book(Django 3 by example), but there seem to be something missing. I have tested if return to home in def product_list seen in views.py, so I believe the problem is in the "if category_slug:" condition or it is not receiving the slug. In main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] In app urls.py urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='products_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ] In views.py: def product_list(request, category_slug=False): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) -
Can't perform migration on django 3, python 3, sqlite3
I run manage.py migrate on my django blog project and get this: (joelgoldstick.com) jcg@jcg-hp:~/code/p3/joelgoldstick.com/blog$ python manage.py migrate . . . django.db.utils.OperationalError: table "django_content_type" already exists During handling of the above exception, another exception occurred: . . . raise IntegrityError( django.db.utils.IntegrityError: The row in table 'blog_app_entry_categories' with primary key '8' has an invalid foreign key: blog_app_entry_categories.category_id contains a value '3' that does not have a corresponding value in blog_category.id. but the table blog_category contains a row with id = 3 -
Django project not start
Why my django project not start? django version - 1, path - 2 -
How to get data from a data base in Django
I want to create a car park app using Django and need to query the database for all carparks and then display this information on the app home page. Below is a models.py file. from django.db import models class Campus(models.Model): enter code herecampus_id = models.IntegerField(primary_key = True) enter code herename = models.CharField(max_length = 100) enter code heredef str(self): enter code hereenter code herereturn self.name class Carpark(models.Model): enter code herecarpark_id = models.IntegerField(primary_key = True) enter code herename = models.CharField(max_length = 100) enter code herecampus_id = models.ForeignKey(Campus,on_delete = models.CASCADE) enter code herespaces = models.IntegerField() enter code heredisabled_spaces = models.IntegerField() enter code heredef str(self): enter code hereenter code herereturn self.name -
How to delete Data from db by Datatable href delete button using django python
**I need to delete data from the data table please check my below code. kjndekjnkewjkjbwebewbrbkjewkjkjdkjfcbsdbndksjfhkhweiroiweoirjowjernkjm bmdsvmn mndsf dkjsfnkjdsnfkjkdsfkjdbskjfbwehrohoweijroiwej] lkfnewlklewjrjewiroijewoirjoierwhktbkjergtmnbermntbewnmbnmwebmnrbwemnrbmnwebrmnbwewenrbnmwebrmnewbnmr ** What i have to pass in htlm href tag *********Model.py ******* class Ownership(models.Model): ownrspid=models.AutoField Ownership_Type= models.CharField(max_length=20, default='') Desc= models.CharField(max_length=254, default='') def __str__(self): return self.Ownership_Type #*********views.py ******* def RemoveOnwer(request, id): if request.method == "POST": onwrid = int(request.POST.get('ownrspid')) onwr = Ownership.objects.get(id=onwrid) onwr.delete() messages.success(request, 'Ownership Type successfully deleted!') return redirect('/Add_Ownership') ownr = Ownership.objects.all() return render('Add_Ownership.html', {'ow': ownr}) *********urls.py ******* path('Add_Ownership', views.RemoveOnwer, name='Add_Ownership') *********Add_Ownership.html******* <tbody> {% if ow %} {% for j in ow %} <tr> <td>{{j.Ownership_Type}}</td> <td>{{j.Desc}}</td> <td class="text-right"> <a href="#" class="btn btn-link btn-info btn-just-icon like"><i class="material-icons">favorite</i></a> <a href="#" class="btn btn-link btn-warning btn-just-icon edit"><i class="material-icons">dvr</i></a> <a href="/RemoveOnwer/{{}}" class="btn btn-link btn-danger btn-just-icon remove" type="Submit" value="yes"><i class="material-icons">close</i></a> </td> </tr> {% endfor %} {% else %} NoData {% endif %} </tbody> -
Django migrate error for Oracle database table
I have created django project where following versions I have used. Python version 3.8.6 Django version 3.1.2 Oracle 11g I have run makemigrations which works all correct but mugrate commands give me error i.e django.db.migrations.exceptions.MigrationSchenaMissing: Unable to create the django_migrations tabel (ORA-02000: missing ALWAYS keyword) Database setting is following: > DATABASE = { 'default':{ 'ENGINE': 'django.db.backebds.oracle', > 'NAME': '10.1.5.87:1529/cdxlive', 'user': 'cisadm', 'PASSWORD': > 'cistechnology' } } Table I am creating is class Test(models.Model): name = models.CharField() score = models.CharField() -
Call different view function with empty url path , on same app (multiple empty url mapping to different view function)
This is my project urls.py urlpatterns = [ path('', include('index.urls'), name='index'), path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('terms-and-conditions/', include('index.urls', namespace='index'), name='terms'), ) this is my app's urls.py: urlpatterns = [ path('', views.index, name='index'), path('', views.terms, name='terms'), ] my goal is to have the main urls.py generate paths, without having to change the path inside my app's urls.py Example (desired behaviour): website.com/en/terms-and-conditions -> views.terms gets called website.com/ -> views.index gets called The following app's urls.py works: urlpatterns = [ path('', views.index, name='index'), path('terms/', views.terms, name='terms'), ] But now i get www.website.com -> maps to views.index (This is correct) www.website.com/en/terms-and-conditions/ -> maps to index as well. (not correct) and www.website.com/en/terms-and-conditions/terms -> maps to views.terms (NOT THE DESIRED URL) www.website.com/terms -> maps to views.terms (not desired, its redundant and maps to the same page as above) I could solve this by using an app for each page, but this seems very unnecessary as this is a simple website where i'd like to keep everything contained in one app. I started using django 3 or 4 days ago, so i am really at a loss on how to solve problems like these. Any help is very welcome . And i thank you … -
Django - best way to associate user data after log-in
When my users answer a challenge, I want it to be stored against their profile. When they log in, they will see an index of challenges and it will show which ones have been answered. I thought I could solve this problem by having a User_Challenge model in models.py: class User_Challenge(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, null=True) answered = models.BooleanField(default=False) But because you can't do filtering in a template, I am finding this really cumbersome. Is there a simpler way to associate challenge status against a user profile without introducing another table? -
Django Rest Framework nested serializer creation
I have troubles saving object with foreign key. I have two Django model like (going to simplfy them, for this purpose, but the point remains): class Model1(models.Model): name = models.CharField() class Model2(models.Model): label = models.CharField() rel = models.ForeignKey("Model1", related_name="model2s") and two Serializers like: class model1SER(serializers.ModelSerializer): class Meta: model = Model1 fields = ['pk', 'name'] class model2SER(serializers.ModelSerializer): rel = model1SER() class Meta: model = Model2 fields = "all" def create(self, validated_data): model2 = Model2.objects.create(**validated_data) return model2 I post using axios POST to a modelViewSet, and the POST JSON body looks like: {'label': "xxxx", 'rel': {'pk': 1, 'name': "foo"}} Trying to create an object, returns "rel_id violates not null..." and after inspecting, the validated data only contains: ('rel', OrderedDict([('name', 'foo')])) without pk. I have also tried replacing pk with id, adding id and many more, but can not get to save a object using nested serializer. The Model1 Serializer is used to get the data for all Model1 objects. After selecting a single one, it is appended to a post data for a Model2 Serializer, so the structure of serialized data remains the same. Can I change the create method to somehow get the validated_data['rel']['pk'] ? Thank you -
Django queryset verify if fields exists
I want to implement a custom ordering backend (using rest_framework.filters.OrderingFilter) and I basically want to check if the field exists for my queryset first before filtering it without evaluating the queryset. something like if queryset.is_available_field(my_field): queryset = queryset.order_by(my_field) I cannot try / except because I don't know exactly when my queryset will be evaluated. -
Looping Multi-Dimensional Array in Django HTML Template
My Dictionary looks like below Table: 0: Name1 : ABC Name2 : IJK 1: Name1 : QQQ Name2 : FFF 2: Name1 : WWW Name2 : RRR Currently the below HTML code working with hard coded '0', but nor working with 'row' Here key = 'Table', as mentioned above. {% for key, value in data.items %} {% for row in value %} <br> {{value.0.Name1}} {% endfor %} {% endfor %} for : {{value.0.Name1}} --> Gives output as ABC In the above code, if i replace '0' with 'row' then i get error. Please help. Best Regards, Namratha Patil -
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf
i am new in django. i work on a project . it is my bookdetailview:: class BookDetailView(generic.DetailView): model = models.Book template_name = 'catalog/book_detail.html' and this is my renewbooklibririan that define in views:: def renew_book_librarian(request, pk): """ View function for renewing a specific BookInstance by librarian """ book_inst=get_object_or_404(models.BookInstance, pk = pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_inst.due_back = form.cleaned_data['renewal_date'] book_inst.save() # redirect to a new URL: return HttpResponseRedirect(reverse('catalog:my-borrowed') ) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) and this is my url pattern: urlpatterns = [ path('', views.Index.as_view(), name = "index"), path('books/', views.BookListView.as_view(), name = "books"), path('authors/', views.AuthorListView.as_view(), name = 'authors'), path('book/<int:book_id>/', views.BookDetailView.as_view(), name = "book-detail"), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name = 'my-borrowed'), path('book/<int:book_id>/renew/', views.renew_book_librarian, name='renew-book-librarian' ) ] my code is working until add the renew-book-libririan … -
Django: for loop through parallel process and store values and return after it finishes
I have a for loop in django. It will loop through a list and get the corresponding data from database and then do some calculation based on the database value and then append it another list def getArrayList(request): list_loop = [...set of values to loop through] store_array = [...store values here from for loop] for a in list_loop: val_db = SomeModel.objects.filter(somefield=a).first() result = perform calculation on val_db store_array.append(result) The list if 10,000 entries. If the user want this request he is ready to wait and will be informed that it will take time I have tried joblib with backed=threading its not saving much time than normal loop But when i try with backend=multiprocessing. it says "Apps aren't loaded yet" I read multiprocessing is not possible in module based files. So i am looking at celery now. I am not sure how can this be done in celery. Can any one guide how can we faster the for loop calculation using mutliprocessing techniques available. -
[tag:celery [Connection reset Error either due to "connection to broker" lost or Could not receive ack
I have a back ground task named task_conclude_key_issues_through_selenium, which will perform some click operations on a web page which takes about 3 to 5 mins. I am getting any one of below error once celery back ground task execution is completed. 1.[2020-10-26 16:14:45,233: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last) 2.Couldn't ack 2, reason:ConnectionResetError(10054, "An existing connection was forcibly closed by the remote host', None, 10054, None) After 2 to 3 minutes,its getting connected to broker with following log message ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [2020-10-26 16:23:07,677: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// views.py: -------- board_details_task_info = task_conclude_key_issues_through_selenium.apply_async(args=[created_pk]) tasks.py: -------- @shared_task(bind=True) def task_conclude_key_issues_through_selenium(self, created_pk): settings.py: ----------- CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TRACK_STARTED=True My Application uses below Packages: 1.celery - 5.0.1 2.celery_progress 3.Python - 3.6.2 Please let us know how to resolve these errors and proceed further. Regards, N.Dilip kumar. -
CSRF cookie not set in Postman by Django
I am having strange behaviour: Situation 1: I set 'django.middleware.csrf.CsrfViewMiddleware' in my MIDDLEWARE settings. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I do a POST call with Postman to a REST endpoint: class BlogCreateView(APIView): http_method_names = ['post'] def get_context_data(self, **kwargs): return { 'request': self.request, 'kwargs': kwargs, } def post(self, request, **kwargs): """ POST a new object """ context = self.get_context_data(**kwargs) serializer = self.serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) new_instance = serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) The CSRF cookie is not set. I don't set a csrf value in the header of the request either. But the server accepts it. This should not happen right? -
How to Convert JSON Data Flask Into Djano Object
Flask project Convert flask application to django from flask import Flask, jsonify, request app = Flask(__name__) incomes = [ { 'cpu': "5.2 %" } ] @app.route('/cpu') def get_incomes(): return jsonify(incomes) @app.route('/cpu', methods=['POST']) def add_income(): incomes.append(request.get_json()) return '', 204 I want to convert the above piece of code into corresponding Django. Inside Django project in views.py file def cpu(request) is defined.