Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How To Get Current Logged In User's Form Input On Database
I have been making a website where a user logs in, and then they fill a form describing themselves further (what city they are in, which neighbourhood, which category, their description), then that input is collected into the database. Currently, the user logs in, but when they fill a form, the database doesn't store their username, meaning that they cannot edit their profile informations. Right now, I can only determine each input's user manually on Django admin, and I would like it to be automatic through simple code. Here is my models.py class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) website = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) telefon = models.CharField(max_length=200, null=True) desc = models.TextField(max_length=1000, null=True) il = models.ForeignKey(Il, on_delete=models.SET_NULL, null=True) ilce = models.ForeignKey(Ilce, on_delete=models.SET_NULL, null=True) image = models.ImageField(default='ananas.jpg', upload_to='profile_images') def __str__(self): return self.name Here is my views.py def createUsta(request): form = UstaForm() if request.method == 'POST': #print('Printing POST:', request.POST) form = UstaForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'form.html', context) Here is my forms.py class UstaForm(ModelForm): class Meta: model = Usta fields = ('name', 'category', 'il','ilce', 'website', 'email', 'desc', 'telefon', 'image') Here is my HTML (forms.html) for logged … -
Generate pdf from embedded Kibana dashboards from the Frontend
I'm trying to build a portal with Django and React. I'm also using Elasticsearch + Kibana. The situation : I've made 2 dashboards in Kibana and put those dashes in the react app (via iFrame method). Everything is fine up so far. The problem : I want to generate a pdf or ppt document, containing those Kibana dashboards and let the user download it. I know Kibana has a paid option to generate a pdf from dashboards but that's not possible in my case, plus it is from the Kibana interface. I've tried to use libraries like revealJS and puppeteer or take screenshots programmatically and insert them into pdf files but none seem to work (CORs errors in most cases, screenshots made don't display the content of the iframes). The last thing I tried was : https://www.geeksforgeeks.org/how-to-take-screenshot-of-a-div-using-javascript/ Thank you for your answers. -
Is djangorestframework-jwt not good for http, https?
I am trying to build an API server for http and started off with djangorestframework and someone suggested using djangorestframework-jwt. However, I saw this from their homepage. Unlike some more typical uses of JWTs, this module only generates authentication tokens that will verify the user who is requesting one of your DRF protected API resources. The actual request parameters themselves are not included in the JWT claims which means they are not signed and may be tampered with. You should only expose your API endpoints over SSL/TLS to protect against content tampering and certain kinds of replay attacks. Does djangorestframework-jwt work for http and https? Is it safe? If not, what is the alternative? Is this the approach for authentication in a REST API? -
Need An Query from Django Model
I have created two models in Django from which I want to make a query First Parties Model class Party(models.Model): name = models.CharField(max_length=30, unique=True) contact = models.CharField(max_length=13) opening_Balance = models.FloatField() current_Balance = models.FloatField(blank=True, null=True) date = models.DateField(default=timezone.now, blank=True) Second is the dispatch where I will dispatch my product in inventory: class DirectCompanyRecieve(models.Model): date = models.DateField(default=timezone.now, blank=True) slug = models.SlugField(null=True, blank=True, default='none5lucky-cement') orderStatus = models.CharField(max_length=50, choices=[( 'Pending', 'Pending'), ('Received', 'Received'), ('Dispatched', 'Dispatched')], default='Pending') company = models.ForeignKey(Company, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) Destination = models.CharField(max_length=50) qty = models.IntegerField() rate = models.IntegerField() FrieghtPerTon = models.FloatField(null=True) Frieght_left = models.FloatField(null=True, blank=True) total_amount = models.FloatField(null=True, blank=True) company_lg_id = models.IntegerField(blank=True, null=True) wareHouse_lg_id = models.IntegerField(blank=True, null=True) Now I Need a query Like The 'BW', 'NW ', 'ML' etc are brand Names -
Django - conditional permissions - how to?
I'm trying to figure out how to (and if) use Django Groups/Permissions for cases when the permission depends on current user and it's attributes. class Team(..): ... class User(...): team = ... class Product(...): team = ... I have two Groups - admins and users. Let's say that I use DRF and I want any "admin" to see/fetch all product objects that belong to user's team and also update/delete. But I want regular user to be able only to retrieve (readonly) products. I'm thinking about creating permission: "can_edit_teams_products" Which would belong only to the admins group. But even if this was a common way to do that, how to check such permissions? It's not static, I need to get user.team when checking the permission. -
How to Use Materialize CSS Time Input with Django?
my current view - start_time = form.cleaned_data['start_time'] end_time = form.cleaned_data['end_time'] model - start_time = models.TimeField(auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) HTML - <input type="text" id="start_time" name="start_time" class="timepicker" placeholder="Start Time"> <input type="text" id="end_time" name="end_time" class="timepicker" placeholder="End Time"> Form Error I get : -
How do I use Graphql generated JWT to authenticate my rest_framework view?
I am using Graphql jwt to generate my token but I am not able to find a way to authenticate my rest_framework view using that token. -
Not able to use gensim module in Django
I have included the 2 import statements in my views.py from gensim.summarization.summarizer import summarizer from gensim.summarization import keywords However, even after I installed gensim using pip, I am getting the error: ModuleNotFoundError: No module named 'gensim.summarization' -
Django problem with form using action and not the if method == post in the view
So i am trying to add a value to the session dictionary because i wanted to make a cart/checkout for guests. This is the code in my views.py def productdetail(request, pk): Decks = decks.objects.get(id=pk) if request.method == 'POST': form = order(request.POST) if form.is_valid(): request.session['cart'] = [pk] else: form = order() return render(request, 'shop/single_product.html', {'deck': Decks, 'form': form}) And the code in my html <form action="{% url 'productdetailcart' deck.id%}" method="post"> {% csrf_token %} {{ form }} <input class="btn btn-lg btn-block btn-round btn-b" type="submit" value="Add To Cart"> Now my problem is that without the action in the form tag the session.['cart'] adds the value in the session which is what i want. But if i have the action to go to that url i only go to the url without adding the pk to the session.cart . Its like im forced to choose between going to the page or saving to session. -
Django Mongodb dumpdata not valid json format
We are using Django and MongoDB on our backend. We are also using Djongo to communicate with MongoDB. When running ./manage.py dumpdata > fixtures/db.json This produces a json dump that is not valid. The problem is that nested objects are not parsed correctly. { "model": "project.project", "pk": 1, "fields": { "name": "iiuyo", "project_type": "blank", "created_at": "2021-06-09T13:27:06.468Z", "modified_at": "2021-06-09T13:27:06.468Z", "account": 1, "status": "active" } }, { "model": "template.template", "pk": 1, "fields": { "data": "OrderedDict([('slides', [OrderedDict([('shapes', [OrderedDict([('type', 'image'), ('version', '3.6.3'), ('originX', 'left'), ('originY', 'top'), ('left', 0), ('top', 0), ('width', 960), ('height', 540), ('fill', 'rgb(0,0,0)'), ('stroke', None), ('strokeWidth', 0), ('strokeDashArray', None), ('strokeLineCap', 'butt'), ('strokeDashOffset', 0), ('strokeLineJoin', 'miter'), ('strokeMiterLimit', 4), ('scaleX', 1), ('scaleY', 1), ('angle', 0), ('flipX', False), ('flipY', False), ('opacity', 1), ('shadow', None), ('visible', True), ('clipTo', None), ('backgroundColor', '#fff'), ('fillRule', 'nonzero'), ('paintFirst', 'fill'), ('globalCompositeOperation', 'source-over'), ('transformMatrix', None), ('skewX', 0), ('skewY', 0), ('crossOrigin', ''), ('cropX', 0), ('cropY', 0), ('id', 'workarea'), ('name', ''), ('link', OrderedDict()), ('tooltip', OrderedDict([('enabled', False)])), ('layout', 'fixed'), ('workareaWidth', 600), ('workareaHeight', 400), ('src', ''), ('filters', [])]), OrderedDict([('type', 'chart'), ('version', '3.6.3'), ('originX', 'left'), ('originY', 'top'), ('left', 41.04), ('top', 33.12), ('width', 888.48), ('height', 450.2133070866142), ('fill', 'rgba(144,13,13,1)'), ('stroke', ''), ('strokeWidth', 1), ('strokeDashArray', None), ('strokeLineCap', 'butt'), ('strokeDashOffset', 0), ('strokeLineJoin', 'miter'), ('strokeMiterLimit', 4), ('scaleX', 1), ('scaleY', 1), ('angle', … -
OperationalError: no such table: django_content_type and django_session
I cannot access my app, when I enter the URL, it gives me the error OperationalError: no such table: django_session This usually means I need to migrate, or delete my sqlite database and redo migrations, so I did that multiple times. I deleted everything in the migrations folder and sqlite3.db and ran: python manage.py makemigrations app_name python manage.py migrate app_name No errors yet. Then after creating a superuser I run: python manage.py runserver It tells me 18 migrations have not been made, which I was able to fix with: python manage.py migrate --fake I try the site and again I get the no such table: django_session error. I read this thread Django: no such table: django_session and tried everything in it, including the approved solution, same error. Also, when I try to run the migrate command again, I get this error OperationalError: no such table: django_content_type so I went to this thread sqlite3.OperationalError: no such table: django_content_type once again, the solutions that worked for them did not work for me. This problem started after we migrated to MySQL, I tried to switch databases using a .env file, but ran into these problems, so I tried to switch back to sqlite … -
How to get a list of Items that have ManyToMany relationship to an object and Include some fields of the same object in the query set result
I would like to implement an efficient queryset from the model classes below. How to get a list of Items that have ManyToMany relationship to an object and include some fields of the same object in the query set result in each item? Model Classes class Property(models.Model): lr_no = models.CharField(max_length=30) class PropertyObjection(models.Model): objection_no = models.CharField(max_length=20) properties = models.ManyManyField(Property) A single objection has multiple properties as shown from the example below: objection = PropertyObjection.get(id=1) objection.properties.all() # Multiple properties My scenario is I want to use PropertyObjection model class to get all properties and include the `objection_no. (or is there any other effective way to do it) That is the result should be something like this: [ { "objection_no": "KF00988", "id": 1, "lr_no": "345/j" }, { "objection_no": "KN00988", "id": 2, "lr_no": "345/jK" } ] -
Python chashing sys for save statics files
I wanna use file cashing to save my statics file in the client device to speed up my site loading if anyone knows about it please help me to do this thanks -
Django Celery, not executing scheduled tasks
I'm developing a Django application to track crypto assets, what Im looking to do is, to take a snapshot of the user total value every 5 Days (X time). What i did for now: core/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.beat_schedule = { 'print': { 'task': 'app.tasks.test', 'schedule': 15 }, } app.conf.timezone = 'UTC' # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) core/settings.py: # -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us """ import os from decouple import config from unipath import Path import dj_database_url import django # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY', default='S#perS3crEt_1122') # SECURITY WARNING: don't run with debug turned on in … -
Font Face is not working except on Chrome
I use Lufga font for my web app but the font isn't working on Safari or Firefox. I've tried to use @font-face but it doesn’t seem to work, the text is still rendering in a default font. for context, I use Django on VS Code if it's relevant. this project is in development, not production. Here's my styles.css (P.S. when I cmd+click on the URL link I do end up in the right file, so I guess the location is good) @font-face{ font-family: 'Lufga'; src: url("../styles/Lufga-Regular.otf") format("Regular"); font-style: normal; font-weight: normal; } .Logo { position: absolute; width: 519.61px; height: 135px; left: calc(50% - 519.61px/2 + 0.3px); top: calc(50% - 135px/2 - 60px); } .ComingSoon { position: absolute; left: 38.59%; right: 38.59%; top: 51.88%; bottom: 44.78%; font-family: 'Lufga'; font-style: normal; font-weight: normal; font-size: 24px; line-height: 28px; /* or 117% */ text-align: center; color: #FFFFFF; } .Inquiries { position: absolute; width: 487px; height: 36px; left: calc(50% - 487px/2 + 0.5px); top: calc(50% - 36px/2 + 320px); font-family: 'Lufga'; font-style: normal; font-weight: normal; font-size: 18px; line-height: 28px; /* or 156% */ text-align: center; color: #FFFFFF; } .EmailLink { font-family: 'Lufga'; font-style: normal; font-weight: normal; font-size: 18px; line-height: 28px; color: #FFFFFF; } and here's … -
User self-hosted Database in Django
I have a Django project where the users can connect their own database as well as static file storage for security purposes. For example: when a user will signup into our system, they will ask for a database and a file storage address and credentials. After that, all the data for this user will store in his self-hosted Database as well as files also. I already checked the multi-database feature in Django but I guess it's not helpful for me -
Delete ManyToManyField if "items" was empty
I have Order Section and my models are like this : class OrderItem(models.Model): product = models.ForeignKey(Stock, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = jmodels.jDateField(auto_now=True) date_ordered = jmodels.jDateField(null=True) quantity = models.IntegerField(default=0, verbose_name='quantity') class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, related_name='item') date_ordered = jmodels.jDateField(auto_now=True,null=True) created_on_time = models.TimeField(auto_now_add=True,null=True) def get_cart_items(self): return self.items.all() def get_cart_total(self): return sum([item.quantity*item.product.price for item in self.items.all()]) My problem is that when in cart I delete all Items, and Items become empty, but still Order exist in my database. I want the whole of order would delete if Items was empty. -
django-export data foreign_id instead the real value
class Students(models.Model): MY_CHOICES = ( ('m', 'male'), ('f', 'female'), ) first_name = models.CharField(max_length=50,unique=False) last_name = models.CharField(max_length=50,unique=False) date_of_birth = models.DateField(null=True,blank=True,) gender = models.CharField(max_length=10,choices=MY_CHOICES) school= models.ForeignKey(school, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True,null=True,blank=True,) def __str__(self): return self.first_name + ' ' + self.last_name class Meta: verbose_name = 'Student' class StudentsResource(resources.ModelResource): class Meta: model = Students school= fields.Field(id='school', attribute='school', widget=widgets.ForeignKeyWidget(School, 'school')) Thank you for your help -
Django display dynamically HTML option depending on whether a checkbox is checked or not
As I said, I want to display dynamically HTML option depending on whether a checkbox is checked or not I tried this portion of code : <select id = "productPickerID" name = "product" multiple="multiple" required> {% for p in Products%} {% if "checked" in mycheckbox.checked %} <option value = {{c.productid}}>{{c.productname}}</option> {% endif %} {% endfor %} </select> <input type = "checkbox" id = "mycheckbox" checked="checked"> This code is working well without the if statement so I wonder how I could do that... Maybe use some javascript? or it's possible to do it directly with the templates... Thanks for answers -
Django field.choices + HTML. How do I get the word display, not id?
I have a this list in .models SIDES = ( [1, 'Attack'], [2, 'Defense'], ) side = models.PositiveSmallIntegerField( ("side"), choices=SIDES) and here i trying display on page 'Attack' or 'Defense', but he display only '1' or '2' {% for el in operators %} <div> <h3>{{ el.side }}</h3> </div> {% endfor %} How do I get the word display, not id? -
No information in a variable is being displayed on Django Website
I am a beginner in python and I am learning python. I am creating a Website using Django and faced a problem once trying to add information into the django website using for loops in Django HTML. The information from the below bolded code is not being displayed, can someone please help me out! <table class="table"> <thead> <tr> <th>Name</th> <th>Language</th> <th>Price</th> <th>Year Published</th> </tr> </thead> <tbody> {% for course in courses %} <tr> <td>{{course.name}}</td> <td>{{course.language}}</td> <td>{{course.cost_in_rupees}}</td> <td>{{course.year_published}}</td> </tr> {% endfor %} </tbody> -
Retrieve file name based on extension from path
I need to make a dynamic path for a file that I want to open. I need to retrieve the .tif file from within a path. this path is formed by a combination of a "STATICFILES_DIRS" from my settings.py and a field ccalled docId from my models.py that get filled from the views.py now, I'm very new to django so I really don't understand what I dont know (if this makes sense) my views.py has the following: from django.shortcuts import render import pyodbc # Create your views here. def home(request): conn=pyodbc.connect('Driver={sql server};' 'Server=server.domain.com;' 'Database=database;' 'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute("select top 100 docId, supplierName, invoiceNumber, reference from table") result = cursor.fetchall() return render(request, 'azolve/home.html', {'Azolve': result}) and my models.py has this: from django.db import models import os import fnmatch class Azolve(models.Model): docId = models.IntegerField supplierName = models.CharField(max_length=100) invoiceNumber = models.IntegerField reference = models.CharField(max_length=100) # for file_name in os.listdir(str(filePath)): # if fnmatch.fnmatch(file_name, '*.tif'): # docIdFileName = file_name and in my settings.py I have this part: STATIC_URL = '/static/' STATICFILES_DIRS = [ "//server1/Shared1/folder/ Migration Images/", ] so, to give an idea, each docId that gets retrieved is the name of a folder contained in the path "STATICFILES_DIRS " what I was trying to … -
How to organize test files on django 3.x and run single file tests?
I've been learning about django testing and would like to have several tests files that I would like to rename and place then in to a folder. How is the proper way to do it? In a single file test.py I used to call my test with the "python.manage.py tests appname" command. I tried to organize my tests files this way. app/tests/__init__py app/tests/test_something.py app/tests/test_something_else.py The problem is that when I organize them in several files I can't run a single test file. At this point all I can do is run then all with the command "python manage.py tests app test_something_else.py" but this it will also run test_something.py. I've already try the django documentation, but it hasn't help much because I think this example is for a single test.py file. (for an example app named animals) Run just one test case $ ./manage.py test animals.tests.AnimalTestCase Run just one test method $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak What am I doing wrong? -
How to fix psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block error
I have django app and separate script folder. Script folder has file that execute select * from table from DB which is connected to Django app. This scripts working in While=True I am using docker and scripts folder , django , postgresql are separate docker containers. I am restoring data to Postgresql container then making migrate. However, I am getting psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block this error from script container, ERROR: current transaction is aborted, commands ignored until end of transaction block this error from Postgresql container. How can I fix it? I have spent whole day could not find anything useful. Thanks in advance. -
I have a troubles whilefiltering by year and month in Django
I'm trying to filter queryset by month and date Here is a code: class FinalListView(generics.ListAPIView): serializer_class = FinalSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] def get_queryset(self): condition = Q() queryset = Final.objects.all() month = self.request.query_params.getlist('month') year = self.request.query_params.getlist('year') if month: if month != 'all': for a in month: condition |= Q(created_at__month=a) queryset = queryset.filter(condition) print (queryset) if year: if year != 'all': for a in year: condition |= Q(created_at__year=str(a)) queryset = queryset.filter(condition) print (queryset) return queryset When I'm filtering by year, it returns 200 response, but 0 objects When I'm filtering by month, I can't even get a 200 response, it returns 500 response