Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Should I learn .Net or Drupal for web-development?
I just started a new job and I've been asked to develop a web-app and need to decide what development framework (.Net or Drupal) to learn. I apologize if this is the wrong place to post this question. I have experience as a Linux admin, and have written primarily in Python in the past. I have slight familiarity with C++ and Java but greatly prefer Python. I know that my IT department is trending towards a Linux environment (it's mostly windows atm) and I want to develop in something that can potentially migrate from a windows server without having to completely re-write the application. My boss has other ideas, however. If he had his way, I'd be developing in .Net everything for all time. And before he'd let that happen, all my development would be in Access....and I'm not sure I want to do that. I know that there is some development happening with Drupal in our environment elsewhere. It would be nice to have a backup or someone around that can be a reference when I run into issues. Otherwise I'd be the only .Net developer in the org. My predecessor is working part-time as a developer for my … -
Rendering results of multiple value Django annotate query with into html table
I am trying to display a summary of statuses by agent. Annotate looks like the way to go, but the data structure doesn't seem to allow me to loop through the objects and populate an html table cleanly. I've tried manipulating the result set further in my view before passing to the template, but I've mangled it so badly that I'm not sure if I'm approaching this correctly. Any feedback is appreciated. I've attempted the query the database with a 'group by' query using the objects.values().annotate() methods. This outputs a list of dictionaries. If I could get the values as keys, that might work, but there is another list. Querying the user model directly may inadvertently leave out any agents that don't have any QA events. original views.py def agent_summary(request): lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id')) context = {'lead_qas': lead_qas} return render(request, 'manager/agent_summary.html', context) This gets me a data structure like: {'qa_agent': 3, 'qa_status': 'Confirmed', 'id__count': 1}, {'qa_agent': 1, 'qa_status': 'Pending Review', 'id__count': 6}, {'qa_agent': 1, 'qa_status': 'Disqualified', 'id__count': 8}, {'qa_agent': 2, 'qa_status': 'Disqualified', 'id__count': 1}, {'qa_agent': 2, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Not Started', 'id__count': 3}, {'qa_agent': 3, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Confirmed', 'id__count': … -
About installation issue of postgreSql
When I tried to install Postgre SQL in my windows 8.1 when it almost comes near to complete installation showing this error: Problem Running Post-Install Step. Installation May Not Complete Correctly failed to start the database server. Please, someone, help me in this case ???? error: Problem Running Post-Install Step. Installation May Not Complete Correctly failed to start the database server. -
Django: How to Sum By Range_Date
Filter with the date and find the sum of the range, not the total of all the objects,example, from January 1 until January 2 or from February 1 to February 20, each range. This is my code: def orecerca(request): qs = Ore.objects.filter(user=request.user) sum = Ore.objects.filter(user=request.user).aggregate(totals=(Sum('oret'))) nomecognome = request.GET.get('nomecognome') date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(nomecognome): qs = qs.filter(nomecognome=nomecognome) if is_valid_queryparam(date_min): qs = qs.filter(data__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(data__lte=date_max) context = { 'ore': qs, 'sum': sum, } return render(request, "guarda.html", context,) -
AttributeError: 'int' object has no attribute 'pk'
I am attempting to create a POST endpoint using DRF ListSerializer to create a list of LogLevel objects. I have tried to serialize the foreign key using PrimaryKeyRelatedField without success. models.py relevant fields for LogLevel model. note foreign key to node model #associated node node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name="log_levels") #logger name name = models.CharField(max_length=32, choices=LOGGERS) # Current log level level = models.IntegerField(default=INFO, choices=LOG_LEVELS) # Timestamps created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True, blank=True, null=True) serializers.py class LogLevelListSerializer(serializers.ListSerializer): def create(self, validated_data): log_levels = [LogLevel(**item) for item in validated_data] levels = LogLevel.objects.bulk_create(log_levels) return levels class LogLevelCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = LogLevel fields = "__all__" list_serializer_class = LogLevelListSerializer LogLevel view class LogLevelList(MethodSerializerMixin, generics.ListCreateAPIView): """ Log Level list API Endpoint. """ method_serializer_classes = { ("POST",): LogLevelCreateUpdateSerializer } def get_queryset(self): """ Queryset to use for endpoint. """ return LogLevel.objects.all() def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() # check if many is required if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return serializer_class(*args, **kwargs) I expect the objects to be created and displayed to … -
MultipleObjectsReturned Django error despite fields being unique together
I have a model called Packaging that is defined in Django as follows using Postgres: class Packaging(BaseModel): unit_of_measure = models.CharField( _("UOM"), max_length=50, null=True, ) quantity_in_unit_of_measure = models.IntegerField( _("Qty In UOM"), null=True, blank=True, ) class Meta(BaseModel.Meta): index_together = [ 'unit_of_measure', 'quantity_in_unit_of_measure' ] unique_together = [ 'unit_of_measure', 'quantity_in_unit_of_measure' ] BaseModel adds some fields like created_by and modified_by. I'm trying to allow multiple Celery threads to call the following function while avoiding duplicate entries: packaging, _ = safe_get_or_create( Packaging, unit_of_measure=description.get('unit_of_measure'), quantity_in_unit_of_measure=description.get( 'quantity_in_unit_of_measure' ) ) Description is a dict that varies with values like the following: { "unit_of_measure": "EA", "quantity_in_unit_of_measure": 1 } The function I'm calling is: def safe_get_or_create(model, **kwargs): ''' the keys of kwargs must be enforced as unique_together in the database ''' try: created = False try: instance = model.objects.get(**kwargs) except model.DoesNotExist: try: with transaction.atomic(): instance = model.objects.create(**kwargs) created = True except IntegrityError: instance = model.objects.get(**kwargs) return instance, created except MultipleObjectsReturned: print(model) print(kwargs) print(model.objects.filter(**kwargs)) print(model.objects.filter(**kwargs).count()) raise Which is based on https://www.agiliq.com/blog/2013/08/writing-thread-safe-django-code/ The error I'm getting and output from that function is: <class 'apps.products.models.Packaging'> {'unit_of_measure': 'EA', 'quantity_in_unit_of_measure': None} <QuerySet [<Packaging: Packaging object (262)>, <Packaging: Packaging object (241)>]> 2 apps.products.models.Packaging.MultipleObjectsReturned: get() returned more than one Packaging -- it returned 2! When I view the … -
Is there a way to pass model attribute into another attribute?
I'm using {% autoescape off %} to render html that I add through admin page. I want to get another variable of the model. post.html {% autoescape off %} {{ post.content }} {% endautoescape %} Is it possible pass another attribute of the same model into the content? Something like that post.content <img src="{{ post.main_image.url }}"> -
Django migrations not pushing to Heroku
I have updated a Django blog to use slug urls <slug:slug>/ instead of id <int:pk>/. I also added a slugField to the Article model, and converted all hrefs to article.slug. Ran migrations and everything worked fine locally. However, when I pushed to Heroku I got the following error. ProgrammingError at /admin/articles/article/ column articles_article.slug does not exist LINE 1: ...ticles_article"."id", "articles_article"."title", "articles_... ^ Request Method: GET Request URL: https://***********.herokuapp.com/admin/articles/article/ Django Version: 2.1.4 Exception Type: ProgrammingError Exception Value: column articles_article.slug does not exist LINE 1: ...ticles_article"."id", "articles_article"."title", "articles_... ^ I checked my Heroku Postgress database and I found that the new slug column hadn't been added even though I did migrations. I'm not exactly sure what to do next. I'm currently searching for ways to manually update the heroku postgress, but if there's a less invasive way to solve this problem I'm all ears. -
Extension of user model in django redux registration gives NotImplementedError at /accounts/register/ error
I am trying to extend the user model in django redux registration. I have tried some possible solutions, but all in vain. Django Debug shows that is "NotImplementedError at /accounts/register/ No exception message supplied" I have tried this to solve this problem Moreover, i was following rvlsico answer here on how to get started on it. Any help would be appreciated. Here are my code snippets: regbackend.py class MyRegistrationView(RegistrationView): form_class = ProfileForm def register(self,form_class): new_user = super(MyRegistrationView, self).register(form_class) p = form_class.cleaned_data['teacher'] new_profile = Profile.objects.create(user=new_user, teacher=p) new_profile.save() return new_user models.py class Profile(models.Model): user = models.OneToOneField(User, primary_key=True,on_delete=models.PROTECT) teacher = models.BooleanField(default=False) @property def is_teacher(self): return self.teacher forms.py class ProfileForm(RegistrationFormUniqueEmail): teacher = forms.BooleanField(required=False,label=("Are you a teacher?")) urls.py urlpatterns = [ re_path(r'^register/$', MyRegistrationView.as_view(), name='registration_register'), path('', include('registration.backends.default.urls')),] -
Django Forms: unique inputs, similar form on same page?
In my admin console - users can upload more than one picture and give each picture a unique slug (site/pictures/slug) - if the user tries to give a picture a slug that already exists by querying the database, they get a validation error telling them to create a unique slug - but if they submit two pictures at the same time with the same slug, theres not such error because the slugs arent in the database yet to raise errors. how do i query the form to make sure two pictures slugs are unique to eachother within the form? def clean_slug(self): slug = self.cleaned_data.get('slug', '').strip() picture_id = self.cleaned_data.get('picture_id') slug_query = Pictures.objects.filter(slug=slug.lower()) if self.instance and self.instance.id: slug_query = slug_query.exclude(id=self.instance.id) if slug.lower() and slug_query.exists(): raise forms.ValidationError('This slug is not unique. Please try a different slug.', code='invalid') return slug.lower() the first if statement is so if a user updates a picture resource, the db wont query the database and say the slug exists. the second prevents none unique slug urls from being added