Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to process a CSV file from DB in Django
I am a newbie to Django. While working on a project I have stuck on CSV operations and radio forms. I have a file in my DB and it wants to read it in my views.py. Below is the model using which I m uploading the file in the DB. class Exam_Upload(models.Model): Id=models.IntegerField(primary_key=True) Question_file=models.FileField(upload_to='Documents/') where the CSV has the following columns: Question Option1 Option2 Option3 Option4 I want all these fields to be displayed as- The question should be the ordered list in the HTML staring from 1 and the options should be in the radio button. Where I can save the selected option in the DB. Your help will be really appreciated. -
How to create set object for a Django model with a many to many field?
I'am trying add many objects(Products) for my Database by ORM. In this script i want add some products def add_new_products(self): for i in range(100): Product.objects.create(name='kk',seller_id=5,description='kkkk',category_set=set([1,2]), image='/media/product_images/burger.jpg',manufacturer_id=2) return 'ff' without adding field category_set work fine with this instructions I tried to do but it didn't help on my case How to create an object for a Django model with a many to many field? shop/models.py Product model class Product(models.Model): name = models.CharField(max_length=200) seller = models.ForeignKey(to=Shop, related_name='products', on_delete=models.CASCADE) category_set = models.ManyToManyField(to=ProductCategory) description = models.TextField(blank=True) image = models.ImageField(upload_to='product_images/', null=True) manufacturer = models.ForeignKey(to=Manufacturer, related_name='products_manufactured_by', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name ProductCategory model class ProductCategory(models.Model): name = models.CharField(max_length=100, unique=True) # supercategory parent_category = models.ManyToManyField('self', related_name='subcategories', blank=True, symmetrical=False) image = models.ImageField(upload_to='product_category_images/', null=True) class Meta: verbose_name_plural = "product categories" def __str__(self): return self.name -
Instance of 'Flight' has no 'id' member
enter image description here Instance of 'Flight' has no 'id' member It seems like I have no id non the above class but it was working on the video I had watched -
Using Djongo with Django is failing to install database through migration scripts with in AWS DocumentDB
I have an existing project which I have developed Django rest-framework, Djongo (ORM) and MongoDB (4.0.2). Now, I have to move it to AWS DocumentDB. I have followed the instruction of index limit provided by AWS documentdb docs. https://docs.aws.amazon.com/documentdb/latest/developerguide/limits.html But still I am receiving following error messages djongo.sql2mongo.SQLDecodeError: FAILED SQL: ALTER TABLE "django_content_type" ADD CONSTRAINT "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE ("app_label", "model") Params: () Pymongo error: {'ok': 0.0, 'errmsg': 'namespace name generated from index name is too long', 'code': 67} Version: 1.2.33 Why are we getting this issue? Can someone help me ? -
Do i have to use WSGI, nginx for small applications
i have created a simple blog like application using django and want to host it on AWS. After going through some blogs i found that django in-built server is not good for production and i have to use nginx and a WSGI for hosting. Do i need to use nginx and WSGI even for simple applications ? -
Django: add `__str__` function in models.py doesn't work
I'm following the tutorial linked below to build a Django app. Here is the content in my models.py from django.db import models class Word(models.Model): word = models.CharField(max_length=100) def __str__(self): return self.word in interactive shell, Word.objects.all()[0].word can get the actual content, e.g >>> Word.objects.all()[0].word 'the meaning of the word get' Since I've already add the __str__ function, the code Word.objects.all() is supposed to output something like <QuerySet [<Word: the meaning of the word get>]> However, I just got the same one before I add __str__ function. <QuerySet [<Word: Word object (1)>]> I've already restart everything but didn't get what is expected to be. Could someone help me with this? video: https://youtu.be/eio1wDUHFJE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=428 -
How to fetch data from other table django rest framework
I have a cartmodel, cartitem and offlinecheckout model. I want to display cartitem instead of cartmodel id, I want to display all the cartitem data which have cart_id = offlinecheckout cart_id. But I got this response. I tried a lot but didn't get. Anybody will please help me. views.py class GetAPI(APIView): def get(self, request, *args, **kwargs): serializer = OfflineSerializer() return Response(serializer.data) models.py class OfflineCheckOut(models.Model): billing_name = models.CharField(max_length=254) billing_phone_no = models.CharField(max_length=15) user = models.ForeignKey('accounts.User', on_delete=models.CASCADE) cart = models.ForeignKey('cart.CartModel', on_delete=models.CASCADE) cartitem = models.ManyToManyField(CartItem, blank=True) # time_slot = models.ForeignKey('category.TimeSlot', on_delete=models.CASCADE) address = models.ForeignKey('cart.CustomerAddress', on_delete=models.CASCADE) status_choice = [ ('0', 'Offline'), ('1', 'Online') ] status = models.CharField(max_length=3, choices=status_choice, default=0) # date = models.DateField() date = models.DateField() time_slot = models.ForeignKey('category.TimeSlot', on_delete=models.SET_NULL, null=True, blank=True) order_id = models.CharField(max_length=254, blank=True) # date = models.DateField() razorpay_payment_id =models.CharField(max_length=254, blank=True) razorpay_signature = models.CharField(max_length=254, blank=True) paid = models.BooleanField(default=False) service = models.ForeignKey('service.ServiceProvider', on_delete=models.SET_NULL, null=True, blank=True) class CartModel(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE) status_choice = [ ('1', 'open'), ('2', 'closed') ] status = models.CharField(max_length=2, choices=status_choice, default=1) validated = models.BooleanField(default=False) def __str__(self): return self.user.username @property def total_price(self): return self.cartitem_set.aggregate( total_price=Sum(F('quantity') * F('price')) )['total_price'] or Decimal('0') class CartItem(models.Model): cart = models.ForeignKey('CartModel', on_delete=models.CASCADE) user = models.ForeignKey('accounts.User', on_delete=models.CASCADE) service = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE) defects = models.ForeignKey('category.Defects', on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price … -
Run and validate online compiler against test cases
I made a online compiler (python/Django web app) using hackerearth's API. it's just a normal compiler you can write and run the codes. but I want to add questions and validate the output on that particular question. i.e if output is not according to that particular question then it should give an error. the problem is i don't know the logic(how to validate against test cases). here is the code for API connection that send and receive the JSON dictionary from hackerearth. this is provided by hackerearth itself def runCode(request): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': '*********bbbb9496f094d690*********', 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } if 'input' in request.POST: data['input'] = request.POST['input'] r = requests.post(RUN_URL, data=data) return JsonResponse(r.json(), safe=False) else: return HttpResponseForbidden() the above code just give a blank compiler to write and run anything and does not provide validation. i hope you got my point. and please contact me if you have any idea about this thing, even if you have done this with other language and not only python/Django -
Adding online chat to existing Django website
I have developed a website that is currently working. Is there any Django package which I can add to my website so I can have online chat with website users? -
RecursionError : maximum recursion depth exceeded while calling a Python object
I am getting an error in admin console while trying to open a model . How to fix it Model.py class TbSysEmailconfig(models.Model): id = models.ForeignKey('self', models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase. emailtemplateid = models.ForeignKey(TbMasEmailtemplate, models.DO_NOTHING, db_column='EmailTemplateId') emailfromname = models.CharField(db_column='EmailFromName', max_length=100, blank=True, null=True) emailfrom = models.CharField(db_column='EmailFrom', max_length=100) credential = models.CharField(db_column='Credential', max_length=100) password = models.CharField(db_column='Password', max_length=100) post = models.IntegerField(db_column='Post', blank=True, null=True) host = models.CharField(db_column='Host', max_length=100) priority = models.CharField(db_column='Priority', max_length=100, blank=True, null=True) maximumday = models.IntegerField(db_column='MaximumDay', blank=True, null=True) maximumminute = models.IntegerField(db_column='MaximumMinute', blank=True, null=True) systemid = models.IntegerField(db_column='SystemId') partfiletemplate = models.CharField(db_column='PartFileTemplate', max_length=500, blank=True, null=True) comment = models.CharField(db_column='Comment', max_length=1000, blank=True, null=True) ismaildefault = models.SmallIntegerField(db_column='IsMailDefault') maildefault = models.CharField(db_column='MailDefault', max_length=4000, blank=True, null=True) createddate = models.DateTimeField(db_column='CreatedDate') createdbyuserid = models.IntegerField(db_column='CreatedByUserId') updateddate = models.DateTimeField(db_column='UpdatedDate') updatedbyuserid = models.IntegerField(db_column='UpdatedByUserId') delflag = models.SmallIntegerField(db_column='DelFlag') class Meta: db_table = 'TB_SYS_EmailConfig' admin.py from django.contrib import admin from .model import TbSysEmailconfig #Modifire admin.site.register(TbSysEmailconfig) When I select some item it show this error -
django sphinx compilation error: index.rst not found and WARNING: Unknown directives
Please I'm facing a weird mistake. Here I have a Django project that runs very well locally, I even generated the documentation and everything is going perfectly well. The problem is that when I import the project in https://readthedocs.org/ the compilation fails, I tried almost everything, but always the same problem I use django == 2.2 python == 3.7.8 My project structure: - Myproject -- docs -- build -- source - conf.py - index.rst - file.rst - another_file.rst make.bat Makefile requirements.txt -- MyprojectDir -- MyappDir My conf.py file inside my source directory look like this: # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- import os import sys import django cwd = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(cwd, '../../'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'vtcvlp.settings' … -
how can I avoid getting duplicates in my header title?
I am trying to format a component where it takes a category followed by a course title. my code currently works, but its adding category + course per course when it should be category + (all courses from that category), how can I fix simple error or retrieve all categories followed by its courses? class Course(models.Model): cuid = models.UUIDField(primary_key=True, default=generate_uuid, editable=False, unique=True) slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() price = models.IntegerField() category = models.ForeignKey(Category,on_delete=models.CASCADE) class CourseListView(ListView): template_name = 'site/courses.html' model = Course {% block page-content-1 %} {% for object in object_list %} {{object.category}} <ul> <li>{{object}}</li> </ul> {% endfor %} {% endblock %} TAG 1 Windows security TAG 2 child_1 TAG 1 112 -
How to display Jsignature field as image using Django templates
Jsignature feild in stored in database in this way user_signature = [{"y": [25, 26, 33, 43, 51, 60, 66, 70, 75], "x": [99, 103, 104, 105, 105, 105, 105, 106, 106]}, {"y": [46, 44, 44, 44, 46, 49, 51, 52, 53, 55, 59, 60, 61, 63, 65, 66], "x": [106, 111, 116, 121, 124, 122, 119, 114, 108, 105, 107, 112, 118, 122, 125, 129]}, {"y": [61, 65, 66, 65, 63, 61, 58, 54, 52, 54, 55, 58, 58, 63], "x": [121, 125, 129, 133, 136, 139, 143, 141, 137, 141, 145, 148, 153, 154]}] Now how can i display this user_signature as image in django template. I tried in this way <img src="data:image/png;base64,{{request.user.user_signature}}" -
Can we deploy keras model on web using Php?
Well currently i am learning machine learning and i found out that we deploy keras model using python framework django or flask? Why we can't Deploy using Php? -
How can I update first_name, last_name & email of Django model User and update other field in separate models
I have been learning the Django tutorial for a few weeks using YT, StackOverflow, Django documentation, and other sources. So, maybe my question goes out of the sense. I hope you will understand my question. If anything is a mistake on my code or you want to give me some suggestions, then reply to me. I make the site locally on my computer. First of all, I have created a signup page and login page using Django Model. After User login the site, In profile settings, I have created form field like first_name, last_name, email, mobile_number, date_of_birth, zip_code, address, website, bio, etc. I have models.py for Account setting from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) profile_photo = models.ImageField(upload_to='profile', null=True) mobile_number = models.PositiveBigIntegerField(null=True) date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True) zip_code = models.IntegerField(null=True) address = models.CharField(max_length=225, null=True) website = models.URLField(max_length=100, null=True) bio = models.CharField(max_length=225, null=True) In forms.py from django import forms from .models import Account class AccountForm(forms.ModelForm): class Meta: model = Account fields = '__all__' In templates <form class="form mx-auto my-5" method="POST" action="" enctype="multipart/form-data"> <input name="user" type="hidden" value="{{request.user.id}}" required> <div class="form-row"> <div class="col form-group"> <label for="first_name" class="font-weight-bold">First name (required):</label> … -
How to stop function and run other after x seconds in Django?
So basically I have a view which runs a function that is written in another file. Since I don't want the function running any longer than 25 seconds, is there any way for me to skip the function after it has ran for 25 seconds and just simply return the redirect reverse? Here is what my view looks like def radio(request): song_search = request.POST.get('search').capitalize() request.session['song'] = song_search if models.Genre.objects.filter(Song=song_search): song_query_createobject(request) else: song_query_createobject(request) song_finder(request) return redirect(reverse('songresult')) -
Django ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead
I've read through plenty of questions with this same error message but I could not find the same case as mine. Usually you would see if statement with no returns but this doesnt have if statements. error Traceback (most recent call last): File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response raise ValueError( ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead. There are other views as well but I dont think they are related view.py def profile(request, name): try: user = User.objects.get(username=name) except User.DoesNotExist: return render(request, "cookbook/error.html") return render(request, "cookbook/profile.html", { "pageuser": user }) profile.html {% extends "cookbook/layout.html" %} {% block body %} <h2>{{ user.username }}</h2> {% endblock %} -
Randomly pick X objects with distinct names
The following attempt: Article.objects.filter(category__id="b5e20323-8cec-413a-b405-342b3809f9a4").distinct('title').order_by("?") Gives me: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions I tried to drop to raw SQL. So I tried: SELECT * FROM (SELECT DISTINCT title from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 This works but I need to add an additional field to to the title. If I change my raw query to: SELECT * FROM (SELECT DISTINCT title, id from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 All of a sudden the DISTINCT keyword has no effect. How can I overcome this? -
Django table with query results and computed data
I am trying to list the last entry a user makes in a table along with the number of entries the user has made. The query I have so far gets me the last entry (there can only be one active at a time) data = Student.objects.filter(session=session, active=True) The objects are then sent over and displayed in a table {% for item in data %} <tr> <td>{{ item.name }}</td> <td>{{ item.category }}</td> <td align="center">{{ [count here]}}</td> </tr> {% endfor %} I would like the count for the number of times the user's name appears in the database in the same row as the object data itself. I would like the count displayed where "count here" is as above. -
why do I get "ModuleNotFoundError: No module named 'model-name'" error when I run my Django project after moving to python3.8.5?
I have a Django project which worked fine, but then I installed Python3.8.5, uninstalled the python27 I was using before, and installed Django 3.1.1 on my computer. Now when I run my project I get the error "ModuleNotFoundError: No module named 'model-name'". Seems like it can't find my models. How do I get my project to run properly? -
How to send POST request in order to add an object that has ForeignKey in Axios and Django Rest Framework
Code models.py class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('メールアドレスは必須項目です。') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) # Django提供のカスタムユーザーのFieldを決定 class User(AbstractUser): # AbstractUserでpasswordは定義済みのため、ここではpasswordを再定義しない(DBにはちゃんと保存される。) username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) profile = models.TextField(max_length=800, blank=True, null=True) icon = models.ImageField(blank=True, null=True) background = models.ImageField(blank=True, null=True) # AbstractUserはfirst_name,last_nameを保持しているため無効化 first_name = None last_name = None is_staff = models.BooleanField( ('staff status'), default=True, help_text=( '管理サイトへのアクセス権を持っているかどうか'), ) is_active = models.BooleanField( ('active'), default=True, help_text=( 'ユーザーがアクティブかどうか' ), ) is_superuser = models.BooleanField( ('superuser status'), default=True, help_text=( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) # createdAt, updatedAt は時系列順等に並べたいモデルに付与 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELD = ["username", "email"] class Meta: db_table = "users" # ====== ======= ====== ====== ====== ====== ======= ======= class Bland(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: db_table = "blands" # … -
compare fields in two different django models
I am trying fill a field (hours) in Employee model based on the aggregate of a field (time_worked) in Timesheet model. MODELS.PY class Employee(models.Model): ... user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='employees') hours = models.DurationField(null=True, blank=True) class Timesheet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True,) time_worked = models.DurationField(null=True, blank=True) How do add up the time_worked in Timesheet model of only employee A and insert the results into hours column of Employee model for employee A? -
Django Static - Google Cloud Storage - CDN
I am still new with serving my Django static/media files to Google cloud storage. It's working now but I am not sure if this is right or is this enough already, do I still need to use CDN like Cloudfront or other similar services? I am really confused and any recommendation would be much appreciated. Below is my configuration. import os from google.oauth2 import service_account BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'extras/google-storage.json') ) STATICFILES_STORAGE = 'extras.storage_backends.GoogleCloudStaticFileStorage' DEFAULT_FILE_STORAGE = 'extras.storage_backends.GoogleCloudMediaFileStorage' GS_PROJECT_ID = 'project_id' GS_STATIC_BUCKET_NAME = 'static_bucket' GS_MEDIA_BUCKET_NAME = 'media_bucket' STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) GS_DEFAULT_ACL = 'publicRead' I am using the following: Django 2.2 Python 3.7 Thanks you so much! -
select serial number from the list given for user in django
i wrote a Django app but it's not complete. it's a kinda CRM app for Controlling my customers. how does it work? in the client section, I enter the customer's name, phone number, email, name of the app that he/she bought, and the SERIAL NUMBER image_one when I create a new user I have to manually type the serial number image_two but I don't want that. WHAT I Want?? in the product section, after I enter the product's name, I want a place to enter 1000 serial numbers ( serial numbers are generated in other app and that app gave me a text file with thousands of serial numbers). I want something like this in Django App: image_tree now the final part : in the client section, when I chose the product name (One product or more), I want a serial number picked up from the list and never use for another user. image_foure I know my English is bad. sorry for that :( please help any idea how I can do this? -
Python script to django html output
I want to put python script output to HTML using Django with a button. When the user clicks the button again and it changes the random number again. import random num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print(random.choice(num))