Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting a C++/Python desktop application to web app
I have a desktop application that's essentially a glorified Monte Carlo simulation. The simulation is written in C++ (<10,000 lines of code) and the GUI, which calls the .exe is written in python (don't ask, I had (bad) reasons). I'm looking to convert this to a web application on Azure, which I know is going to be a less than trivial task, but I'm hoping to get advice on how to best do this. From how I see this, I have three options, modifying the C++ code and somehow converting this to a web app, rewriting entirely in the .NET framework using C#, or rewriting entirely with Django/Python. Regardless of what I do, I'll have a ton to learn, and I'll need to completely rewrite the front end. Modifying the C++ code seemed like the best option at first. However, after doing some research, I'm thinking my modifications will be heavy, and C++ really isn't an ideal fit for web apps to begin with. I'm worried that between the likely heavy modifications and the finagling I'll have to do with C++, that will greatly outweigh me getting to reuse a good amount of code. The next option would be to … -
Django Runserver Crashes without Message
I've been working a project for months using Python3 & Django, never had issues regarding starting django but yesterday I formatted my Mac, I have the project in Github so today I clone the project and had bunch of issues with Psycopg2 and Pillow but eventually fixed it. The problem now is that, when on the terminal I put python manage.py runserver, django simply crashes without any message and I don't know how to find the problem or view any logs regarding the crash, this is all I get: (backend) ➜ src git:(master) ✗ python manage.py runserver 3Watching for file changes with StatReloader Performing system checks... After that it simply crashes and nothing else happens. Any ideas on how to debug this problem? I've tried cloning it again and building it but same results. -
Read file in Django Management Command
I'm trying to read credentials for the Google Sheets API using gspread. I wrote the following code: class Command(BaseCommand): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def handle(self, *args, **kwargs): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('/static/json/spreadsheets.json', scope) gc = gspread.authorize(credentials) wks = gc.open("Where is the money Lebowski?").sheet1 self.stdout.write(self.style.SUCCESS('Succesfully ran "sheets" command')) Reading the file returns the following error: FileNotFoundError: [Errno 2] No such file or directory: 'static/json/spreadsheets.json' I tried multiple paths like: '~/static/json/spreadsheets.json' '/json/spreadsheets.json' 'spreadsheets.json' But none seem to work. Could anybody help me out here? -
Why doesn't Django Rest Framwork show the posted latitude?
I've got a Django code base which uses Django Rest Framework (DRF) for an API which serves the contents of the DB to the frontend. I now also want users to be able to post new content through this API. I got the API to accept POSTs, but I've got trouble with a gis Pointfield. In one of my models I've got the following field: from django.contrib.gis.db import models as gis_models class Device(models.Model): geometry = gis_models.PointField(name='geometry', null=True, blank=True) # And some other fields I let people post the geometry in two separate fields (latitude and longitude) which I then want to write to the geometry field. I've got a DeviceSerializer which looks like this: class DeviceSerializer(HALSerializer): types = TypeSerializer(many=True) longitude = serializers.SerializerMethodField() latitude = serializers.SerializerMethodField() organisation = serializers.SerializerMethodField() class Meta: model = Device fields = ( '_links', 'id', 'types', 'longitude', 'latitude', 'organisation' ) def get_organisation(self, obj): if obj.owner: return obj.owner.organisation return 'Unknown' def get_longitude(self, obj): if obj.geometrie: return obj.geometrie.x def get_latitude(self, obj): if obj.geometrie: return obj.geometrie.y def create(self, validated_data): print(validated_data) # IN HERE I DON'T RECEIVE THE POSTED LATITUDE AND LONGITUDE types_data = validated_data.pop('types') device = Device.objects.create(**validated_data) for type_data in types_data: Type.objects.create(device=device, **type_data) if 'longitude' in validated_data and 'latitude' in … -
why i have ValueError Django
I have this ValueError views.py def category_post(request, category): posts = get_object_or_404(Post, category=category) return render(request, 'blog/category.html', {'posts': posts}) or def category_post(request, category): posts = Post.objects.filter(category=category) return render(request, 'blog/category.html', {'posts': posts}) or def category_post(request, category): posts = Post.objects.get(category=category) return render(request, 'blog/category.html', {'posts': posts}) I have this error: invalid literal for int() with base 10: 'business' where i made wrong? -
Create boolean twin field automatically for Django model fields
I have models with many fields. For a large amount of those fields (let's say around 20) but not all of them I would like to automatically create a twin BooleanField each. Some requirements: The fields are of different type (e.g. CharField, DateField, ...) In the future there will be new fields added, which is why I want to create this generic solution such that I'll only have to add the main field and mark it for adding a twin Ideally I would like to be able to use the same ORM syntax for filtering and such as if I had manually defined the boolean twin Most of the times just the fields themselves are needed, only very rarely the boolean twin Given the following model from django.db.models import model class MyModel(models.Model): ignore_field = models.Charfield(max_length=10) my_field = models.Charfield(max_length=30) I would like to automatically add the field: is_fixed_my_field = models.BooleanField(default=False) What I have considered: 1. composite-fields The problem I see with that approach is that I will need to define such a composite field for every field type manually and I am also not sure if I can pass kwargs. Also, I don't think I can keep the default syntax for … -
Problems saving Django ORM object with a many to one relationship
I have this model: class Answer(models.Model): order = models.IntegerField() question_key = models.IntegerField() answer_index = models.IntegerField() user_session = models.ForeignKey( UserSession, on_delete=models.CASCADE, related_name="answers" ) user_session cannot be None and I'd love to keep it that way. This is how I'm trying to save an Answer object: answer = Answer( question_key=question_key, answer_index=answer_index, user_session=user_session, order=answer_order, ) answer.save() But I get the error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'user_session'. My research suggests that I need to save the Answer object prior to adding the user_session to it. However, I can't do that if I would like to preserve the not null constraint on the Answer model. Is there a better way to solve this or should I just allow Answer.user_session to be nullable? -
Django - Form not displaying in HTML when receiving an error
In my Django project, I display a form when a user sends a GET request. Here's the code for this: form = SignUpForm() if request.method == 'POST': .... else: return render(request, 'users/signup.html', {'form': form}) HTML FOR THIS: <form method="POST" class="signupform"> {% csrf_token %} {% for field in form %} <div class="fields">{{ field }}</div> {{ field.errors }} <br> {% endfor %} <input class="submitButton" type="submit" value="Sign Up"> </form> If the user sends a post request, I set form = SignUpForm(request.POST) and check if a user with the same username as someone else exists. When this happens, I want to render the whole page again, including the form fields, with an error message displayed. Here's my current code for this: try: user = User.objects.get(username=form.cleaned_data['username']) return render(request, 'users/signup.html', {'error': 'Username field has already been taken', 'form':form}) except User.DoesNotExist: ... HTML: {% if error %} <form method="POST" class="signupform"> {% csrf_token %} {% for field in form %} <div class="fields">{{ field }}</div> {{ field.errors }} <br> {% endfor %} <input class="submitButton" type="submit" value="Sign Up"> </form> {{ error }} {% endif %} However when this error occurs, The error message does show but none of the form fields are displayed on the screen. They disappear. Does anybody … -
ReferenceError,with server's GET function
n1 Reference Error: n1 is not defined a = request.GET['n1'] # here is problem,HTML file has 'n1',but still giving Reference Error -
Get data from database to summernote in Django form
I've implemented summernote in Django. When I add a new item and add details using the summernote, I'm able to get it saved in the database. But when I try to edit the same item I'm not able to retrieve details that I've entered in the summernote. I'm using Django forms for this. I'm able to retrieve all the data but not able to display the data into the summernote. I've tried the following way $('.summernote').summernote('code', 'test string'); But not able to set it into the summernote. I'm using Django 2.2 -
How to declare and use global variables in Django (with Eclipse)
I'm developing an application that needs a global variable. Fortunately, it is working despite Eclipse complaining about the way I used the global variable. To use as an example in this question, I created an application (which works!) that uses a global variable as a page counter. Here is the code: My __init__.py file: counter = 0 My views.py from AccessCounter import counter from django.shortcuts import render def conterf(request): global counter counter +=1 context = { 'counter' : counter, } return render(request, 'AccessCounter/index.html', context) And Eclipse is complaining that I have a "Unsed import: counter" at line "from AccessCounter import counter", but if I remove this line, the counter does not work with this error: name 'counter' is not defined I don't think that the following information is relevant, but here they are... My index.html file <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> Access counter: {{ counter }} </body> </html> and my url.py file: from django.contrib import admin from django.urls import path from AccessCounter import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.conterf, name='counter'), ] -
How to embed Wowza Player into Django Website?
I am trying to embed a live stream( on wowza streamcloud) on my django website but it is not showing anything. I am a bit confused about the process. -
Utilising Djangi annotations with F fields to serialize properties
I have the following model property: @property def is_complete(self): if datetime.datetime.now() >= datetime.datetime.combine(self.date, self.ending_time): return True return False I was wondering, how could I convert this to an annotation, such that: MyObject.objects.annotate(is_complete=?).filter(is_complete=True) Would be equiavalent and valid? -
Django function as Charfield Choices
Consider the following models with the following fields: Powers: class Power(models.Model): ... half = models.BooleanField() micro = models.BooleanField() UseP: class UseP(models.Model): ... power_policy = models.ForeignKey(Power, on_delete=models.CASCADE) def use_types(): TYPES = () TYPES += ("F", "Full Use") if power_policy.half: TYPES += ("H", "Half Use") if power_policy.micro: TYPES += ("M", "Micro Use") return TYPES use_type = models.CharField(max_length=1, choices=use_types()) The function doesn't run. As you can see, when I try without the "self" arguments, it says that power_policy is not defined. If I do it like self.power_policy, it recognizes the power policy but then when I got and call the function like use_type = models.CharField(max_length=1, choices=self.use_types()), it says that the self keyword is not defined in this line. I think the code explains it all, but in case it doesn't I want to provide choices to my user after they choose the Power, according to the power option. For which, I created a function but it doesn't really seem to work. What am I doing wrong or is it not even possible like this? Thank You for your time, -
Finding if lastname exists in database
I'm trying to write a simple IF statement on checking if a lastname in a database exists before a user hits the submit button to create a new record. Here is my code so far, I'm new to Django and Python so the help is appreciated. I made a variable called lastname, the thought process here is when the user hits submit, it checks the database first before the commit to warn them with a popup if the lastname exists to prevent duplicate records. It would actually be really cool to have it when a person exits the field for it to run the script before they finish filling out the form to save time. #views.py from .models import StudentCheck from django.shortcuts import render from django.http import HttpResponse, Http404, HttpResponseRedirect from forms.forms import NewStudentForm def NewStudentFormCheckList (request): if request.method == 'POST': form = NewStudentForm(request.POST) lastname = StudentCheck.lastname if form.is_valid(): newstudent= form.save() else: form = NewStudentForm() return render(request, 'forms/newstudentcheck_form.html', {'form': form}) -
TypeError: __init__() missing 1 required positional argument: 'app_module' [05/Nov/2019 21:53:44] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 90506
I am very new with python and Django and I'm trying to customize a Django project. Instead of using the standard sqlite database upon installing Django. I customized some codes and was able to connect it to a MySql Database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'mypassword', } } I was able to create models and migrate data's to my database. Example: class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) I am also able to run server. Now, I believe Django has a default admin panel. Upon running the program and access http://127.0.0.1:8000/admin/login/?next=/admin/ I am getting an error of: TypeError: __init__() missing 1 required positional argument: 'app_module' You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code. I tried to set DEBUG = True to False in my settings.py and ALLOWED_HOSTS = ['*']. But the problem still exist. I don't know where to go from here. I hope someone can help. -
Error when migrating Django models with custom type Unsigned BigInt
I have MySQL tables that use an Unsigned BigInt(20) as their primary key. Django doesn't support this natively so I created a custom class. This is for Django 2.2 with Python 3.6 and the latest version of MySQL all running on a Ubuntu 18.04 server. from models.py from django.db import models from .util import PositiveBigIntegerField class Label(models.Model): Label_Code = PositiveBigIntegerField(primary_key=True) Company_Name = models.CharField(max_length=30) from utils.py from django.db.models.fields import PositiveIntegerField class PositiveBigIntegerField(PositiveIntegerField): empty_strings_allowed = False def get_internal_type(self): return "PositiveBigIntegerField" def db_type(self, connection): # get db vendor ex.mysql, postgresql, sqlite... db_vendor = connection.vendor if db_vendor == "mysql": return "bigint UNSIGNED" else: # if db_vendor is not mysql, we should return None return None And attempting to use ./manage.py showmigrations yields the following error Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 32, in check_all_models errors.extend(model.check(**kwargs)) … -
Renovate Bot update CDN URLs
I have a Django project that uses Bootstrap and Jquery through their CDNs. Is there a way I can get Renovate Bot to keep an eye on these versions in my HTML code so they don't get forgotten and fall way behind? What are best practices here? Thoughts? -
How to get the second to last most recent timestamped record to update a field using Django/Python?
I have a form that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in timestamp and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_exceptions='N') return HttpResponseRedirect(self.request.path_info) I tried the following, but I get a expected string or bytes-like object and while it still creates a new record before crashing, it does not update the time_exceptions of … -
Django Rest Framework Request AssertionError
Into my app, i'm using Django + Rest Framework. I got the following error : .venv/lib/python3.7/site-packages/rest_framework/request.py", line 160, in init .format(request.class.module, request.class.name) AssertionError: The request argument must be an instance of django.http.HttpRequest, not appname.views.AppViewSet. Class View Class AppViewSet(ModelViewSet): . .... function def list(self, request): pass Django 2.1.4 Helps -
calling stored procedure with parameters from django
I have a stored procedure in mssql spGetRowRackInfo, i am calling the procedure in my django application(using pyodbc) URL pattern: urlpatterns = [ path('ReportRacks/', views.ReportRacks, name="ReportRacks"), ] Code: id = request.GET["ID"] Type = request.GET["Type"] cursor = connection.cursor() cursor.execute("{call dbo.spGetRowRackInfo(?,?)}", [id,Type]) getting an error: ERR sql = sql % tuple('?' * len(params)) ERR TypeError: not all arguments converted during string formatting How do i resolve it? -
Errors: "Class ... has no 'objects' member" & "Instance 'Generator' has no ... member"
I'm currently using Python 3.7.4 & Django 2.2.5, but i'm facing the following problems, and i don't have any clue: Class 'Topic' has no 'objects' member pylint(no-member) Class 'Webpage' has no 'objects' member pylint(no-member) Class 'AccessRecord' has no 'objects' member pylint(no-member) And also... Instance of 'Generator' has no 'url' member pylint(no-member) Instance of 'Generator' has no 'date' member pylint(no-member) Instance of 'Generator' has no 'company' member pylint(no-member) File: first_project/populate_first_app.py (some part of it) import random from first_app.models import AccessRecord,Topic,Webpage from faker import Faker fakegen = Faker() topics = ['Search','Marketplace','Social','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # Get the topic for the entry top = add_topic() # Create the fake data for an entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name = webpg, date = fake_date)[0] And the code I wrote in File: first_app/models.py 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 … -
Can you modify a a widget text field to filter the available options furter?
I created a form with a field in my models called employee_number, which is tied to a separate model, called Salesman, which holds all the data with all the employee names, numbers, dept, etc. Currently it works by only allowing submission of the form if the employee number entered is in Salesman. What I'm trying to do is also filter it further, so that only employees that are part of team "MM" and "OM" and whose employee_status is "A" are the only ones able to submit the form. I saw a suggestion for someone with a similar problem where they said to add more constraints in the “attrs”, but I am not sure if it would work in this case too, as I am not too familiar with Python. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_name = models.CharField(max_length=25) employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True) def __str__(self): return self.employee_number alldata/models.py class Salesman(models.Model): id = models.IntegerField(db_column='number', primary_key=True) team = models.CharField(max_length=2) employee_status = models.CharField(max_length=1, blank=True) -
Ingress Nginx won't load resources of a Django Application
so I have a django application running in K8 but my resource, like .css, won't get loaded. I always receive a 404 on them. I use Ingress-Nginx to route incoming traffic. The ingress config looks like this: apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: ingress-aboi annotations: kubernetes.io/ingress.class: nginx ingress.kubernetes.io/rewrite-target: / spec: tls: - secretName: tls-cert rules: #- host: dev.<ip>.xip.io - http: paths: - path: / backend: serviceName: django-service servicePort: 8000 For the index.html I tried with leading slashes and without. Because I found this information in this stackoverflow thread here. Kubernetes Ingress Nginx loading resources 404 Sadly, it doesn't solve my problem. Index.html <html lang="en"> <head> <title>Log in | Django site admin</title> <link rel="stylesheet" type="text/css" href="static/admin/css/base.css"> <link rel="stylesheet" type="text/css" href="static/admin/css/login.css"> <link rel="stylesheet" type="text/css" href="static/admin/css/responsive.css"> </head> <body> </body> </html> Before I was using a nginx with this config, but I don't want to use another pod if I can handle the traffic with a ingress-nginx component alone. nginx.conf server { listen 443 ssl; location /media { alias /website/media; } location /static { alias /website/static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; uwsgi_read_timeout 300; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; } So to sum it up. I … -
django NodeNotFoundError Migration employee.0001_initial dependencies on ('auth', '0013_auto_20191031_1253')
i am getting error while migrating in deployment like django.db.migrations.exceptions.NodeNotFoundError: Migration employee.0001_initial dependencies reference nonexistent parent node ('auth', '0013_auto_20191031_1253') but my migration file working fine in local pc with mysql db like Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_auto_20190907_1107... OK Applying auth.0013_auto_20191031_1253... OK Applying employee.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747... OK Applying sessions.0001_initial... OK but in linux server i am getting error and i am using custom User model from AbstractUser called User in the same models.py file and give to one to one link employee model like class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) and this is migration file import datetime from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0013_auto_20191031_1253'), ] operations = [ migrations.CreateModel( name='User',