Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Erro no Django: TypeError: expected string or bytes-like object na criação de tabelas no models
Boa noite! Estou criando um banco de dados pelo Django, mas ao executar o comando python manage.py migrate, recebo essa mensagem de erro: > python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, core, sessions Running migrations: Applying core.0002_auto_20210621_2027...Traceback (most recent call last): File "C:\Users\mat_a\Documents\GitHub\ProjetoSalvePets\Projeto\SalvePets\manage.py", line 22, in <module> main() File "C:\Users\mat_a\Documents\GitHub\ProjetoSalvePets\Projeto\SalvePets\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, create_field=field) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table self.effective_default(create_field) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\base\schema.py", line 310, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\models\fields\__init__.py", line … -
How do I get collectstatic to work when running a Django/React App on Heroku?
I have a Django/Wagtail/React App that works in my dev server, but when I try to build it on Heroku, I get a ***FileNotFoundError when it runs collectstatic. I'm using Whitenoise to serve the static files and have Gunicorn installed with its corresponding Procfile. This is the error log I get on Heroku: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.5 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (d71a71)... -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput BASE_DIR /tmp/build_73214ee4 BASE_DIR + FRONTENTD: /tmp/build_73214ee4/frontend/build/static Traceback (most recent call last): File "/tmp/build_73214ee4/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File … -
Does formset_factory inherit the clean/validation methods of the form it extends?
Basically the title. I want to know if for example: forms.py class TestForm(forms.Form): field1... def clean_field1(self): field1... views.py formset = formset_factory(TestForm)... formset.is_valid() <---? Will formset.is_valid() call clean_field1()? -
How to retrofit an auto increment id field back to a model in Django
I have the following model: class Team(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(max_length=50) However I realised this is a dumb design since I cannot rename the slug in admin, so I want to add the auto increment id back to the model, by removing the primary_key=True from slug field, however, makemigrations requires me to put in the default value for the id field, how do I go about doing it? class Team(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=50) -
webpack no output file is created
I try to use webpack to overwrite sass. when i run npx webpack --config config.js I get "./src/js/index.js... compiled successfully in 75 ms however, no files are created in my djano project static/js and static/scss If I create the files, they remain empty as no data is pass to them. I note this information is passed to dist/main.js but not to my django project. How can i export the index.js/index.scss files from webpack to my django project? my config.js is: const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: './src/js/index.js', mode: 'development', output: { filename: 'index.js', path: "/carmuse8/static/js/", }, module: { rules: [ { test: /\.(scss)$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ] }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: '../css/index.css', }), ] }; Thanks for any input that will allow me to advance. -
Django admin panel search bar not work (Related Field got invalid lookup: icontains)
I have in models class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sats_balance = models.PositiveBigIntegerField(default=0, validators=[MinValueValidator(0)]) pin = models.CharField(max_length=15, default=pin_generator) pin_saved = models.BooleanField(default=False) and in the wallet app admin.py from django.contrib import admin class WalletAdmin(admin.ModelAdmin): search_fields = ['user'] the search bar has exist but when I search for any user I got this error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains -
Structure of an HTML post Request vs Django HTML Post Request
I have the following HTML form code which I am trying to translate to Django Templating Language. <form action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST"><input type=hidden name="oid" value="00D280000016jv0"> <input type=hidden name="retURL" value="https://url/form/"> <label for="first_name">First Name</label><input id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br> <label for="last_name">Last Name</label><input id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br> <label for="email">Email</label><input id="email" maxlength="80" name="email" size="20" type="text" /><br> <label for="phone">Phone</label><input id="phone" maxlength="40" name="phone" size="20" type="text" /><br> </select><br><input type="submit" name="submit"> </form> I've looked at Django Templating Tutorials which tells me to create a view however I don't think that's necessary. What is the Django equivalent of this code? -
To reload or not reload - Is it better to send data to the server via ajax and then reload the page to see the result or update the DOM using js?
I have a fairly complex Django (3.1) site. On a couple of pages, I have some html/javascript code for the user to add/edit/delete comments. The script packages the comment and other bits and sends it to the server in an ajax POST request so the comment can be added/updated/deleted to/from the database. The script then gets an acknowledgement from the server, and, currently, it reloads the page so the new/edited/deleted comment can be seen at the bottom of the page. It all works fine in Chrome and Firefox. My questions is: Is it better practice to have the script add/edit/delete the comment html directly in the DOM based on the ajax response, rather than just reloading the page with the updated data? Why or why not? Thanks! Mark -
Django SQLite regex query is slow. Local SQLite regex query is fast. Why?
I have a small SQLite3 app that's basically a database search. When I do from main.models import Customer queryset = Customer.objects names = queryset.filter(name__regex = "[^aeiou]ica$") list(names) in ./manage.py shell, Django takes up to 5 seconds to return this result. Meanwhile on my local machine, if I do the same query in the sqlite shell, sqlite> select * from main_customer where name regexp "[^aeiou]ica$"; I get the result in less than a second. Where does the difference come from? Can Django be made to match the speed of my local query? -
is there a way to compute a field based on the value ot other two field in the same form, using ModelAdmin?
I want to compute based on two fields a third field using django and ModelAdmin. example when a write on the firsfield ["this is the value1"] and SecondField["this is the value2"] and then autocomplete a thirdField as [firstfield + SecondField] and then after all that save this info in a model with firstField,SecondField and ThirdField. -
Creating dropdown menu in django for user created data only in a different class
I'm new to programming and my first language/stack is Python and Django. I have figured out how to create a dropdown menu in my Script form that is pointing to a different class "Patient" but I can't figure out how to only show me data that the current user created. I'm confused if I should set this in my models.py, forms.py or in the views.py? Here is what I have that I think should be working but it is not. (Tried setting in the views.py) Models.py class Patient(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) patient_name = models.CharField(max_length=40, unique=True) def __str__(self): return self.patient_name class Script(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, verbose_name='Primary Patient') So my patient field is my dropdown and it is looking at the Patient class grabbing the patient name string. Views.py class ScriptCreateView(LoginRequiredMixin, CreateView): model = Script template_name = 'script_new.html' success_url = reverse_lazy('script_list') fields = ( 'patient', 'drug_name', 'drug_instructions', 'drug_start_day', 'drug_start_time', 'drug_hours_inbetween', 'drug_num_days_take', ) #This sets user created fields only?? def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( author=self.request.user ) #This sets the author ID in the form def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form ) Forms.py class ScriptForm(forms.ModelForm): class Meta: model = Script fields = '__all__' #This … -
Deploy django to GAE standard from cloud build
I run following bash commands from my local machine to deploy django project to App engine. python manage.py migrate python manage.py collectstatic --noinput gsutil rsync -R static/ gs://xyz4/static gcloud config set project project_name_1 gcloud app deploy --quiet I would like to set it up on cloud build. I have enabled PUSH triggers on cloud build. Need help in creating cloudbuild.yaml file -
Django template {%url %} formatting
When I use {% url %} method to create link {% url app_name:sub_directory:url.linkfield %} it is producing error in the console i.e. raise TemplateSyntaxError("Could not parse the remainder: '%s' " django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ':staff:url.linkfield' from 'app_name:staff:url.linkfield' This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] my customer_url.py from application_name import views app_name="customer" urlpatterns=[ url(r"^items/",views.items, name='items'), url(r"^checkout/$", views.checkout, name='checkout'), url(r"^make_payment/$", views.make_payment, name='make_payment'), ] staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc Please what can i do -
Trouble mapping Django URLs
I've completed all of the sections of the Django tutorial and have started my own project now to practice. I am back at the beginning tutorial where it talks about views/mapping urls. I also am following this tutorial for trying to display a table For whatever reason, I cannot figure out why when I try to hit http://127.0.0.1:8000/show/, it returns 404. I've been staring at this for the last hour and have been going back and forth between the tutorial and my code. I had to do things a little bit differently than the 2nd mentioned tutorial, mainly that they didn't talk about creating an app level urls.py file. Everything up to this point has worked fine. The models.py file created the table within the mysql database, as I can see it in workbench. My project structure is like this: mywebsite (project) displaydata (app) Here is my project level urls.py file located in the mywebsite folder: from django.contrib import admin from django.urls import include,path urlpatterns = [ path('admin/', admin.site.urls), path('displaydata/', include('displaydata.urls')) ] Here is my app level urls.py file located in the displaydata folder: from django.urls import path from . import views app_name = 'displaydata' urlpatterns = [ path('', views.show, … -
Django Python current logged User
In my queryset I need to check status of post and if User mentioned in that post is the same as logged User. How can I get current logged User? queryset = Post.objects.filter(Q(status='Done') & (Q(person_1_username=current_logged_user) | Q(person_2_username=current_logged_user))) I know I should use something like code below, but I don't know how to get that value to 'current_logged_user' def my_view(request): username = None if request.user.is_authenticated(): username = request.user.username -
heroku can't migrat database: cannot cast type time without time zone to timestamp with time zone
I've got a Django app (running on Heroku ) with a simple form that contains a DateTimeField() the app work well locally, but after I push it to the heroku, and do heroku run python3 migrate, it will return an error : psycopg2.errors.CannotCoerce: cannot cast type time without time zone to timestamp with time zone LINE 1: ..." TYPE timestamp with time zone USING "date_added"::timestam... here is my models: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class BlogContent(models.Model): blogpost = ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField( auto_now_add=True) class Meta: verbose_name_plural = "blogcontents" def __str__(self): if len(self.text) > 50: return self.text[:50] + '...' else: return self.text from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class BlogContent(models.Model): blogpost = ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField( auto_now_add=True) class Meta: verbose_name_plural = "blogcontents" def __str__(self): if len(self.text) > 50: return self.text[:50] … -
Django query clause be included if data exist else be excluded
I have a query which I want to perform. If the query variable has some things in them the query should be presented. But if it does not have anything inside of them then it should be left blank Modelname.objects.raw("select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id and CASE %s WHEN None THEN #This place is basically empty ELSE tab1.name=%s END and CASE %s WHEN 0 THEN #This place is also basically empty ELSE tab1.year=%s END", [user_name,user_name,digit,digit]) -
Django fetching data with HttpOnly cookie says 401 (Unauthorized)
I have been trying to use HttpOnly cookie with Django for two days but couldn't solve it yet. I tried adding all of these to my settings.py file SESSION_COOKIE_HTTPONLY=True SESSION_COOKIE_PATH = '/;HttpOnly' LANGUAGE_COOKIE_HTTPONLY=True CSRF_COOKIE_HTTPONLY=True My home.html file fetch('http://127.0.0.1:8000/api/books/', { method: 'POST', mode: 'same-origin', credentials: 'include' // Do not send CSRF token to another domain. }).then(function(response) {response.json()}).then( event=>console.log(event) ) My api is working and i am signed in but it still gives me "401 (Unauthorized)" response. I searched in google for days and still couldn't solve it. I think i am missing something but don't know what -
How to connect Celery with redis?
I have taken a free trial for Redis and it gave me an endpoint with a password. I haven't done anything with Redis or celery before so I really don't have any idea how it works. From the Docs of Celery everyone connects to the local host but how can I connect to this endpoint? CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379' What should I replace this with? Where should I give the password? My endpoint looks something like this: redis-18394.c252.######.cloud.redislabs.com:18394, Should I add the password at the end of this after a / ? -
Djagno: form.is_valid() error, but only after "if request.method == 'POST'"?
When I print(formexam) BEFORE the "if request.method == 'POST'", it shows the appropriately filled out form items (the exam was created earlier, now I'm just updating it to make changes as desired). However, when I print(formexam) AFTER "", it shows the form fields (at least several of them, I didn't look at every single one) to be empty. What makes that happen? Also, a very very similar views.py function ("changeExam", bottom of this post) works just fine. Thank you! views.py def updateExam(request, pk): exam = Exam.objects.get(id=pk) formod = form_od.ODForm(instance=exam.od) formos = form_os.OSForm(instance=exam.os) formexam = ExamForm(instance=exam) print(f'The errors are: {formexam.errors}') if request.method == 'POST': formexam = ExamForm(request.POST, instance=exam) print(f'The errors are: {formexam.errors}') formod = form_od.ODForm(request.POST, instance=exam.od) formos = form_os.OSForm(request.POST, instance=exam.os) if formod.is_valid() and formos.is_valid(): print("these are valid") if formexam.is_valid(): print("so is this one.") else: print("Exam form not valid.") Results of hitting submit button: The errors are: The errors are: <ul class="errorlist"><li>doctor<ul class="errorlist">.<li>This field is required.</li></ul></li><li>examtype<ul class="errorlist"><li>This field is required.</li></ul></li></ul> these are valid Exam form not valid. However, this very similar one works: views.py def changeExam(request, pk): exam = Exam.objects.get(id=pk) form = ExamForm(instance=exam) if request.method == 'POST': form = ExamForm(request.POST, instance=exam) if form.is_valid(): print(form) form.save() -
How do you obtain the username in models, without sending the username from views?
I'm trying to include in a models class the username. When I send username from views, ie: in views.py def listing(request, name): return render(request, "auctions/listing.html", { "user": request.user.get_username() }) The above, makes it so that I'm no longer signed in when I visit listing.html Is there a way to return the user without changing the username on this page? The other thought I had was is there a way to just directly access the current user via models without returning anything to models from views. But the following returns errors, that models has no attribute... user = models.get_username() When I read the documentation here https://docs.djangoproject.com/en/3.2/ref/contrib/auth/ I thought it allows me to call get_username() from models as I'm doing above. Thanks -
In this setup, how do I inner join Product, ProductAttributes, and ProductAttributesValue? [Django models & view]
The first line of views.py is the Products queryset that I want to inner join with the next line of the views.py (the inner join of ProductAttributes and ProductAttributesValue) # models.py class Product(models.Model): title = models.CharField(max_length=255) class ProductAttributes(models.Model): name = models.CharField(max_length=255) class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) # views.py - just code fragments Product.objects.filter(categories=self.category) # Products only in selected category products_att = ProductAttributes.objects.filter(productattributesvalue__isnull=False) # Inner join of ProductAttributes and ProductAttributeValues - sent to context in view products_att = products_att.values("id", "name", "productattributesvalue__value") context['attribute_values'] = products_att -
(index):551 Uncaught ReferenceError: validateText is not defined
Just wondering if anyone could help me troubeshoot this error? I am currently working on building a chat application within Django. When I try to send a message within my chat, I receive the following error within the console: (index):551 Uncaught ReferenceError: validateText is not defined Here's the code within my template file from where the error seems to be originating from: var msgP = document.createElement("p") msgP.innerHTML = validateText(msg) msgP.classList.add("msg-p") div1.appendChild(msgP) Just to add in here - My knowledge of JQuery isn't the best, so I do apologise if this comes across as a silly question! Any suggestions would be welcome! :-) -
How to remove tags from RichTextField and calculate words saved in RichTextField Django?
Below is my model I want to calculate the word count in the RichTextField , I tried len(blog.content.split()) but the problem with this is that it doesn't removes the tags and calculates them too, whereas I want only the word count and not tags like <img> , <p> etc. title = models.TextField( verbose_name="title", blank=True ) tagline = models.TextField( verbose_name="tagline", blank=True ) content = RichTextField( verbose_name="content", blank=True ) image = models.TextField( verbose_name="image", blank=True )``` -
Can I concatenate two fields in a Django model to create a third field that will be the primary key for the Model?
I am trying to create a model in Django that will be used to hold records for a review form I am creating. This model will have numerous fields but at the moment I am concentrating on the primary key determination. I have two fields, "claim number" and "review type" that I would like to concatenate as "claim number | review type" as a string to create a third field in the model called "review name". I understand concatenation as I've done this to define full name on other fields using the first and last name fields in the model. Here's my model currently: class QualityReview(models.Model): claim_number = models.CharField(max_length=40) review_type = models.ForeignKey(ReviewType, on_delete=models.CASCADE) def ReviewName(self): return self.claim_number + " | " + self.review_type Is it possible to use that ReviewName def in a field called review_name?