Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove this big error while creating super user?
I have three apps in django. When I makemigrations, it only added one app after migrate to database. After using command python maange.py createsuperuser, it is giving me error. I am using mongodb database. djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s) Params: ['pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', None, True, 'bilalkhangood4', '', '', '', True, True, datetime.datetime(2019, 8, 21, 6, 41, 58, 512948)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: username_1 dup key: { : "bilalkhangood4" }', 'op': {'id': 4, 'password': 'pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhangood4', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 8, 21, 6, 41, 58, 512948), '_id': ObjectId('5d5ce7b62dd232236aa5a188')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} -
How I can write only one django orm query?
The goal is to filter Fitness objects by specified SportType objects, i.e. all Fitness objects which contains at least one specified SportType object as foreignkey. Here is my models and example: class Fitness(models.Model): name = models.Charfield(max_length=100) class SportType(models.Model): name = models.CharField(max_length=100) class FitnessSportType(models.Model): fitness = models.ForeignKey(Fitness, related_name='sport_type_set') sport_type = models.ForeignKey(SportType, related_name='fitness_set') f1 = Fitness.objects.create(name='foo') f2 = Fitness.objects.create(name='bar') f3 = Fitness.objects.create(name='goo') s1 = SportType.objects.create(name='a') s2 = SportType.objects.create(name='b') s3 = SportType.objects.create(name='c') FitnessSportType.objects.create(fitness=f1, sport_type=s1) FitnessSportType.objects.create(fitness=f1, sport_type=s2) FitnessSportType.objects.create(fitness=f2, sport_type=s1) FitnessSportType.objects.create(fitness=f2, sport_type=s3) FitnessSportType.objects.create(fitness=f3, sport_type=s2) SOME_MAGIC_FUNCTION([s1, s3]) = [f1, f2] P.S: sorry for bad English :) -
Retrieve data in API based on ID in Django Rest Framework
I made an APIView of a django function Views.py class TakenQuizListViewAPI(APIView): def get(self, request, *args, **kwargs): queryset = self.request.user.supplier.taken_quizzes.select_related('quiz', 'quiz__truck_type').order_by( 'quiz__posted_on') query = suppliertakenquizSerializer(queryset, many=True).data return Response(query) and it returns data like this: { "id": 5, "score": 0.0, "date": "2019-08-20T13:31:15.156691", "least_bid": 99, "confirmed": "Not Confirmed", "supplier": 32, "quiz": 16 }, How can I get all the details of the quiz in the API ?? Expected Output: { "id": 5, "score": 0.0, "date": "2019-08-20T13:31:15.156691", "least_bid": 99, "confirmed": "Not Confirmed", "supplier": 32, "quiz": { "foo": "", "bar": "" } }, serializer: class suppliertakenquizSerializer(serializers.ModelSerializer): class Meta: model = TakenQuiz fields = "__all__" Model.py: class TakenQuiz(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) least_bid = models.IntegerField(default=0) confirmed = models.CharField(max_length=100, default='Not Confirmed') -
Django how to save logs in transaction.atomic()
Suppose you are processing order when payment is confirmed. with transaction.atomic(): do something like subtract stock log stuff in DB so that we can later investigate what went wrong if something goes wrong: # this line of code may reside in a function nested deep raise do more to finalize the order When there's an exception, db rolls back fine, but I want the logging to be persisted in the db. I'm thinking creating a celery task and do the logging the background, (not sure if it's going to work). Are there better alternatives? -
Copy the data from one ID to another ID in same table in django ORM
Copy the data from one ID to another ID in same table in django ORM -
How do I pass the primary key from one model to another model and display some fields of the first model in the template?
I have 2 models, 'Candidate' and 'Tracker' . I want to add the candidates to the tracker list if I wish to. The tracker has some additional fields. However in the tracker template I wish to display some details of the candidate like name, phone etc. Basically the tracker page contains added candidates with some extra details about them. Candidate models.py class Candidate(models.Model): candidate_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.EmailField() current_company = models.CharField(max_length=100) current_designation = models.CharField(max_length=100) def __str__(self): return self.candidate_name def get_absolute_url(self): return reverse('candidate-detail', kwargs={'pk': self.pk}) Tracker models.py class Tracker(models.Model): candidate_name = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='candidates') position_applied = models.CharField(max_length=100) current_CTC = models.CharField(max_length=100) expected_CTC = models.CharField(max_length=100) def __str__(self): return self.position_applied def get_absolute_url(self): return reverse('tracker-detail', kwargs={'pk': self.pk}) views.py files.. class TrackerCreateView(LoginRequiredMixin, CreateView): model = Tracker fields = ['current_CTC', 'expected_CTC', 'position_applied', 'candidate_name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CandidateCreateView(LoginRequiredMixin, CreateView): model = Candidate fields = ['candidate_name', 'phone', 'email','current_company', 'current_designation'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Uptil now I have just included candidate as a foreign key. But this requires selecting the candidate name from the dropdown which is not practical. How can I display the name,phone,email etc. in the tracker list? I have a button on the … -
local variable 'board' referenced before assignment
I am getting an unbound local error while creating website in Django from django.shortcuts import render, get_object_or_404 from .models import Board from django.http import HttpResponse # Create your views here. def home(request): boards = Board.objects.all() return render(request, 'home.html', {'boards' : boards}) def board_topics(request,pk): board = get_object_or_404(board, pk=pk) return render(request,"topics.html",{'board' : board}) boards = Board.objects.all() return render(request, 'home.html', {'boards' : boards}) -
How can I change this SQL? Django SQL syntax error: near from
I don't know how can I change this. This def is in Desktop\DjangoProject\dj_board\board\views.py boardList = DjangoBoard.objects.raw('SELECT Z.* FROM(SELECT X.*, ceil( rownum / %s ) as page FROM ( SELECT ID,SUBJECT,NAME, CREATED_DATE, MAIL,MEMO,HITS \ FROM BOARD_DJANGOBOARD ORDER BY ID DESC ) X ) Z WHERE page = %s', [rowsPerPage, current_page]) near "FROM": syntax error -
How to fix, 'PyInstallerImportError: Failed to load dynlib/dll', while executing executable file in docker?
I created the executable file for a Python-Django application using PyInstaller. I am trying to run the executable file in docker, which gives me the error. This is the dll which is missing: /home/user/app/mxnet/libmxnet.so' , which is already present in the .exe file folder. The exe file gets executed when not run using Docker. Tried manually installing mxnet and running the docker image, but still not working import mxnet Error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2a02dde510> Traceback (most recent call last): File "PyInstaller/loader/pyiboot01_bootstrap.py", line 149, in __init__ File "ctypes/__init__.py", line 347, in __init__ OSError: libgomp.so.1: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django/utils/autoreload.py", line 227, in wrapper File "django/core/management/commands/runserver.py", line 125, in inner_run File "django/core/management/base.py", line 359, in check File "django/core/management/base.py", line 346, in _run_checks File "django/core/checks/registry.py", line 81, in run_checks File "django/core/checks/urls.py", line 16, in check_url_config File "django/core/checks/urls.py", line 26, in check_resolver File "django/urls/resolvers.py", line 254, in check File "django/utils/functional.py", line 35, in __get__ File "django/urls/resolvers.py", line 405, in url_patterns File "django/utils/functional.py", line 35, in __get__ File "django/urls/resolvers.py", line 398, in urlconf_module File "importlib/__init__.py", … -
Is django rest framework overtaking django with the increasing popularity of javascript frameworks?
I have learning django since 2-3 months and I did pretty good web apps with it.But nowadays with the iincreasing popularity of Javascript frameworks like Vue.js,Angluar and React.js I am not using django anymore.For this i use django rest framework.I know django rest is used for API. So with django it was very easy to render html templates,to do all other things or to make some logics but with django rest framework i am not being able to do so .Everything being new to me with django rest framework.I lost that how i can render html pages and also the logics are different from django. There is no any need of django forms templates anymore. So my question is should i be more focused on django rest framework rather than django with the increasing popularity of frontend frameworks? -
Based on the client id process should allocate
I got the below error when I fetch the process from client_process table invalid literal for int() with base 10: 'client_id' models.py This is my models file the client and client_process are foreign key class Client_files(models.Model): Date = models.DateTimeField(default=datetime.now, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True) File_Name = models.FileField() Pages = models.IntegerField(null=True) Count = models.IntegerField(null=True) Status = models.BooleanField(default = False) class Meta: db_table : 'client_files' views.py def pdf_upload(request): pdf = Client_files.objects.all() print(pdf) obj = Client_files.objects.values('client_id') print(obj) for i in range(len(obj)): client = Client_Process.objects.filter(client_id__in=obj[i]) print(client) obj[i].client = client if request.method == 'POST': form = Upload_files(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/pdf/upload/') else: form = Upload_files() return render(request,'uploadpdf.html',{'form':form, 'pdf':pdf,}) -
What is the meaning of single underscore as a function in python? [duplicate]
This question already has an answer here: What is the purpose of the single underscore “_” variable in Python? 4 answers I recently started working on python and have seen a lot of _ being used. I understand that _ is used to ignore values for e.g. name, _ , shape = get_fruit() # returns a tuple. However, I couldn't get many articles on _ functions e.g. from django.utils.translation import gettext as _ Why is _ used here instead of simply using gettext() ? -
Django REST API framework without models
I created a simple html page which allows me to upload an image and store it in the directory without the use of a model. My aim is to use the REST API framework and display that particular image uploaded in the REST API i.e {"image": "uploaded_image_by_user"} How can I create the POST and GET methods for this REST API? I tried doing it like this but it's not working properly. Is there a proper way to do it? Or rather, does anyone know a basic way of creating a REST API without models? FYI, I'm new to Django My current code: views.py from django.shortcuts import render from django.db import models from django.views.generic import View, TemplateView, CreateView from image_app.forms import ImageForm from django.contrib.messages.views import SuccessMessageMixin import requests from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from image_app.serializers import ImageSerializer from django.http import Http404 import os, sys from rest_framework.parsers import FileUploadParser from django.http import HttpResponseRedirect from django.core.files.storage import FileSystemStorage from django.conf import settings from django.contrib import messages class BaseView(TemplateView): template_name = "base.html" def upload(request): if request.method == 'POST': filename = rename() uploaded_file = request.FILES['image'] fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) name = … -
How to do Foreign Key reverse lookup with related name DJANGO2.1
How can i possibly get the result mentioned below of a ForeignKey reverse lookup? I have seen other similar questions but I believe I will be able to understand this concept with my current problem. Below are my tables. class Invoice(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_invoices') number = models.IntegerField(default=invoice_number, null=True) select = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey('Service', on_delete=models.CASCADE, related_name='invoice_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) class Service(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='services') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) What i am trying to achieve is When i access the detail page of Invoice from the list of invoice: I want to be able to access information from Service table and display name, description, price fields from Service table. def invoice_detail(request, id): invoice = get_object_or_404(Invoice, id=id) context = {'invoice':invoice} return render(request, 'product/dashboard/invoice_detail.html', context) Not sure whether this is the right way to do it or should I just create a ManytoMany Relationship. Any help would be much appreciated. -
Testing abstract models - django 2.2.4 / sqlite3 2.6.0
I'm trying to test some simple abstract mixins using django 2.2.4/sqlite3 2.6.0/python 3.6.8. Currently I'm having issues deleting a model from the test database using the schema editor. I have the following test case: from django.test import TestCase from django.db.models.base import ModelBase from django.db import connection class ModelMixinTestCase(TestCase): """ Test Case for abstract mixin models. """ mixin = None model = None @classmethod def setUpClass(cls) -> None: # Create a real model from the mixin cls.model = ModelBase( "__Test" + cls.mixin.__name__, (cls.mixin,), {'__module__': cls.mixin.__module__} ) # Use schema_editor to create schema with connection.schema_editor() as editor: editor.create_model(cls.model) super().setUpClass() @classmethod def tearDownClass(cls) -> None: # Use schema_editor to delete schema with connection.schema_editor() as editor: editor.delete_model(cls.model) super().tearDownClass() Which can be used like this: class MyMixinTestCase(ModelMixinTestCase): mixin = MyMixin def test_true(self): self.assertTrue(True) This does allow for a model to be created and tested. The problem is that within ModelMixinTestCase.tearDownClass, connection.schema_editor() is unable to disable constraint checking which is done in django.db.backends.sqlite3.base using: def disable_constraint_checking(self): with self.cursor() as cursor: cursor.execute('PRAGMA foreign_keys = OFF') # Foreign key constraints cannot be turned off while in a multi- # statement transaction. Fetch the current state of the pragma # to determine if constraints are effectively disabled. enabled = … -
Django: runserver_plus and werkzeug: How to execute multiline code like if or for
I am working on DJango and using runserver_plus and werkzeug for some debugging purpose. I opened a interactive debugger to execute some python commands. I wanted to execute the following commands: items = [] for key in dir(obj): try: items.append((key, getattr(obj, key))) except Exception: pass I am not able to copy paste multiline code and run. I can paste only one line at a time. So is this possible to paste the above code -
Ways to link two panels in different html templates
I am doing a patient-hospital app. I want to implement a function that the receptionist and the doctors can view schedules on that day. If the receptionist on her pc click on the panel which represents that patient check in for his or her appointment, the panel will change color to red. At the same time, the doctor's pc can see the change as well. I think this function looks similar to the Observer pattern but I don't know how to implement it. my Schedule model class Schedule(models.Model): checked_in = models.BooleanField(default=False) patient = models.OneToOneField('Patient', models.DO_NOTHING, db_column='patient') date = models.DateField(db_column='date&time') # Field renamed to remove unsuitable characters. time = models.TimeField() doctorid = models.ForeignKey('Staff', on_delete=models.CASCADE, db_column='doctorID', blank=True, null=True) id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. notes = models.CharField(max_length=255,blank=True, null=True) waiting_time = models.TimeField(db_column='waiting time',blank=True,null=True) # Field renamed to remove unsuitable characters. class Meta: db_table = 'Schedule' The panels which represent all the schedules on that day in the html {% if appoints %} {% for i in appoints %} <div class="panel panel-success"> <div class="panel-heading">Appointment</div> <div class="panel-body"> Patient: {{i.select_related('patient__user___first_name')}}{{i.select_related('patient__user___last_name')}}<br> Doctor: {{i.select_related('doctorid__user___first_name')}}{{select_related('doctorid__user___last_name')}}<br> Time: {{i.time}} </div> </div> {% endfor %} {% endif %} js file responsible for the panels. ATTENTION: I am not certain … -
Django Doc Convert to HTML
I am looking for a HTML converter which allows me to convert doc to HTML in my Django project. In my project, docx files can be converted but not doc files. Docx file processing was done as follows. view.py: @csrf_exempt @api_view(['POST']) def fileload(request): if request.method == 'POST' and request.FILES['file']: urls = settings.MEDIA_ROOT+'fileload/' fs = FileSystemStorage(location=urls, base_url=urls) filename = fs.save(file.name, file) filepath = urls + file.name ext = os.path.splitext(filepath)[1] print(ext) html=None code = '0' if ext == '.docx': html = get_docx_html(filepath) code = '1' fs.delete(file.name) data = { 'code': code, 'html': html } response = JsonResponse(data) return response def get_docx_html(path): with open(path, "rb") as docx_file: result = mammoth.convert_to_html(docx_file) html = result.value messages = result.messages return html In the same way, doc files are not converted. I'd like to have the doc file converted. Any idea of approach that can be recommended or sample code? Thanks a lot. -
Django models naming convention
Can any one please look at the below piece of code to create table/class in models.py. I need these column names as I plan to auto upload the table values via excel on external location automatically. Hence dont want to change the column names. I have tried adding single quotes column name with special characters. Please advise from django.db import models class Errors(models.Model): 'S/O#' = models.IntegerField(max_length=10) Line Number = models.IntegerField() 'S/O' Type = models.CharField(max_length=5) Error Detail = models.CharField(max_length=50) Comments = models.TextField() 'Incident#' = models.CharField(max_length=10) Assigned To = models.CharField(max_length=10) Issue Status = models.CharField(max_length=15) Action = models.CharField(max_length=20) Thanks -
how to make django templates to display
Django templates are not displaying variable. i tried all sort of things and still it didnt work. this is the code my view code def detail(request, Category_id): try: category=Category.objects.get(pk=Category_id) except Category.DoesNotExist: raise Http404("Album does not exist") context={ 'category':category } return render(request,'guestpostapp/detail.html',context) detail.html code <h1>{{category.name}}</h1> <ul> {% for blogger in category.blogger_set.all%} <li>{{blogger.b_name</li> {%endfor%} lease i need help. -
Django with s3 buckets
I have images on s3 buckets and will be adding more images to the s3 bucket with other processes running. The goal is to be able to view all these images and be able to sort these images according to their metadata on a website structure. I am currently using django with the sqlite database, and I have seen ways to use s3 buckets for media uploads on django apps; however, I am looking to automate the process. How would I be able to automatically upload all the images being put on to the s3 bucket to the django web app I am trying to build? -
Django Cusom User Manager Unit Test - NoneType object is not callable
This all started when I downloaded coverage.py and started testing my django project. Everything is fine, however I'm lacking coverage on a custom user manager I set up in Models.py Here's the full code. models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') 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): """Create and save a regular User with the given email and password.""" 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): """Create and save a SuperUser with the given email and password.""" 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) class CustomUser(AbstractUser): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) # profile_image = models.ImageField(upload_to="users/profile_pic", blank=True) is_pastor = models.BooleanField(default=True) home_church = models.ForeignKey( 'church.Church', on_delete="CASCADE", blank=True, null=True) username = None email = … -
Django Admin: how to display a url as a link while calling specific function to download the file
Title is a bit confusing, but basically I have an s3 path stored as a string class S3Stuff(Model): s3_path = CharField(max_length=255, blank=True, null=True) # rest is not important There are existing methods to download the content given the url, so I want to utilize that def download_from_s3(bucket, file_name): s3_client = boto3.client(bleh_bleh) s3_response = s3_client.get_object(Bucket=s3_bucket, Key=file_name) return {'response': 200, 'body': s3_response['Body'].read()} s3_path can be broken into bucket and file_name. This works very easily when I use my own frontend because I can do whatever I want with it, but I don't know how to apply this to admin class S3StuffAdmin(admin.StackedInline): model = S3Stuff fields = ('s3_path', ) Now how do I call that method and make the display a link that says "download" -
How to replace localhost in emails with correct domain for django reset password?
I am serving a django app with a reverse proxy via nginx. The app runs locally under localhost:8686 which is mapped to example.com. So the correct link to reset a password would be something like: https://example.com:8686/accounts/reset/MQ/591-05377c39db92f2d5368a/ but this is what appears in the emails: https://localhost:8686/accounts/reset/MQ/591-05377c39db92f2d5368a/ Obviously, django (locally served with waitress) does not know about the domain name. Is it possible to tell django which domain name it should be using? -
Adding domain path to django html templates
I am serving a django app with a combination of nginx reverse proxy and waitress. In the nginx configuration the app is linked via a location: location /app/ { proxy_pass http://localhost:8686/; } While the app runs on via waitress on port 8686. Now, if I go to the domain.com/app, I the index page is served correctly. Though, my django html template contains the following link: <p> You are not logged in.</p> <a href="/accounts/login"><button>Login</button></a> When I press that button I get to domain.com/accounts/login but it should be domain.com/app/accounts/login I wonder how to change the code so that it works independently of where the app is linked.