Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
putting dictionary values inside a table in Django template
Its my first time using Django template. I'm trying to make a table inside my page with values from a dictionary that I built consuming an API. Here is how I'm sending the data inside my views.py: data = { "year_most_launches": result_launches, "launch_sites":response_sites, "launches_2019_2021":response_2019_2021 } return render(request,"main/launches.html", {"data":data}) Here is how it is my html page: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> <tr> <td>{{ data["year_most_launches"] }}</td> <td>{{ data["launch_sites"] }}</td> <td>{{ data["launches_2019_2021"] }}</td> </tr> </tbody> </table> But I'm getting the following error django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '["year_most_launches"]' from 'data["year_most_launches"]' How can I solve this? Can someone help? -
Filtering in Django which depends on first field
>Suppose I have 3 fields of a Car Shop. those are Condition, Brand, Model . class Car(models.Model): ConditionType=( ('1','New'),('2','Used'),('3','Reconditon') ) BrandType=( ('Toyota','Toyota'),('Honda','Honda'),('Mitsubishi','Mitsubishi'), ('Nissan','Nissan'),('Hyindai','Hyindai')) >now model will depends on Brand user select . if user select Toyota as brand then >available model for toyota are (Axio,Premio ,Allion etc) ,for Honda carmodels are (civic >,vezel,Grace) Condition=models.CharField(max_length=120,choices=ConditionType,default='New') Brand=models.CharField(max_length=120,choices=BrandType,default=None) Condition=models.CharField(max_length=120,choices=ConditionType,default='New') CarModel=models.CharField(max_length=120,choices=ModelType,default=None) Now how can I make carmodel dependent on Brand . Suppose if user choose Brand - Toyota >then user can only choose Carmodel of Toyota if user Choose Honda than he can choose >CarModel of Honda . which means how can I make my model selection dependent on Brand ? if no brand is selected than user won't able to choose CarModel .** -
erro h14 do heroku
fiz o deploy com sucesso no heroku , criei as tabelas e o super user , mas não tem nenhuma execução web ate o momento... mostra esse erro h14 e as tags abaixo heroku logs 2010-09-16T15:13:46.677020+00:00 app[web.1]: Processing PostController#list (for 208.39.138.12 at 2010-09-16 15:13:46) [GET] 2010-09-16T15:13:46.677023+00:00 app[web.1]: Rendering template within layouts/application 2010-09-16T15:13:46.677902+00:00 app[web.1]: Rendering post/list 2010-09-16T15:13:46.678990+00:00 app[web.1]: Rendered includes/_header (0.1ms) 2010-09-16T15:13:46.698234+00:00 app[web.1]: Completed in 74ms (View: 31, DB: 40) | 200 OK [http://myapp.heroku.com/] 2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204" dyno=web.1 connect=1ms service=18ms status=200 bytes=975 2010-09-16T15:13:47.893472+00:00 app[worker.1]: 2 jobs processed at 16.6761 j/s, 0 failed . -
How Not to render visible
i want to define this function not to render as default. Right now with connect with html template i am seeing this field as default, how to not make as default visible def check(self, obj): return format_html( "<ul>{}</ul>", format_html_join( "\n", "<li>{}</li>", obj.tee_rates.values_list( "tee__name__chek__short_name", ), ), ) -
Django-Rules working in some apps views but not others
I am integrating Django-Rules into my project for object-level permissions. Once I got it configured, I was initially successful in getting it to function properly for my Users and Profiles apps-models/views. I just cannot figure out why it won't work for my others apps-models/views. I've written the predicates and when I run them independently in the shell they return True. However, when I try to access the view it returns a 403 and the debugger doesn't even indicate that the rules were checked. I have been working on this for 2 days and would appreciate any insight offered. profiles rules.py import rules @rules.predicate def is_patient(user, profile): return profile.user == user @rules.predicate def is_provider(user, profile): return getattr(profile.user.patientprofile, "provider") == user change_profile = is_patient|is_provider view_profile = is_patient|is_provider rules.add_rule('can_edit_profile', change_profile) rules.add_rule('can_view_profile', view_profile) When User enters view with correct permission, console logs: | Testing (is_patient | is_provider) | is_patient = True | (is_patient | is_provider) = True When User enters view with incorrect permission, console logs: | Testing (is_patient | is_provider) | is_patient = False | is_provider = False | (is_patient | is_provider) = False profiles views.py ... from rules.contrib.views import PermissionRequiredMixin ... class MedicalProfileUpdate(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UserDetailRedirectMixin, UpdateView): model = MedicalProfile permission_required = … -
django html: how to center the login form?
my login form is not looking good, it's too wide. how to make it smaller and center in the middle of the page? signin html: {% extends "accounts/_base.html" %} {% block title %} Sign In {% endblock %} {% block control %} <form class="form-signin" action="{% url 'login' %}" method="post"> {% csrf_token %} <h2 class="form-signin-heading">Sign In</h2> <div class="form-group"> <div class="fieldWrapper"> {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} </div> <div class="fieldWrapper"> {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} </div> </div> <label for="signIn" class="sr-only">Click</label> <button id="signIn" class="btn btn-lg btn-primary btn-block" >Sign In</button> </form> <form class="form-signin" action="{% url 'signup' %}"> <button id="signUp" class="btn btn-lg btn-default btn-block">Sign up now!</button> </form> {% endblock %} base html: <!DOCTYPE html> <html lang='en'> <head> <meta CharacterSet='UTF-8'> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> {% load static %} <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="{% static 'js/main.js' %}"></script> {% block script %}{% endblock %} </head> <body> <!-- head --> <nav id="navbar" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand mb-0" href="#">Pizza</a> </div> {% if user is not none %} <div id="navbar-collapse" class="collapse navbar-collapse"> <ul class="nav … -
mock queryset in Django unittest
I have sample code and test: queryset_response = something.object.filter(foo="bar", foo1="bar1") for count, queryset_res in enumerate(queryset_response): store = queryset_response[0].data print(store) I wanna test this situation using mock and probably return list of queryset using mock if possible. m_queryset = Mock() m_queryset.filter.return_value = #<queryset> if possible # also I wanna return data for the 0th value to test store = queryset_response[0].data m_queryset.filter().data.return_value = "some string" # i tried sending dict into m_qeueryset.filter.return_value. nothing works. -
Django admin allow to sort postgres DateTimeRangeField
Say I have the following model: from django.contrib.postgres.fields import DateTimeRangeField class Record(models.Model): .... range = DateTimeRangeField() When I add the model to admin, the range field is not sortable, even I explicitly declared in sortable_by attribute. Please note the range field can be used for "order by" in raw query. Any ideas how to enable sort on this field? -
How not to visible all columns as default
Hi with this code i can see all the columns as default but how to make the column as visible not default. {% block object-tools %} <ul class="grp-object-tools"> {% block object-tools-items %} {% if has_add_permission %} {% url opts|admin_urlname:'add' as add_url %} <li><a href="{% add_preserved_filters add_url is_popup to_field %}" class="grp-add-link grp-state-focus">{% blocktrans with opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}</a></li> {% endif %} {% endblock %} </ul> {% endblock %} -
PostgresQL Query totally baffling me
I'm dealing with a django-silk issue trying to figure out what it won't migrate. It says all migrations complete and then when I run my code it gives me a warning that I still have 8 unapplied migrations, despite double checking with python manage.py migrate --plan. I'm pretty stumped at this point so I began setting up queries to just populate the db with the info already. And now the query is giving me a syntax error that for the life of me I can't understand! Hoping there are some Postgres masters here who can tell me what I'm missing. Thanks! Here's the query: -- Table: public.silk_request -- DROP TABLE IF EXISTS public.silk_request; CREATE TABLE IF NOT EXISTS public.silk_request( id character varying(36) COLLATE pg_catalog."default" NOT NULL, path character varying(190) COLLATE pg_catalog."default" NOT NULL, query_params text COLLATE pg_catalog."default" NOT NULL, raw_body text COLLATE pg_catalog."default" NOT NULL, body text COLLATE pg_catalog."default" NOT NULL, method character varying(10) COLLATE pg_catalog."default" NOT NULL, start_time timestamp with time zone NOT NULL, view_name character varying(190) COLLATE pg_catalog."default", end_time timestamp with time zone, time_taken double precision, encoded_headers text COLLATE pg_catalog."default" NOT NULL, meta_time double precision, meta_num_queries integer, meta_time_spent_queries double precision, pyprofile text COLLATE pg_catalog."default" NOT NULL, num_sql_queries integer … -
Date filtering not working in django queryset
The queryset needed is so basic I am stumped as to why this is not working Basic layout class ExampleModel(models.Model): ... date = models.DateTimeField() # this field is filled by an API It is a valid datetime field such that when I pull it individually and check data by actions like .day or .year it works fine. When I pull one individual record and do `type(record.date), it a datetime.datetime object. It does not have second or millisecond data. I do not know if this is the reason behind my results. For example here is the output of one of the records datetime.datetime(2022, 4, 21, 15, 32, 59) I just want to fetch all the entries for a given day. Thats it. In my code I specify todays date at time 00:00:00 via const_today = datetime.combine(datetime.today(), time(0,0,0), tzinfo=timezone.utc) I have tried almost every method. ExampleModel.objects.filter(date__date = today) ExampleModel.objects.filter(date__day = today.day) (just to see if even this would work even though i know it should pull up other months on this day) I have done date__gte and date___lte date__range[const_today, const_today+timedelta(days=1)] I have flicked USE_TZ in django settings on and off And basically every other method on stackoverflow with exception to building a … -
Error when autocreating slug in django models
This is my model: class post (models.Model): title = models.CharField(max_length=200) post = models.CharField(max_length=75000) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") show_date = models.DateTimeField() slug = models.SlugField(editable=False) def save(self, *args, **kwargs): to_slug = f"{self.title} {self.show_date}" self.slug = slugify(to_slug) super(Job, self).save(*args, **kwargs) When I run my website and try to add an item from the admin portal, though, I get this: NameError at /admin/blog/post/add/ name 'Job' is not defined I got the autoslugging part from here, what is 'Job' that I have to define? -
Unknown field(s) (groups, user_permissions, date_joined, is_superuser) specified for Account
I just try add "is_saler = models.BooleanField(default=False)" into class Account and migrate. And now i got the error when trying to change the superuser data. The line "is_saler = models.BooleanField(default=False)" had been deleted but still got this error after migrate. from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) data_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def … -
Django Serialize a JsonField, Django Rest API
I have a class for example from django.forms import JSONField class Area(models.model): GeoJson = JSONField ... and a serializer for the class class AreaSerializer(serializers.ModelSerializer): model = Areas fields = ('GeoJson', ... ) but when I try to get the data from my rest frame work I get this error Object of type 'JSONField' is not JSON serializable What am I doing wrong? it is my first time using django and I need to store GeoJson in the database so im really stuck on how to fix this issue as I dont understand why it wont work, Any help or advice is greatly appreciated. -
How to run a Django's application server on a VPS server
I have an application that should run via VPS terminal-based so that the web app can be online permanently. The command: python manage.py runserver 173.249.8.237:8000 should be executed via the VPS terminal because when I use putty via my laptop, whenever I switch off my putty software via my laptop, the application won't be accessible. Please, suggest to me a way open a terminal in order to run the Django application server. Or, is there any method that can allow me to my Django web application on VPS? Thanks in advence -
form pot URL not defined in URLconf
I have a form that is on the URL: http://127.0.0.1:8000/disciplineReport/1/ where 1 is the primary key of the object I'm editing. detail.html: <form method="post" id="edit-form" action="{% url 'disciplineReport:saveDiscipline' doctor.id %}}"> urls.py: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/saveDiscipline/', views.SaveDiscipline, name='saveDiscipline'), ] Error: Using the URLconf defined in program_history_reports.urls, Django tried these URL patterns, in this order: disciplineReport/ [name='index'] disciplineReport/ int:pk/ [name='detail'] disciplineReport/ int:pk/saveDiscipline/ [name='saveDiscipline'] admin/ The current path, disciplineReport/1/saveDiscipline/}, didn't match any of these. What am I missing here? it seems like the URL matches the 3rd pattern... -
TypeError : Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x00000000044871C0>'
Good time of day. I am an aspiring Django developer. When working on a project, I ran into a problem, and I don't have any older comrades. Could you help me with her? I am developing a small store and when adding a product to the cart I get this error. I've already tried everything and I'm just desperate Field 'id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x00000000044871C0>'. models.py # Категория продукта class Category(models.Model): name = models.CharField('Категория', max_length=100) url = models.SlugField(max_length=100, unique=True, db_index=True) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not self.url: self.url = slugify(self.name) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('product_list_by_category', args=[self.url]) class Meta: verbose_name = "Категория" verbose_name_plural = "Категории" # Папка продуктов для каждой организации def products_image_path(instance, filename): return f'organisations_{instance.organisations.name}/products/{filename}' # Продукт class Products(models.Model): name = models.TextField(max_length=100, blank=False) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to=products_image_path, blank=True) number = models.PositiveIntegerField('Количество') price = models.DecimalField('Цена', max_digits=10, decimal_places=2) category = models.ForeignKey(Category, verbose_name='Категория', blank=False, on_delete=models.SET_NULL, null=True) organisations = models.ForeignKey(Organisations, related_name="org_info", on_delete=models.CASCADE) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Products, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('product_detail', args=[self.id, self.slug]) class Meta: verbose_name = "Продукт" verbose_name_plural = "Продукты" ordering = ('name',) index_together = (('id', 'slug'),) … -
Can't call / pass data from django database onto website using built in auth model and a model I created, which is the one I cant query
Any help would be appreciated, basically I am a beginner and I'm struggling to pull data from my database. I used the built in auth method from django, which seemingly works ok as I can pull user data. However as soon as I want to use my Member class I made in models nothing seems to work. Can't output all its data. When looking at the admin page I see authentication and authorisation table and my Members table created in models.py. When I try pass into the context however nothing is displayed. My index.html {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! Hi {{ user.email }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> Hi {{ all }}! <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} {% block title %}Home{% endblock %} My Views.py from django.shortcuts import render from .models import Member # Create your views here. def index(request): all_members = Member.objects.all return render(request, 'index.html', context = {'all':all_members}) def ethos(request): return render(request, 'ethos.html', {}) Models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Member(models.Model): phoneNumber = PhoneNumberField() firstName = models.CharField(max_length=50) … -
How can I solve the issue: psql cannot connect to the server in Ubuntu?
In hosting my Django web application on VPS using PostgreSQl. However, the configuration seems to be fine but whenever I want to access the Postgres Shell, I ma getting the error bellow. root@vmi851374:~# sudo su -l postgres postgres@vmi851374:~$ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? postgres@vmi851374:~$ I have checked the Postgres service status and everything seems fine but I don't know where this error comes from. Notice that in my localhost (laptop), I am not facing this issue. Only in the VPS server, I am getting this issue. Please assist me to solve this issue. -
Saving encrypted file using python django
How can we save an encrypted file using python django.. In models field i used FileField to save encrypted file.. but it is not correct.. instead of file field which field can i use.. and How can we save an encrypted file using python django? -
Uploaded file type check in django
I want to design a form in django that takes a text file as input and does some processing using it. I have written the following HTML file. <!DOCTYPE html> <html> <body> <h1>Transcript To Voiceover Convertor</h1><br/> <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} <label for="document"> <b> Select a text file: </b> </label> <br/> <input type="file" name="document"> <br/><br/><br/> <!--<input type="file" accept="text/*" name="document"> <br/><br/><br/>--> <b> Select a gender for the voiceover </b> <br/> {{ form }} <br/><br/><br/><br/> <input type="submit" value="Submit" /> </form> </body> </html> As you can see, one of the input line is uncommented and the other one is commented. So basically, in the commented line I tried to use the accept attribute with text MIME but the problem I am facing is that in this case the browser only detects files with .txt extension but in Operating system like Ubuntu/Linux it is not necessary for text files to have .txt extension. So when I am using the commented line for input it is not able to detect those files. So, can someone please suggest me what should I do? My second problem is related to the first one. So, as you must be knowing that having a check on the … -
What python packages am I missing?
I'm trying to get my local windows 10 pc up and running with my django application. I'm a novice at python and django. My app was written by another developer who's been very helpful and has limited availability. I also want to sort it out myself for learning purposes. I'm including as much information as I can. I can add more if needed. I'm at my wit's end. I downloaded my code from bitbucket and loaded all of the packages in the base.txt and development.txt files onto my windows 10 pc. I keep getting several errors when trying to run the server. App is using in the following: python 3.61 django 1.11.3 base.txt file: boto3==1.4.7 celery==4.1.0 click==6.7 dateutils==0.6.6 Django==1.11.3 django-anymail==0.11.1 django-cors-headers==2.1.0 django-countries==5.0 django-filter==1.0.4 django-solo==1.1.3 django-storages==1.6.5 djangorestframework==3.6.3 djoser==0.6.0 kombu==4.1.0 mysqlclient==1.3.10 Pillow==4.3.0 python-dotenv==0.6.4 python-magic==0.4.13 pytz==2017.2 redis==2.10.6 uWSGI==2.0.15 xlrd==1.2.0 I don't get any errors loading the packages; however, when I run the server I get this screenful of error msg vomit: (venv) C:\Users\romph\dev\EWO-DEV\backend>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors..wrapper at 0x000002A64687E0D0> Traceback (most recent call last): File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\romph\.pyenv\pyenv-win\versions\3.6.1\lib\site-packages\django\core\management\base.py", line 359, in … -
update field based on another table django
hello I have to models I want to run a query every day to update a total field in a weekly table in some conditions first user ids should be equal then start_date in weekly table and date in daily table should be in the same week please help class Daily(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE,) total = models.FloatField(default=0) date = models.DateField(blank=True, null=True,) class Weekly(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE,) total = models.FloatField(default=0) start_date = models.DateField(blank=True, null=True,) -
Unable to runserver due to the error mentioned below
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/Desktop/cookiecutter/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace '_PQbackendPID' -
web socket in django showing error 10048
Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.