Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When typing: print(Topic.objects.all()) , I get the error message: django.db.utils.OperationalError: no such table:
hello after running this code in a models.py file: from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, ) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey( 'Webpage', on_delete=models.CASCADE, ) date = models.DateField() def __str__(self): return str(self.date) As a note, I was having trouble with migrations as I kept getting error messages related to the .ForeignKey so I got the following code from some other forum, and it finally ran the migrations but I'm not sure if this code is the problem... topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, ) After successful migrations, I ran python manage.py migrate; everything seemed to migrate fine. Then I ran python manage.py shell then I ran: >>> from first_app.models import Topic >>> print(Topics.objects.all()) but got the following error: OperationalError: no such table: first_app_topic here's the full read out: Traceback (most recent call last): File "/Users/homepage/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/db/backends/utils .py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/homepage/opt/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/db/backends/sqlit e3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: first_app_topic The above exception was the direct cause of the following exception: Traceback (most recent … -
Uncaught ReferenceError: jQuery is not defined in Django
I have a simple Django project. I want to add material design bootstrap in it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> {% load static %} <title>Material Design for Bootstrap</title> <!-- MDB icon --> <link rel="icon" href="{% static 'assets/images/mdb-favicon.ico' %}" type="image/x-icon" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" /> <!-- Google Fonts Roboto --> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" /> <!-- MDB --> <link rel="stylesheet" href="{% static 'assets/css/mdb.min.css' %}" /> <!-- Custom styles --> <style></style> </head> <body> <!-- Start your project here--> <header> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top"> <div class="container" style="height: 100px; "> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarExample01" aria-controls="navbarExample01" aria-expanded="false" aria-label="Toggle navigation" > <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarExample01"> <ul class="navbar-nav mr-auto mb-2 mb-lg-0"> <li class="nav-item active"> <a class="nav-link" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> <!-- Navbar --> <!-- Jumbotron --> <div class="p-5 text-center bg-light" style="margin-top: 100px;"> <h1 class="my-1 h4">The title of our atricle</h1> </div> <!-- Jumbotron --> </header> <!-- End your project here--> <!-- Main layout --> <main class="my-4"> <div class="container"> <div class="row"> <div … -
Send email after returning response to user in django
I want to send verification email to new users. But because of slow connection it takes a long time to send an email and user will see a CONNECTION TIMED OUT error. I want to return the response to user and after that send the email. I already tried StreamingHttpResponse and using yield. But it returned a creepy response instead of the response I wanted. I prefer to do it using function view but there is no problem if I HAVE to use class view. What should I do? from django.shortcuts import render from django.http import HttpRequest def sign_up (request: HttpResponse): method = request.method if method == 'GET': # checking cookies return render(request, "template name", context) if method == 'POST': # validating data if unvalid_data: return render(request, "template name", context) # saving data return render(request, "template name", context) # sending email -
How to specify form with specific user type in DetailView Django?
In my DetailView I want to specify form for specific user type like if user is a teacher then use AttendanceForm and if user is a student then use StudentleaveForm. I have tried get method but it failed. How can I do that? here is what I have tried: class Class_detailView(LoginRequiredMixin, FormMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html" def get(self, request, *args, **kwargs): if request.user.is_teacher: form_class = AttendanceForm elif request.user.is_student: form_class = StudentLeaveForm return super(Class_detailView, self).get(request, *args, **kwargs) here is the error I got 'NoneType' object is not callable -
"[Site]" in email subject line when django-allauth sends email
I'm using django-allauth for user authentication in my Django project. Right now account emails are being sent through MailGun. When a password reset or confirm account email comes through, [Site] is printed in the subject line of the email as such: [Site] Password Reset E-mail How can I remove this? Thanks. -
Get user authentication or session or cookie data from php to django server
I have a php server running and using a django-dash app server as an iframe. My issue is that I want to the user to have access of the django server only if he is authorized by the credentials had given in the php server. So the django server will not have the ability to run standalone if he hasn't receive the user authentication. I tried to filter the session data that are created by the php and written in the database but my problem is how to filter the exact parameters in the django server. Do you consider any other solution to pass the authenticated data or session or cookies from php to django in order to examine the django server if the user is authenticated and then will be depict its content?? -
Wagtail modeltranslation doesn't work with DEBUG = False
I have a problem with absent redirection to the default language for the multilanguage wagtail site. If I set DEBUG = False on production, I got Internal server error, because redirection to url with language postfix is absent. If DEBUG = True everything works fine. I'm using wagtail_modeltranslation https://progtribe.com/ - doesn't work https://progtribe.com/ua - works # urls.py from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( url(r'', include(wagtail_urls)), path('dj_admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), ) -
Create function and validated_data in Django rest
This is my class and create function in serializers.py. I dont understand this create function and validated_data on serializers.py . I mean whats is purpose and what it is doing here? It is necessary or optional. Please explain in lay man terms. User = get_user_model() class UserCreateSerailizer(ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'email', ] # fields ="__all__" extra_kwargs = { "password":{"write_only":True} } This is my create function with validated data. But I have no idea of its purpose. def create(self, validated_data): username = validated_data ['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username = username, email = email ) user_obj.set_password(password) user_obj.save() return validated_data -
show data according to login user in admin template if login user is not admin but it's staff?
I am create two user in django admin this and this two user is able to login in admin panel. and both are user is create a blog so on display list i want to set only login user is can seen list of blog that is add by him and admin can seen all data. let's i give you a situation. suppose you create a blog site befour 1 year is this site only a one user that is super user and it's create a blog but after some time you feel that you don't have time to operate that. and you don't want to create other user panel. so at this point you dissed that i create two new staff user and give the permission that he can create blog and edit blog but thy can not delete that blog. but there are no any permission for view list of blog. so they can view all blog but user A have a permission for edit so he can edit the blog that is created by user B so that why we want to set view permission according to login user so thy can only see blogs that is … -
How can I get a particular value from sqlite using ajax in django
I want to fetch database object values. When I enter a title value to the field (newvalue) and display the corresponding descreption value to the template field (appendlabel). I know one possible solution could be Ajax, I trying for last few days but I can't get it. Below is the code, please help with the implementation. Here is my AJAX code <script> $("#getvalue").click(function () { $.ajax({ type: "GET", url: '{% url "getvalue" %}', data: { title: $('#newvalue').val(), }, dataType: 'json', success: function (response) { $('#appendlabel').append(response.alldata.description) } }); }); </script> Template part <button id="getvalue" type="button" class="btn btn-primary"> Get</button> <input id="newvalue" name="newlabel"> <label id="appendlabel"></label> Views.py def getvalue(request): descreption = request.GET.get('title', None) ob=Post.objects.get('select description from newapp_post where title=%s',[descreption]) return JsonResponse({'alldata': ob}, status=200) urls.py path('getvalue', views.getvalue, name='getvalue'), models.py class Post (models.Model): title = models.CharField(max_length=50) description = models.TextField() -
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> …