Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare current time and timestamp in Django
I am experimenting with my Django templates with the now function. What the code below is supposed to do is to set the current_time as HH:MM and compare that to the timestamp in my cart.created. If HH:MM is the same it should color the text green, but it colors it red. Where is my logic wrong? {% now = "H:i" as current_time %} {% if current_time == cart.created|date:"H:i" %} <td class="ok">{{ cart.created | date:"H:i:s" }}</td> {% else %} <td class="buh">{{ cart.created | date:"H:i:s" }}</td> {% endif %} -
ValueError: invalid literal for int() with base 10: '' with POST
I'm trying to add a product to the cart in my database. But I keep on getting the following error. Internal Server Error: /cart/update/ Traceback (most recent call last): File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\david\Desktop\Lieferhalle2\src\carts\views.py", line 13, in cart_update product_obj = Product.objects.get(id=product_id) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 371, in get clone = self.filter(*args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1210, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\sql\query.py", line 1104, in build_lookup return final_lookup(lhs, rhs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\lookups.py", line 74, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "C:\Users\david\Desktop\Lieferhalle2\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The error seems to always throw on line product_id = request.POST.get('product_id'), with the Post request. views.py from django.shortcuts import render, redirect … -
With an nginx / gunicorn / Django setup, what logs the Bad Requests?
I'm following a teach yourself type book about how to set up a Python-based web thing. I've just set up gunicorn so that it functions as a systemd service, rather than having to run it manually. Previously, if a "Bad Request (400)" came in you would see something in the gunicorn server output. But now I don't know where, if at all, this is logged. Or which of the components involved does the logging. From my searching I tried various things, like: journalctl --unit=gunicorn | tail -n 300 ... this produced nothing. Someone also recommended /var/www/django for Django logs. But there is no such directory under /var/www. -
Password missmatch issue in html [closed]
I have the following code: <form data-provide="validation" data-disable="true" method="POST" action="{% url 'signup' %}"> <div class="form-group"> <input placeholder="Mot de passe" type="password" class="form-control" id="id_password" name="password" data-minlength="6" data-error="Le mot de passe doit comprendre au moins 6 charactères." required> <div class="invalid-feedback"></div> </div> <div class="form-group"> <input placeholder="Confirmation du mot de passe" type="password" class="form-control" id="id_password-conf" name="password-conf" data-match="id_password" data-error="Les mots de passe ne correspondent pas." required> <div class="invalid-feedback"></div> </div> </form> And it was working fine but I did something and now even when I put the exact same password it gives the validation error that the passwords do not match. Any ideas? Thanks! -
Django: Elasticsearch-dsl not found
I am currently setting up a simple search in django using the elastic search and haystack. However, when I run the server , it occures the following error: (development_env) C:\Users\user\Desktop\Development\development>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'elasticsearch-dsl' 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 "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Desktop\Development\development\development_env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv … -
django last_modified with different query_params
I have an endpoint that is cached using last_modified. But the endpoint receives a query param with 1 value. And it returns different result depending on the query param received. Will the cached result in the browser be affected by the query param? -
Bootstap datatable ajax reload when new data appear
I'm showing data in table using django view, in addition I've bootstrap datatable that is responsible for pagination, searching and sorting functionalities. The problem is when I'm adding the data to the database (using ajax call) the pagination is not working and number of records is not refreshed. view.py def patients_list(request): patients = Patient.objects.all() return render(request, 'patients/patients.html', {'patients': patients}) ajax call for inserting data var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book .modal-content").html(""); $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }; datatable $(document).ready(function() { $('#book-table').DataTable({ retrieve: true, "order": [], "columnDefs": [ { "targets" : 'no-sort', "orderable": false, }] }); }); Does anyone knows how can I refresh the datatable so that number of rows will align with newly added ones? What I've tried already was ajax.reload() and ajax.draw(), but nothing worked. -
Celery queues and Redis queues
I was looking at some tutorials for setting up Redis (message broker) + Celery for Django and I'm a little confused about how the queues work. The tutorial I followed was https://hackernoon.com/asynchronous-tasks-with-celery-redis-in-django-3e00d3735686 Does redis have an inbuilt queue as the message broker? Or is the queue a part of celery? Which queue is the task pushed onto? The redis queue or the celery queue? In this diagram it looks like redis and celery have their own queues -
Django: forbid to add the same data for user
I have app where user can add url to favorite in database with ManyToMany relationship. So every user can have a lot of urls and every url can have a lot of users. I have problem with creating restriction to avoid adding the same url for user. I mean I want to create the mechanism where url can be added a lot of time for users, but only one per user. In my models I have: from django.db import models from django.contrib.auth.models import User class Repository(models.Model): url = models.CharField(max_length=250,unique=False) user = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE,default='') repositorys = models.ManyToManyField(User,related_name='user') And in my views: def favorites(request): url = request.session.get('url') repo = Repository(url=url,user=request.user) repo.save() repo.repositorys.add(request.user) user = User.objects.get(username=request.user.username) repos = user.users.all() return render(request, 'favorites.html',{'url':url,'repos':repos}) Favorites function is called on clicked button in my template. When I click the above function is executed and redirect to /favorites. The problem is, when I click again on button and Im logged as the same user, this url is added again to database. Same problem with refreshing favorites.html. Is there any logic way to solve this problem? -
Django; passing value from dropdown list to main page
I am still a novice to django and I have a form with a drop down menu; I am able to make a selection, but once I make that selection I need help passing it to the main page. I think I need to add detail to the views but I am not sure if it is there or if the detail needs to be added to the main *.html page views.py def search_device(request): locations = Locations.objects.all() context = {"locations": locations} for location in context['locations']: print(location) if request.method == "POST": location_name = request.POST.get("locations") return render(request, 'example/search_device.html', context, ) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', example_views.home, name="home"), path(r'^location/$', example_views.home, name="location_name"), path('add_location', example_views.add_location, name='add_location'), path('add_device', example_views.add_device, name='add_device'), path('search_device', example_views.search_device, name='search_device')] device_list.html <html> <head> <title>Device List</title> </head> <form method="post"> <body> <a href="add_device">Add Device</a> <a href="add_location">Add Location</a> <a href="search_device">Search Devices</a> <p> <h3>Devices Go Here:</h3> {% csrf_token %} {% for device in devices %} {{device.device_name}} <br> {% endfor %} <br> <br> <h3>Associated Locations</h3> {% if location.location_name %} <p> Great, you selected: {{location.location_name}} </p> {% endif %} </body> </html> and search_devices.html <html> <head> <title>Device List</title> </head> <form method="post"> <body> <a href="add_device">Add Device</a> <a href="add_location">Add Location</a> <a href="search_device">Search Devices</a> <p> <h3>Devices Go Here:</h3> {% csrf_token %} … -
DJANGO SESSION KEYERROR
I have an angular frontend app which send file to django backend which data is setting in django session. After I send a httprequest to django backend to make ML tratements on that data and get the results. But I've a 500 sever error: keyerror 'ts_dataset_copy': KeyError: 'ts_dataset_copy' [24/Feb/2020 18:43:46] "GET /cv_classification/5/FOTS/283/None/0/0 HTTP/1.1" 500 78264. Here are my django code: @csrf_exempt def upload_local_dataset(request): if request.method == 'POST': dataset = pd.read_csv(request.FILES.get('datasetfilepath'), header=None, index_col=None) request.session['ts_datset'] = dataset.to_json(orient='values') request.session['ts_dataset_copy'] = dataset.to_json(orient='values') return HttpResponse(dataset.to_json(orient='values')) second httrequest that throws a server internal error def cv_classification(request, kfolds, dissimilarity_func, windows_length=0, noisy_law="", mu=0, std=0): noisy_law = noisy_law.lower() df = pd.read_json(request.session['ts_dataset_copy'], orient='values') predictions = cv_classify(df, kfolds, dissimilarity_func, windows_length, noisy_law, mu, std) return JsonResponse(predictions, safe=False) Thanks for your help! -
File Download won't complete (discards finished file, restarts - affecting newer Chrome (-like) browser)
This wasn't a problem until recently and it's only affecting Chrome-like browsers. It does affect Brave, for example, but the download still works well on Firefox. And this problem started on recently. My server creates a report file (a csv) and this should then, when ready, be served to the user via a link. The report file is created via a asynchronous task via django-celery. If the file is not ready, the page just reloads and offers the same download link. Creating the file doesn't take very long in practice... It's not particularly sophisticated, but it works for my purposes. View: def account_get_all(request): link = None if request.method == 'GET': if request.GET.get('create-report'): # creates report elif request.GET.get('link'): link = request.GET.get('link') try: result = AsyncResult(link) if result.ready(): filename = "path/to/app/media/dumps/" + result.get() wrapper = FileWrapper(open(filename)) response = FileResponse(wrapper, content_type='text/plain') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename="'+result.get()+'"' return response else: parsed_uri = urlparse(request.META.get('HTTP_REFERER')) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) return redirect(domain + path + result) except: # do some error handling return render(request, 'get_report.html', {'accounts' : accounts, 'file_link': link }) else: return render(request, 'get_report.html', {'accounts' : accounts }) -
celery class-based Task is not retring when autoretry_for is set
Celery class-based task is not retiring automatically when autoretry_for is configured. import celery class SaveImageUrl(celery.Task): autoretry_for = (TypeError,) retry_kwargs = {'max_retries': 5, 'countdown': 5} def run(self, message_id: str) -> None: ... raise TypeError SaveImageUrl = app.register_task(SaveImageUrl()) # here app is celery app However, this works for function-based task: @shared_task(bind=True, autoretry_for=(TypeError,), retry_kwargs={'max_retries': 3, 'countdown': 2}) def save_image_url(self, message_id: str): ... raise TypeError Celery Version : 4.4 -
Django Form Init not prefilling the form
I have a model form and I want to initialize my form with two prefilled fields, I have override the init method but is not working, this is something that I have tried: forms.py class AgregarPagoTransaccionExistente(forms.ModelForm): def __init__(self, *args, **kwargs): self.carro = kwargs.pop('carro') self.semana = kwargs.pop('semana') super(AgregarPagoTransaccionExistente, self).__init__(*args, **kwargs) class Meta: model = Pagos fields = ('carro', 'pago', 'fecha', 'semana', 'renta') widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}), 'semana': forms.DateInput(attrs={'type': 'week'}) } views.py class AgregarPagoSemana(CreateView): template_name = "AC/add_paymentexistingweek.html" model = Pagos form_class = AgregarPagoTransaccionExistente def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'semana': self.kwargs['semana'], 'carro': self.kwargs['carro'], }) return context def get_form_kwargs(self): kwargs = super(AgregarPagoSemana, self).get_form_kwargs() kwargs['carro'] = self.kwargs.get('carro') kwargs['semana'] = self.kwargs.get('semana') return kwargs this is how I'm passing the parameters in the template <a href={% url 'pago_existente' carro=request.resolver_match.kwargs.carro semana=request.resolver_match.kwargs.semana %}><button type="button" class="btn btn-primary" > this is the UI of the form with the blank fields: I'm not getting any errors, the form is being display but now with the data prefilled according to the parameters that I'm passing wich are 'Carro' and 'Semana'. -
How to link html files together using Django?
i am using django 3.0 with python 3.8. i am new to coding. below is my project hierarchy.i want to connect my "home" page to next html "teoco" page by clicking on continue button for which i have below html code myproject.urls- from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('training_review.urls')), path('teoco', include('training_review.urls')), path('admin/', admin.site.urls), ] home.urls- from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), path('teoco',views.teoco, name='teoco') ] home.views- def home(request): return render(request, 'home.html') def teoco(request): return render(request, 'teoco.html') -
'User' object is not iterable , on save function called
in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME in value_from_datadict: [''] FOUND AN EMPTY TIME Internal Server Error: /factarti/upload/file Traceback (most recent call last): File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/brter/PycharmProjects/brter/brter_2_7/factartis/views.py", line 352, in upload factarti, admin = savefactarti(request.POST, factarti_object_type, factarti_form, request.user)# here is error File "/home/brter/PycharmProjects/brter/brter_2_7/factartis/views.py", line 515, in savefactarti specific_form.save() File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/forms/models.py", line 458, in save self.instance.save() File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/db/models/base.py", line 790, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/signals.py", line 52, in handle_save index.update_object(instance, using=using) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line 284, in update_object backend.update(self, [instance]) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 60, in update docs.append(index.full_prepare(obj)) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line 208, in full_prepare self.prepared_data = self.prepare(obj) File "/home/brter/.virtualenvs/brter/lib/python3.6/site-packages/haystack/indexes.py", line … -
django aws elastic beansstalk error ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
I know this error have come to many people and i have tried different solutions and none of them worked. I am using aws eb cli. i am using following command eb deploy to deploy my application to server. Following are the configuration for my django. under .ebextensions directory, i have following 2 files: 1: 01_packages.config packages: yum: git: [] python27-devel: [] mysql: [] mysql-devel: [] and another file is 2: 02_django.conf option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "settings.development" "PYTHONPATH": "/opt/python/current/app/src:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: src/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" following is my requirements.txt file after pip freeze in my local virtual environment. requirements.txt asn1crypto==0.24.0 awsebcli==3.17.1 backports.ssl-match-hostname==3.5.0.1 botocore==1.14.17 cement==2.8.2 cent==2.1.0 centrifuge==0.8.4 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 colorama==0.3.9 cryptography==2.1.4 Django==1.8.18 django-colorfield==0.1.14 django-countries==5.0 django-debug-toolbar==1.9.1 django-environ==0.4.4 django-multiselectfield==0.1.8 django-simple-history==1.9.1 django-sslserver==0.20 docutils==0.15.2 enum34==1.1.6 future==0.16.0 google-api-python-client==1.6.4 hiredis==0.2.0 html5lib==1.0b8 httplib2==0.10.3 icalendar==4.0.0 idna==2.6 ipaddress==1.0.18 jmespath==0.9.4 jsonschema==2.4.0 mysqlclient==1.4.6 oauth2client==2.0.0 oauthclient==1.0.3 olefile==0.44 pathspec==0.5.9 paypalrestsdk==1.13.1 pdfcrowd==4.0.1 phonenumbers==8.8.6 Pillow==4.3.0 pyasn1==0.3.7 pyasn1-modules==0.1.5 pycparser==2.18 PyJWT==1.5.3 pyOpenSSL==17.5.0 PyPDF2==1.26.0 pypiwin32==219 pytesseract==0.1.7 python-dateutil==2.6.1 pytz==2017.3 PyYAML==5.2 reportlab==3.4.0 requests==2.18.4 rsa==3.4.2 semantic-version==2.5.0 six==1.11.0 sockjs-tornado==1.0.1 sqlparse==0.2.4 termcolor==1.1.0 toredis-fork==0.1.4 tornado==4.2.1 toro==0.8 twilio==6.9.1 uritemplate==3.0.0 urllib3==1.22 wcwidth==0.1.8 webencodings==0.5.1 xhtml2pdf==0.2.2 i kept this in my root directory. when i run eb deploy it deploys successfully. but when i run the browser to my url. I get this Internal Server … -
How to properly write complex boolean expressions in Python [closed]
if not request.user.is_staff and obj.is_internal or not request.user.is_kyc_complete: return None I tried: if not (request.user.is_staff and obj.is_internal) or not request.user.is_kyc_complete: return None But my tests keep failing -
Difference between models and Model in django
What exactly is the difference between models and Model.while writing a model in django. from django.db import models class Teacher(models.Model): -
Select a valid choice. <choice> is not one of the available choices
I am passing choices from the view into my form. When I submit the form , the error returned from form.errors is: Select a valid choice. 1-20-2020 - 1-27-2020 is not one of the available choices. views.py : lstchoices = [] for week in weeks: lstchoices.append((week,week)) form.fields['camp_dates'].choices = lstchoices def register(request): form = RegistrationForm() print (request.POST) if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegistrationForm(request.POST) # check whether it's valid: if (form.is_valid()): return render(request,'camp_registration.html') else: print (form.errors) forms.py class RegistrationForm(forms.Form): camp_dates = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple, ) -
Populate database with foreign key relationship in Django (Wagtail)
once a day I need to remove all data from 2 tables and upload new data. All goes well with "product" table, but I'm not able to populate "pricelist" table because there is foreign key relationship on the table. model.py: class product(models.Model): EAN = models.CharField(primary_key=True, unique=True, max_length=13) Name = models.CharField(max_length=50) class vendor(models.Model): vendor = models.CharField(primary_key=True, unique=True, max_length=7) Name = models.CharField(max_length=50) class pricelist(models.Model): EAN = models.ForeignKey(product, on_delete=models.CASCADE) vendor = models.ForeignKey(vendor, on_delete=models.CASCADE) Qty = models.CharField(max_length=15) app.py ... def app ... product_list = product_list[["EAN", "Name"]] session.execute("use intranet; SET FOREIGN_KEY_CHECKS = 0; DELETE FROM product_list; DELETE FROM pricelist; SET FOREIGN_KEY_CHECKS = 1;") session.flush() session.commit() product_list.to_sql("product_list", con=engine, if_exists='append', chunksize=1000, index=False) df = df[["EAN", "vendor", "Qty"]] # everything works until here: df.to_sql("pricelist", con=engine, if_exists='append', chunksize=1000, index=False) Error I get: (1452, 'Cannot add or update a child row: a foreign key constraint fails If I replace if_exists='append' with if_exists='replace' then data is uploaded but table settings (including all relations) are wiped out. Any help would be really appreciated! -
Pull Variable From HTML And Pass to Django Form
In my url i have my classroom id : example here : http://127.0.0.1:8000/points/k8_points_classroom/1? I need to pull the 1 out of this and send it to my forms view to achieve this query. How do i go about doing that ? Thank you class K8Points_ClassroomForm(forms.ModelForm): class Meta: model = K8Points fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','class_name') labels = {'class_name':_('Class Name'),'student_name':_('Student Name'),'time_frame':_('Time Frame') } def __init__(self, *args, **kwargs,): super(K8Points_ClassroomForm,self).__init__(*args,**kwargs) self.fields['date'].disabled = True self.fields['day'].disabled = True self.fields['week_of'].disabled = True classid = getstudents = Student.objects.filter(class_name = classid).order_by('student_name') self.fields['student_name'].queryset= getstudents.all().order_by('student_name') self.fields['class_name'].widget.attrs['readonly'] = True The query filters the students that are present in the class to the dropdown menu. -
Does a Django form invalidates if additional input fields are injected and posted from html?
I am using two different forms for same model, one of which is supposed to not include a particular field in it. Say, I have a model called payments (which has a field 'lead' and some other fields). I make two forms out of it - PaymentAddWithLeadField and PaymentAddWithoutLeadField. The latter form excludes the field lead in it. Now, if someone manually injects the field lead in html form and posts it, will form.is_valid() stand invalidated? I just want to make sure that no one can save the value for the field 'lead' from PaymentAddWithoutLeadField (that excludes the field) form posting as I dont want it to happen. -
Specify where django should look for template
I have a loca django project. In this project I stored a templates/ directory at the same level as apps/the inner project folder. This folder only held base.html (as I didn't think it made sense to store it in an app if all pages would extend it). To use this template I simply said {% extends 'base.html' %} and it would work. Now, I have set up a server and am working on moving my project over. However, now when I go to my domain(have debug=True for now) I see: TemplateDoesNotExist at / Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/justin/project/account/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/job/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/crispy_forms/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/justin/project/env/lib/python3.6/site-packages/django/contrib/auth/templates/base.html (Source does not exist) Is there a way to tell Django it can find base.html at /home/justin/project/templates/base.html? -
django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id
I am currently working on a project that would take in a users information and store it. My problem is I keep running into this NOT NULL constraint failed with the user id error. I believe this comes from having a null user when the form is trying to save, but don't know what I could do to fix it. I tried using this line: form.user = Profile.objects.get(user=self.request.user) but it didn't work and gave me this error: NameError at /users/pii/ name 'self' is not defined Any help or advice that would point me in the right direction would be greatly appreciated! models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') gender = models.CharField(max_length = 1, choices = GENS, default = '') birthday = models.DateField(default = '1900-01-01') address = AddressField(on_delete=False, blank=True, null=True) race = models.CharField(max_length = 2, choices = RACES, default = 'x') ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x') income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x') education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x') employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img …