Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to multi thread and do tasks in django?
I am working on a website based on Django. users can register and enter a URL, and my website should check and get some information from that URL, for example, every hour, how should I handle these tasks? how should I write the structure of my website? -
Python Django - compare datetime weeks
I have a queryset of objects with a DateTimeField and another queryset of objects with a DateTimeField. How can I find which objects from the first queryset A belong to the same week of an object of the queryset B. So, the queryset A is filled with events, and the queryset B is filled with objects representing weeks of the year. I'd like to map the events to their corresponding week object (the week object has a DateTimeField that is created on monday using datetime.today) I can imagine ways to solve this but there must be an elegant, better way. I'm using django 3.0.5, there is no way to create a query from its week number. -
Looking for the right way how to update existing object with form and Dynamic RadioSelect Choice in Django
I have been learning Django a few weeks. I am trying to render list of entries dynamically with possibility to choose one of them by Radio Select Choice. Chosen item has to update field in existing object model. I have tried a lot of ways to do it recently. I have written the code that render list of radio buttons dynamically but I have not figured out how to catch selected item and updated corresponding object in model with form. Could anyone help me to catch the idea which is the best way to render list of entries with radio buttons dynamically, select one of them and update corresponding field in existing object model. Thanks. ### Model class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='Comments_Article') author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField(max_length=500) chosen = models.BooleanField(default=False) ### View class ChooseComment(FormMixin, DetailView): model = Article template_name = 'comment_page.html' context_object_name = 'get_article' form_class = ChooseCommentForm def get_form_kwargs(self): kwargs = super(ChooseComment, self).get_form_kwargs() kwargs['article_object'] = self.get_object().id return kwargs def post(self,request, *args, **kwargs): id = request.POST['chosen'] obj = get_object_or_404(Comment, id=id) form = ChooseCommentForm(request.POST, instance=obj) if form.is_valid(): return self.form_valid(form) else: self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.chosen = … -
how can I detect the machine language in django?
So, I know that language = request.session.get(LANGUAGE_SESSION_KEY) gets language saved to session but my question is.. Is this the language used by the computer? and if not how can I detect the language used by my computer? -
how to store location in Point field using Mongo Engine and fetch nearest 5 restaurant around a location
I am new to mongoengine and trying to store location data into MongoDB using mongoengine , I am doing some silly mistake but not able to figure out. My requirement is to store location data into MongoDB and fetch all the restaurant a in 1000 Meter radius around a mobile device location My Model Class from mongoengine import * class ResLocation(Document): id = IntField(required=True) loc = PointField(required=False) updated_date_time = DateTimeField(default=datetime.datetime.utcnow) In the views.py saving the location `def store_restra_location(id, lat, lon): location = {type: "Point", "coordinates": [lat, lon]} res_location = ResLocation(id=id, loc=location) res_location.save()` Fetching the nearest restaurant def get_nearest_res(lat, lon): distance = 1000 # distance is in meters restaurants = ResLocation.objects(point__near=[lat, lon], point__max_distance=distance) all_res = [] for res in restaurants: all_res += [ { "id": res.id, "lat": res.lat, "lon": res.lon } ] I am a completely noob in dealing with Mongo with mongoengine -
python manage.py collectstatic - Digital Ocean - Django
I tried again to host my django project on digital ocean and I get this error after I send "python manage.py collectstatic". Can you help me interpret this error? I can't understand if it is correlated to my code in django or something that I wrote wrong during the process of hosting the project on the server. TRACEBACK (django_env) mattia@droplet:~/piattaforma$ python manage.py collectstatic 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/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect for path, storage in finder.list(self.ignore_patterns): File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/home/mattia/piattaforma/static' MY DJANGO PROJECT CODE piattaforma/settings.py """ Django settings for piattaforma project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ … -
Renaming a Django superclass model and updating the subclass pointers correctly
I'm having trouble refactoring a superclass in Django v2.12 involving three models, with one superclass model and two subclass models: class BaseProduct(models.model): # ... class GeneralProduct(BaseProduct): # ... class SoftwareProduct(BaseProduct): # ... The BaseProduct model needs to be renamed to just Product, so I changed this code to: class Product(models.model): # ... class GeneralProduct(Product): # ... class SoftwareProduct(Product): # ... And then ran python manage.py makemigrations, in which Django seems to correctly see what changed: Did you rename the buyersguide.BaseProduct model to Product? [y/N] y Did you rename generalproduct.baseproduct_ptr to generalproduct.product_ptr (a OneToOneField)? [y/N] Did you rename softwareproduct.baseproduct_ptr to softwareproduct.product_ptr (a OneToOneField)? [y/N] y Migrations for 'yourapp': .../yourapp/migrations/002_auto_20200507_1830.py - Rename model BaseProduct to Product - Rename field baseproduct_ptr on generalproduct to product_ptr - Rename field baseproduct_ptr on softwareproduct to product_ptr So far so good. The migration it comes up with looks about as terse as it should be: # Generated by Django 2.2.12 on 2020-05-07 18:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('yourapp', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='BaseProduct', new_name='Product', ), migrations.RenameField( model_name='generalproduct', old_name='baseproduct_ptr', new_name='product_ptr', ), migrations.RenameField( model_name='softwareproduct', old_name='baseproduct_ptr', new_name='product_ptr', ), ] This all looks perfect, but applying that migration using python manage.py migrate crashes out: … -
Can't post data from Angular 8 to Django
I'm trying to send data from Angular to Django and I keep getting the following error message in my browser: HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/polls/token", ok: false, …} error: error: SyntaxError: Unexpected token N in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:32795:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6802:31) at Zone.runTask (http://localhost:4200/polyfills.js:6579:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6876:34) at invokeTask (http://localhost:4200/polyfills.js:8014:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:8051:21) message: "Unexpected token N in JSON at position 0" stack: "SyntaxError: Unexpected token N in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:32795:51)↵ at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6802:31)↵ at Zone.runTask (http://localhost:4200/polyfills.js:6579:47)↵ at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6876:34)↵ at invokeTask (http://localhost:4200/polyfills.js:8014:14)↵ at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:8051:21)" __proto__: Error text: "None" __proto__: Object headers: HttpHeaders lazyInit: () => {…} lazyUpdate: null normalizedNames: Map(0) {} __proto__: Object message: "Http failure during parsing for http://localhost:8000/polls/token" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:8000/polls/token" __proto__: HttpResponseBase Here is my Angular frontend: data.service.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; const httpOptions = { withCredentials: true, }; const test = 'test'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) { } public sendPostRequest(){ return this.http.post("//localhost:8000/polls/token", test, httpOptions); } } here's an excerpt of … -
Django: How to load form to current html page
I am trying to load a form into my page without redirect to other pages. I am using jquery. but nothing happens and I missing something very small I bet. so.. I have a popup that I want the templete to load into. my template that tries to show in my div: 1) i dont know if i need to use the {% block content %} dayform.html (templete) {% block content %} <form action="{% url 'dayform' %}" method='post'> {% csrf_token %} {{form.as_p}} <button name='submit'>Submit</button> </form> {% endblock %} urls.py path('calendar/dayform', views.addnewevent, name='dayform'), views.py def addnewevent(request): if request.method != 'POST': form = Eventform() else: form = Eventform(request.POST) if form.is_valid(): form.save() return redirect('controlpanel') context = {'form': form} return render(request, 'studentform/dayform.html', context) jquery $('.badge').get( "{% url 'dayform' %}", function(data) { $('#myform').html(data) } ); the badge is link clickable, I don't know if I should use "get" or "click" -
Updating multiple objects at once with a filter in django
The query below filters a queryset of Credentials objects based on these creds and updates the password of a Credentials object with the password that the user put in the form. This works and it updates the password, the problem with this is that it only updates one object, since no more than one object can have the same pcol, user, pcol_user, data_source, and username. creds = Credentials.objects.filter(pcol=pcol, user=user, pcol_user=pcol_user, data_source=data_source,username=username).update(password=password) The query below is what Im trying to do, filter only on these creds since I want to filter multiple objects. If I were to create two objects with the same pcol, user, pcol_user, username, and data_source I wouldn't be able to since they have the same exact creds. In contrast, if I created an object where the user, pcol_user, username, and data source are the same as another object, and the protocol is different it doesn't care and I am able to create the object with no problem. My objective is to update an object based on the user, pcol_user, username, and data source that the user enters. I have tried the query below on two sample objects, where the user, pcol_user, username, and data_source of those two … -
How to show paginated data from 3 different models?
I have three Django models. Person: Fields first_name, last_name, date_of_birth, gender, profile_pic (Nullable), created_at, modified_at PersonStatus: Fields person (fk Person), status_text, created_at, modified_at FormulaFields: formula(TextField that is able to store python code of up to 2000 characters), column_number (Integer >=4), created_at, modified_at. I need to show a paginated table with the same data, Person ID First Name Last Name Person Status: Latest Status of Person Full Name Is Adult (Adult if person > 18 years of age) Profile Pic (Icon) if available For populating columns 5 and 6, I need to add the code in the FormulaFields model. For displaying Person Status, I need to use Subquery and OuterRef (maybe my tech lead is asking so that I learn?) I did pagination with one model and it works, but how do I show the data which are in three different models? Here is my view. I've been stuck on this, please do help. class FileExamListView(generic.ListView): model = Person template_name = "exam_list.html" def get_context_data(self, **kwargs): context = super(FileExamListView, self).get_context_data(**kwargs) list_exam = Person.objects.all().order_by('date_of_birth') paginator = Paginator(list_exam, self.paginate_by) page = self.request.GET.get('page') try: file_exams = paginator.page(page) except PageNotAnInteger: file_exams = paginator.page(1) except EmptyPage: file_exams = paginator.page(paginator.num_pages) context['person'] = file_exams return context I also looked … -
Blog post with image Django3
Hi i'm trying to add some funcionality to my blog post app, i'd like to paste image into post content so i figured is this waw that ive created new model just for images and set it as OneToOne with my Post model i wonder if ther is any way to set this image to content field in the post model models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class PostImage(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE) image = models.ImageField(default=None, upload_to='post_pics', blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: output_size = (500, 500) img.thumbnail(output_size) img.save(self.image.path) vievs.py def home(request): context = { 'posts': Post.objects.all(), 'user_posts': "active", } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 post_template.html {% extends "blog/base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
Weasyprint/Cairo loses SVG text labels when converting to PDF
I have an SVG image generated by Bokeh (link here) with labels on the left and bottom of the chart. The image itself shows the text within the chart just fine, however, when converting to PDF through Weasyprint, the text is lost. Has anyone else encountered a similar issue? I'm not sure how to debug this as there are no errors when converting. A snippet of my export function: html = HTML(string=html_string) result = html.write_pdf('./tmp/example.pdf', stylesheets=[css], font_config=font_config) Within the HTML template, I use css to embed the image as a background image as so: html body article#columns section#linechart{ width: 100%; background: url(./tmp/linechart.svg) no-repeat center; background-size: contain; margin: 0; height: 500px; overflow: visible; } Thanks in advance! Current version info: CairoSVG = 2.4.2 Weasyprint = 51 Python = 3.73 -
How can I create redirect button with post method in Django template
I'm trying to create a button in the Django template which will redirect to another URL. But getting error 404 since Django can't recognize URL path rescribed in the urls.py. HTML part <form method="post" action='sts'> {% csrf_token %} <button class="btn btn-outline-success my-2 my-sm-0" type="submit" name="cts_link">cts</button> </form> urls.py from django.conf.urls import include, url from django.contrib import admin from rtRegRes.views import units from rtRegRes.views import spartan urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^units/$', units), url(r'^units/sts/?$', spartan), ] views.py from django.shortcuts import render, redirect, reverse, render_to_response from .models import rt_reg_res from django.http import HttpResponse, JsonResponse def units(request): """Return main webpage""" return render_to_response('runtime.html') def spartan(request): """Link to the other unit webpages""" table = rt_reg_res.objects.all() if request.method == 'POST': qatables = request.POST.get("cts_link") if qatables: return render(request, 'cts.html', {'table': table}) Clicking the button following error message appears: enter image description here Could somebody point me what is wrong in my code Thanks -
I'm trying to connect customer to User but getting this error: AttributeError at /user/' User' object has no attribute 'Customer
I'm trying to get the user data from Customer model. For this I also connect the Customer to User which I import from django.contrib.auth.models. But getting this error: AttributeError at /user/ 'User' object has no attribute 'Customer' at views page: @login_required(login_url='login') def user_page(request): orders=request.user.Customer.order_set.all() context={'orders':orders} return render(request, 'blog/user_page.html', context) at models page from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): User=models.OneToOneField(User, null=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField() phone=models.IntegerField(null=True) date_created=models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name -
Styling HTML for model property with verbose name in Django admin
I have a Django model like this: class MyModel (models.Model): value = IntegerField() def custom_field(self): return self.value + 1 Then in my admin.py file, I have a model: class MyModelAdmin(admin.ModelAdmin): list_display = ('id', 'custom_field') def custom_field(self, obj): if obj.total_counter_actual != obj.total_counter: color = 'red' return format_html( '<b style="color:{};">{}</b>', color, obj.custom_field ) else: return obj.custom_field custom_field.short_description='My custom column name' Although column name (implying analogue of verbose name) and styling both work as exepcted, instead of values I see something like <bound method MyModel.custom_field of <MyModel: TEST_VALUE>>. Any way to fix this? -
linking miniconda environment to wsgi.py django apache windows deployment?
I was following this guide to deploy Django app on windows. I'm using miniconda environment as my environment how should I link it in my windows_wsgi.py file i tried activate_this = 'C:/ProgramData/Miniconda3/envs/sentizer/python.exe' # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) but I get this error in the logs Traceback (most recent call last):\r File "C:/Users/Administrator/Eyelizer/Eyelizer/wsgi_windows.py", line 3, in <module>\r exec(open(activate_this).read(),dict(__file__=activate_this))\r File "c:\\programdata\\miniconda3\\envs\\sentizer\\lib\\encodings\\cp1252.py", line 23, in decode\r return codecs.charmap_decode(input,self.errors,decoding_table)[0]\r UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined>\r mod_wsgi (pid=4268): Failed to exec Python script file 'C:/Users/Administrator/Eyelizer/Eyelizer/wsgi_windows.py'. mod_wsgi (pid=4268): Exception occurred processing WSGI script 'C:/Users/Administrator/Eyelizer/Eyelizer/wsgi_windows.py'. -
Why is my login_required redirect not working?
I seem to be doing everything correctly, yet I am still receiving a 404 when I try to login into a page that is login_required only rather than being redirected to the login page. Settings.py/Login_url LOGIN_URL = '/dating_app/login/' dating_app/urls/login path('login/', LoginView.as_view(template_name = 'dating_app/login.html'), name='login'), project_urls/dating_app path('', include('dating_app.urls', namespace= 'dating_app')), project_directory . ├── 11_env │ ├── bin │ ├── include │ ├── lib │ └── pyvenv.cfg ├── dating_app │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── chat.html │ ├── forms.py │ ├── media │ ├── migrations │ ├── models.py │ ├── static │ ├── tag.py │ ├── templates │ ├── templatetags │ ├── tests.py │ ├── urls.py │ └── views.py ├── dating_project │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 └── manage.py -
How to return a token with graphql jwt upon user sign up
I'm wondering how can I return a token instead of a user. I'm using graphql-jwt for signing in and I don't want to have to sign up a user then sign-in them in the fronted I want a token to be returned upon successful signup from django.contrib.auth import get_user_model import graphene from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = get_user_model() class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: username = graphene.String(required=True) password = graphene.String(required=True) email = graphene.String(required=True) def mutate(self, info, username, password, email): user = get_user_model()( username=username, email=email, ) user.set_password(password) user.save() return CreateUser(user=user) class Mutation(graphene.ObjectType): create_user = CreateUser.Field() -
Deploying a Django app to Heroku: H14 - No web dynos running
I have deployed my app successfully on heroku following the "Getting Started" documentation. After deployment ended, I entered: heroku ps:scale web=1. But in return I got : Scaling dynos... ! ▸ Couldn't find that process type (web). I printed my logs and I got: 2020-05-07T16:55:45.691324+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=thawing-retreat-70669.herokuapp.com request_id=08bf5ac4-dc36-404d-98a3-dd3434084a44 fwd="90.2.155.70" dyno= connect= service= status=503 bytes= protocol=https And heroku ps Free dyno hours quota remaining this month: 548h 53m (99%) Free dyno usage for this app: 0h 0m (0%) For more information on dyno sleeping and how to upgrade, see: https://devcenter.heroku.com/articles/dyno-sleeping No dynos on ⬢ thawing-retreat-70669 I've read that it may be my Procfile; I have one that reads: web: gunicorn pur_beurre.wsgi --log-file- I've checked the builpacks and I got: heroku/python -
Add request user to InlineFormSet: TypeError: __init__() got an unexpected keyword argument 'user'
I'm using InlineFormSetView from extra_views to create a custom inlineform. On form save I need to make some changes that's relevant to the request user. So the request user is required in the form. From what I found, I came up with this solution but it seems that get_formset_kwargs may be used elsewhere. Causing an exception to occur. I'm not quite sure what is the cause. May be there is another solution to adding request user to an inline form. View: class MyModelSetsView(InlineFormSetView): model = MyModel inline_model = MySubModel form_class = MySubModelSetForm template_name = "update_sets.html" success_message = "Updated successfully." permission_required = [] factory_kwargs = { 'extra': 1, } def get_success_url(self): return self.object.get_absolute_url() def get_formset_kwargs(self): kwargs = super(MyModelSetsView, self).get_formset_kwargs() kwargs.update({'user': self.request.user}) return kwargs Form: class MySubModelSetForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PeakPeriodSetForm, self).__init__(*args, **kwargs) Exception: File "..\venv\lib\site-packages\extra_views\formsets.py", line 268, in get formset = self.construct_formset() File "...venv\lib\site-packages\extra_views\formsets.py", line 36, in construct_formset return formset_class(**self.get_formset_kwargs()) File "...\venv\lib\site-packages\django\forms\models.py", line 897, in __init__ super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs) File "...\venv\lib\site-packages\django\forms\models.py", line 569, in __init__ super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs}) TypeError: __init__() got an unexpected keyword argument 'user' -
Django 3: AttributeError: 'AdminSite' object has no attribute 'Register'
AttributeError: 'AdminSite' object has no attribute 'Register' when i go to make migrations and open my admin section to add so dummy info and image I receive the error. admin.site.Register(Bet, BetAdmin) What I have done so far is delete and hit return to see if it was indentation mistake on the class. I also installed pylint to see more details on errors based on the one suggested answers. Class has no objects member pip install pylint-django then I added to my setttings.json { "terminal.integrated.shell.windows": "C:\\WINDOWS\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe", "workbench.colorTheme": "PowerShell ISE", "python.pythonPath": "C:\\Users\\taylo\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe", "json.schemas": [ ], "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ], "[python]": { } } but it didn't seam to solve anything related to issue. FYI: I did a bunch of searches and view on stack and but solutions seen where for spelling errors ased on the word being spelled incorrectly with q like reqister instead of register is and was not spelled wrong. the full terminal error (venv) PS C:\Users\taylo\django\pybet_project> python manage.py makemigrations 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\taylo\django\pybet_project\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\taylo\django\pybet_project\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\taylo\django\pybet_project\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) … -
Django get template id tags values from view
In my project i have a template for example like this: ... <div class="row no-gutters row_app" id="first_id"> <div class="col-12 bg-066AB3" id="second_val"><img src="{% static "img/Icona_Medico.png" %}"></div> <div class="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 bg-BCBCBB"> <div class="row no-gutters" id="Other_val"> <div class="col-12 d-xl-flex justify-content-xl-center align-items-xl-center"> <div class="width_100 box_testo"> ... well, i would then when in my views.py all start a python function that check every values of ids in my template and put its in a list: def index(request, **kwargs): ids_val = [] #Here a function that return the template ids value and put into my ids_val list context_dict = {} response = render(request, 'base_home.html', context_dict) return response Someone know how is possible extract id template tags values from my django template? So many thanks in advance -
How do I make Django form fields required conditionally?
I am new to Django and I am trying learn about creating web apps. I am trying to delete a record without the form fields being required. I only want them to be required when creating a new record. Here is a screen shot: enter image description here Here is my form.py: from django import forms class ExpenseForm(forms.Form): name = forms.CharField( max_length=255, widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "Expense Name" }) ) amount = forms.DecimalField( max_digits=16, decimal_places=2, widget=forms.NumberInput(attrs={ "class": "form-control", "placeholder": "$400.00" }) ) Here is my view.py: from django.shortcuts import render from budget.models import Expense from .forms import ExpenseForm from django.http import HttpResponse, HttpResponseRedirect from django.db.models import Sum def budget_view(request): expenses = Expense.objects.all() total = Expense.objects.aggregate(total=Sum('amount'))['total'] form = ExpenseForm() if request.method == 'POST': form = ExpenseForm(request.POST) if form.is_valid() and 'create-expense' in request.POST: expense = Expense( name=form.cleaned_data["name"], amount=form.cleaned_data["amount"] ) expense.save() return HttpResponseRedirect('/') elif form.is_valid() and 'edit-expense' in request.POST: return HttpResponseRedirect('/') else: expense = Expense.objects.get(id=request.POST.get("delete-expense")) expense.delete() return HttpResponseRedirect('/') context = { "form": form, "expenses": expenses, "total": total, } return render(request, "budget_view.html", context) I tried adding form.fields[<field_name>].required() = False to the else block, but to no avail. Do I need to create a custom clean() in the form.py to perform validation on each field … -
Getting python usage errors using Django to display a table of files in a directory
So I am trying to get Django to display a template that shows a list of files on a local directory. My views.py looks like this: from django.shortcuts import render from django.http import HttpResponse from os import listdir def index(request): files = listdir("/path/to/directory/") filelen = len(files) return render(request, 'path/to/template.html') My html template looks like this: {%for i in range(1, filelen)%} <tr> <td>{{i}}</td> <td>{{files[i]}}</td> {% if "a" in files[i] %} <td>✓</td> {% else %} <td>x</td> {% endif %} {% if "b" in files[i] %} <td>✓</td> {% else %} <td>x</td> {% endif %} But when I try to run it I get the following error: Error at line 39 'for' statements should use the format 'for x in y': for i in range(1, len_files) Anybody know how to get this to work? I have tried replacing filelen with {{filelen}} but that gave me the same error.