Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get ETA when fetch data from postgres?
I have Django project and in some view users can select what data their want to fetch from DB. But when query is large and fetching take some time ~ 10min users dont know there is an error or just fetching time. How can i get aproximatelly execution time when fetching data from postgres? And how can i display that? -
Django | Not Found issue while updating record
Other Coding I did ***urls.py of web app path adding ***: path('update/updaterecord/int:id', views.updaterecord, name='updaterecord'), views.py file of web app : update coding info: def updaterecord(request, id): first = request.POST['first'] last = request.POST['last'] member = Members.objects.get(id=id) member.firstname = first member.lastname = last member.save() return HttpResponseRedirect(reverse('index')) -
Python Django Rest - Return extra field with lowest, highest and average values of some other field
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. Here's what I want to do: Endpoint to age range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/age/ Response: { "younger": { "id": "1", "name": "Anakin Skywalker", "email": "skywalker@ssys.com.br", "department": "Architecture", "salary": "4000.00", "birth_date": "01-01-1983"}, "older": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "average": "40.00" } Endpoint to salary range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/salary/ Response: { "lowest ": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "highest": { "id": "3", "name": "Leia Organa", "email": "organa@ssys.com.br", "department": "DevOps", "salary": "5000.00", "birth_date": "01-01-1980"}, "average": "4000.00" } I have two apps, employees and reports. Here's employees/models.py: class Employee(models.Model): name = models.CharField(max_length=250, default='FirstName LastName') email = models.EmailField(max_length=250, default='employee@email.com') departament = models.CharField(max_length=250, default='Full-Stack') salary = models.DecimalField(max_digits=15, decimal_places=2, default=0) birth_date = models.DateField() Here's employees/serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'email', 'departament', 'salary', 'birth_date'] I'm not sure how to create my views and serializers for my report app. How should I approach this? How can I return an extra field with a calculation between values of another … -
Django Views filter objects by user from custom model
I've created custom user model, and i'm trying to filter data in views.py by that user. The error i get is: 'SomeClassView' object has no attribute 'user' My goal is to 'encapsulate' data for each user. user model: class CustomUserManger(BaseUserManager): use_in_migrations = True def create_user(self, email, username, password, **other_fields): email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to staff') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to superusers') return self.create_user(email, username, password, **other_fields) class User(AbstractUser, PermissionsMixin): username = models.CharField(_('username'), max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) objects = CustomUserManger() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username Views: class SomeClassView(viewsets.ModelViewSet): user = SomeClass.user serializer_class = WagonSerializer authentication_classes = (SessionAuthentication, ) @login_required def get_queryset(self): user = self.request.user return SomeClass.objects.filter(user=user) -
django-auth-ldap - modify debug messages / adding IP adress
Is it possible to somehow modify django-auth-ldap messages logged in log? I need to log IP adress alongside user if login failed: 2022-05-17 12:54:08 [DEBUG] Authentication failed for yyyyy: failed to map the username to a DN. 2022-05-17 12:54:32 [DEBUG] Authentication failed for xxxxx: user DN/password rejected by LDAP server. -
Connectivity issues to Sybase database as a secondary database with Django
I can connect to sybase database with FreeTDS and pyodbc as follows: # hello_sybase.py import pyodbc try: con = pyodbc.connect('Driver={FreeTDS};' 'Server=10.60.1.6,2638;' 'Database=blabla;' 'uid=blabla;pwd=blabla') cur = con.cursor() cur.execute("Select * from Test") for row in cur.fetchall(): print (row) cur.close() con.close() except Exception as e: print(str(e)) I tried to connect in a django view as follows: import pyodbc CONN_STRING = 'Driver={FreeTDS};Server=10.60.1.6,2638;Database=blabla;uid=blabla;pwd=blabla' def my_view(request): with pyodbc.connect(CONN_STRING) as conn: cur = conn.cursor() cur.execute('SELECT * FROM test') rows = list(cur.fetchall()) return render(request, 'my_template.html', {'rows': rows}) When I run python manage.py runserver and run the code in the above view. I have this error message '08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') I tried to put TDS_Version=7.4 as was mentioned here in the comment, but it didn't helped. Is it possible that these are issues with the threading as is said in that comment? How can I fix it? The code works without django, but with python manage.py runserver it doesn't work. -
Django_jsonform not detecting changes, when attempting to makemigrations
I've added explanation to JSON form but when i attempt python manage.py makemigrations questions, says no changes detected in app "questions" I've added questions to INSTALLED_APPS in settings.py This only happens when i edit the JSON form. If i edit outside, then makemigrations work? class NewQuiz(models.Model): ITEMS_SCHEMA = { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'question_english': { 'type': 'string' }, 'answers': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'answer_english': { 'type': 'string' }, 'is_correct': { 'type': 'boolean', 'title': 'Is correct', 'default': False, } } } }, 'explanation_english': { 'type': 'string' }, } } } How do i solve? -
isADirectoryError [Errno 21] while trying to render custom select form field
I am working with Python framework Django v2.2. I am trying to add custom attributes to <option> elements so that they are constructed as <option ext='xx'>. The forms are generated with Django admin templating and I am trying to extend them rather than creating completely new ones. My code: class CustomFormatSelect(forms.Select): def __init__(self, attrs=None, choices=(), disabled_choices=()): super(forms.Select, self).__init__(attrs, choices=choices) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): if index: dataformat = DataFormat.objects.get(id=index) extension = dataformat.ext option = super(forms.Select, self).create_option(name, value, label, selected, index, subindex, attrs) option['attrs']['ext'] = extension return option format = forms.ModelChoiceField(queryset=DataFormat.objects.all(), required=True, widget=CustomFormatSelect(attrs={'class':'file_formats'})) I am using Django debug mode and after this chunk is executed I get error: [Errno 21] Is a directory: '.../miniconda3/envs/migrator_admin/lib/python3.7/site-packages/django/contrib/admin/templates' Further messages: In template .../templates/django/forms/widgets/select.html, error at line 3 And it points to line in template: 3 {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} I am pretty new one to Django, so my question is should I do it this way (if it is solvable), or should I create completely new template which is separated from Django admin ? -
Django view not rendering - sidebar & header loads fine but main content does not load
I've been through so many different things and I just can't work it out; need a fresh set of eyes haha My view does not render and this seems to be the case across my apps and landing page - the sidebar and header loads fine, footer looks to partially load but I believe this is due to the fact the main content does not load. Current HTML page screenshot - not rendering view views.py from django.shortcuts import redirect, render from django.views import View from django.views.generic.base import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.core.paginator import Paginator from django.http import request from django.http.response import HttpResponse from django.conf import settings # Form Imports from .models import NewRecipeForm ######################################### # Form Pages # ######################################### # Recipe View class RecipesView(LoginRequiredMixin, View): def get(self, request): content = {} content['heading'] = "Recipes Database" content['pageview'] = "Recipes & Formulations" return render(request, 'nf_recipes/recipes-database.html', content) ######################################### # Form Pages # ######################################### # Add New Recipe Form class AddNewRecipeForm(LoginRequiredMixin, View): def get(self, request): add_new_recipe_form = NewRecipeForm() content = {} content['heading'] = "Add New Recipe" content['pageview'] = "Recipes & Formulations" content['add_new_recipe_form'] = add_new_recipe_form return render(request, 'nf_recipes/add-new-recipe.html', content) def post(self, request): if "add-new-recipe-submit" in request.POST: add_new_recipe_form = NewRecipeForm(request.POST) add_new_recipe_form.save() return redirect("/nf_recipes/recipe-db") # … -
Django db_router does not exclude app models as expected
I am trying to create an application where one server communicates with many other worker servers. Those servers will each have their own DB which should only contain the tables for their own models. I have created a database router which unfortunately does not work as the migrate command continues to create auth, contenttypes and virtually all Django application models in the database that as per the router, should contain none of that and only the worker server specific models. Expected in database: Worker Server Model 1 Actually produced in database: Worker Server Model 1 auth_group auth_group_permissions auth_permission auth_user auth_user_groups all the rest of the django models Code in Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'server_1_db', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } DATABASE_ROUTERS = ['ApplicationServer_2.db_routers.RestRouter'] Router code: class RestRouter: app_labels = {"DoNOTadd", "auth", "admin", "sessions", "contenttypes"} def db_for_read(self, model, **hints): if model._meta.app_label not in self.app_labels: return 'default' return "For read db" def db_for_write(self, model, **hints): if model._meta.app_label not in self.app_labels: return "default" return "For write db" def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label not in self.app_labels or obj2._meta.app_label not in self.app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
Want to build custom Audit logging
We have a enterprise application in django, want to do few enhancements Enhancements : i don't want to save log change data in django_admin_logs table in db, instead of this , we have a external service where we want to append all the logs there , There is a history page in django when we click on the models data , on history page what we want is to show data on that page by making a get call to audit service When we changed something in the entry we want to make a post call to audit service and with old and new data Can someone explain how can i achieve that -
How to get users spent time on a task with Djanog?
I have Django project and several views. In one view i want to track users spent time. How can i do that? Maybe some libraries or django built in methods? Little bit more about view: when user open view he can see many photoes, and then he need to choose similar and save. Then page reloads with new photoes and task is similar, find similar photoes and submit. I need to track and store that time what each user spent on this task. If i check users time when he open view i don't know when she close it, and also user can just open view and chill, without doing something. How or with i can realize it? -
How do I include a Django project's README.md in a template?
I want to add the text of the readme to a custom index template in admin. So I have the following relevant paths in the project: ./README.md ./impact_api/templates/admin/index.html And in the project settings I have TEMPLATES = [ { 'DIRS': [BASE_DIR / 'templates'], ...}] So in the index.html file I want to do something like this: {% include "../../README.md" %} But that raises an error: TemplateSyntaxError at /admin/ The relative path '"../../README.md"' points outside the file hierarchy that template 'admin/index.html' is in. The only things I can think of are a) to move the README into the body, which I'm not sure I can do without losing the display on Github and seems like a bad idea even if I can, or to change the templates lookup path to the entire project, which also seems like a terrible idea. Is there a more sensible option? -
IndexError: list index out of range Django and Postgresql DB
I'm getting mad with this issue, so please help hahahahaha. the error i have is IndexError: list index out of range, when i try do an insert to in table of my DB. I'm trying insert a svc document with only 30 rows. any idea? class CamerasBaleares(TimeStampedModel, SoftDeletableModel): title = models.CharField(max_length=50, blank=True) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) url = models.URLField(blank=True) is_removed = models.BooleanField(default=False) def __str__(self): return self.title def load_data(self): import csv self.file = open(r'/home/elsamex/Documentos/CamarasBaleares.csv') self.row = csv.reader(self.file, delimiter='"') self.list = list(self.row) self.tupla = tuple(self.list) def save_data(self): import psycopg2 self.connection = psycopg2.connect("dbname=camarasdgt user=******* password=++++++++") self.cursor = self.connection.cursor() self.cursor.executemany ("INSERT INTO api_camerasbaleares (title, lat, lon, url) VALUES (%s, %s, %s, %s)", self.tupla) self.connection.commit() self.cursor.close() self.connection.close() def select (self): self.load_data() self.save_data() self.cursor = self.connection.cursor() self.cursor.execute("""SELECT * FROM api_camerasbaleares""") self.rows = self.cursor.fetchall() self.cursor.close() self.connection.close() return self.rows ins_db= CamerasBaleares() ins_db.load_data() ins_db.save_data() ins_db.select() -
Django Bootstrap 5 - Custom styling
I am using django-bootstrap5 in a Django project. According to the docs, for customization, I can add the following to settings.py: BOOTSTRAP5 = { "css_url": {}, # I could add a custom URL here "theme_url": "..." # Or I could override the theme here } Which seems overkill for only a few customizations. How can I customize something like the primary colour of Bootstrap? Do I have to use Sass/Scss, and if so, how does one do this in Django? -
django when viewing other users profile i get the logged user's profile
New to Django and i can't figure out why i keep getting the profile view of the user I logged in with when i try to view other user's profile. HTML: {% extends "Portfolio/base.html" %} {% block content %} <body> <a href=""><i class="bi bi-pencil"></i>Send Message</a> {% for message in message_list %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ message.sender_user.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'profile-detail' message.sender_user.id %}">{{message.sender_user.username}}</a><small class="text-muted">&emsp; {{message.date_posted}}</small></p> {# |date:"F d, Y" #} </div> <p class="article-content mb-4">{{message.content|safe}}</p> </div> </article> <p>{{message.seen}}</p> {% endfor %} Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Views: ''' User Profile ''' class ProfileDetailView(DetailView): template_name = 'user/profile_detail.html' # <app>/<model>_<viewtype>.html model = Profile fields=('image') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) URLs path('profile/<int:pk>', user_views.ProfileDetailView.as_view(), name='profile-detail'), -
How to deploy Django Based Server and Laravel Project Simultaneously on a Single Droplet
I am new to Digital Ocean and was wondering on how to deploy Django and Laravel code side-by-side. The code works fine locally but I don't know how to deploy the both sources over Digital Ocean droplet. We bought cloudways server but it doesn't offer anything other than PHP which was the limitation. So, we don't have any experience with deployment on Digital Ocean. Is there anyone who can help me with this? Thank you! -
How to send parameter from Django to JavaScript function
I would like to know how I can send a parameter value from Django (View, Form, etc) to JavaScript function in js file. I have a Contact app: Models.py class Contact(models.Model): firstname = models.CharField(max_length=100, verbose_name='Nombre') lastname = models.CharField(max_length=100, verbose_name='Apellidos') email = models.EmailField(max_length=100, verbose_name='eMail') message = models.TextField(max_length=1000, verbose_name='Mensaje') created = models.DateTimeField(auto_now_add=True, verbose_name='Creado') updated = models.DateTimeField(auto_now=True, verbose_name='Editado') class Meta(): verbose_name = 'Contacta Mensaje' verbose_name_plural = 'Contacta Mensajes' ordering = ['-created'] def __str__(self): return str(self.email) Forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ("firstname", "lastname", "email", "message") widgets = { 'firstname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_firstname'}), 'lastname': forms.TextInput(attrs={'class':'form-control', 'id': 'id_lastname'}), 'email': forms.EmailInput(attrs={'class':'form-control', 'id': 'id_email'}), 'message': forms.Textarea(attrs={'class':'form-control', 'id': 'id_message'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) View.py class ContactView(CreateView): form_class = ContactForm template_name = 'core/contact.html' JS function in theme.js forms: function () { (function() { "use strict"; window.addEventListener("load", function() { var forms = document.querySelectorAll(".needs-validation"); var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener("submit", function(event) { if(form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add("was-validated"); if(form.checkValidity() === true) { event.preventDefault(); form.classList.remove("was-validated"); // Send message only if the form has class .contact-form var isContactForm = form.classList.contains('contact-form'); console.log(isContactForm); if(isContactForm) { var data = new FormData(form); var alertClass = 'alert-danger'; fetch("", { method: "post", body: data }).then((data) => { if(data.ok) { … -
Django Unknown column in field list error
I am unsure why I am getting this error when I load order_processing.html django.db.utils.OperationalError: (1054, "Unknown column 'orchestration_ce_base.model' in 'field list'") In models.py, I have just added the these: model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) I assume they have not been created in the database. I have tried running makemigrations/migrate, but no changes are detected. When the html page is loaded it is throwing an error. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.order_name class Ce_Base(models.Model): ROUTER_MODELS = ( ('CISCO2901', 'CISCO2901'), ('ISR4331', 'ISR4331'), ('CISCO1921', 'CISCO1921'), ('ISR4351', 'ISR4351'), ('ISR4451', 'ISR4451'), ('ISR4231', 'ISR4231'), ('ISR4431', 'ISR4431'), ('ISR4461', 'ISR4461'), ) REGION = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ) ce_hostname = models.CharField(max_length=15) new = models.BooleanField() location = models.TextField(null=True, blank=True) model = models.CharField(max_length=200, null=True, choices=ROUTER_MODELS) region = models.CharField(max_length=200, null=True, choices=REGION) order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.shortcuts import render from .models import Order from .models import Ce_Base from .forms import OrderForm #from .tables import OrderTable #from django_tables2 import … -
Django Detail View on Boostrap Modal?
Am in the process of building an Ecomerce app with django and although am comming along just fine, I can't seem to be able to render the details of a specific object on a bootstrap modal. This is a screenshot of what am trying to get rendered on the modal This is the modal being display but no image or data being passed to it I went around searching and saw that modals can be rendered with Ajax but haven't found any solid article so far. I would appreciate if anyone could provide a source or a quick sample on how to pull this off. NOTE: I am able to render the detail view as a standalone view as you can see in the image that will follow:Detail View My views: def product_list(request, category_slug=None): # category_slug parameter gives us the ability to optionally filter product by a give category category = None categories = Category.objects.all() # Available=True to filter only the available products products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) paginator = Paginator(products, 9) # Show 9 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # -> Adds the "add to cart" form to … -
Deploying Django Web App with Apache2 on Ec2 Instance
I have come back to AWS and now the old methods don't work anymore. I have followed an instruction manual on the internet to deploy my web app but I run into this 403 Forbidden page. The security groups are entered and everything else is also according to the instructions. So what is wrong here. This is my 000-default.conf <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/django/hosp_app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/hosp_app/static <Directory /home/ubuntu/django/hosp_app/static> Require all granted </Directory> <Directory /home/ubuntu/django/hosp_app/hosp_app> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> WSGIDaemonProcess hosp_app python-path=/home/ubuntu/django/hosp_app python-home=/home/ubuntu/django/hosp_app_env WSGIProcessGroup hosp_app WSGIScriptAlias / /home/ubuntu/django/hosp_app/hosp_app/wsgi.py </VirtualHost> I am in a bit of a hurry so please help. Thanks -
How To send live video frame to server(python side) while using webrtc?
I want to make a Video conferencing app like zoom. I decided to use webrtc, django and django-channel. I want to use mahine learning in live stream video using opencv and deep learning models. How can I do such things, I know for that, we need to send video frame to server side but I could not do due to p2p browser connection after initial offer/answer exchange. Plsese any reference can you provide?? I did not find any answer? -
Django. How to show only related choices in a two table relationship?
Why does this work? This is hard coded with contrato_id = 1, but the goal dynamicaly present related choices, not the full table model. class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'].queryset=FaturaBlog.objects.filter(id_contrato=1).all() But none of them works? a) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'].queryset = FaturaBlog.objects.filter(id_contrato=self.object.pk).all() Exception Type: AttributeError Exception Value: 'LancamentoBlogForm' object has no attribute 'object' b) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.id_fatura_choices = [*forms.ModelChoiceField(FaturaBlog.objects.filter(id_contrato=self.object.pk).all().choices)] Exception Type: AttributeError Exception Value: 'LancamentoBlogForm' object has no attribute 'object' c) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = FaturaBlog.objects.filter(id_contrato=contratoblog__id).all() Exception Type: NameError Exception Value: name 'contratoblog__id' is not defined d) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = super(LancamentoFormset, self).get_context_data() Exception Type: AttributeError Exception Value: 'super' object has no attribute 'get_context_data' BUT I do have context, as return self.render(context) returns data for base.html context [{'True': True, 'False': False, 'None': None}, {}, {}, {'object': <ContratoBlog: Terceiro Contrato Blog>, 'contratoblog': <ContratoBlog: Terceiro Contrato Blog>, 'form': <django.forms.formsets.LancamentoBlogFormFormSet object at 0x107cfb0d0>, 'view': <blog.views.ContratoLancamentoEdit object at 0x107cfb0a0>, 'contrato_dados': <ContratoBlog: Terceiro Contrato Blog>, 'fatura_list': <QuerySet [<FaturaBlog: c.3.vct.2022-07-15>, <FaturaBlog: c.3.vct.2022-08-15>, <FaturaBlog: c.3.vct.2022-09-15>]>, 'lancamento_list': <QuerySet [<LancamentoBlog: L7.2022-02-01>, <LancamentoBlog: L8.2022-04-01>, <LancamentoBlog: L9.2022-06-01>]>}] e) class LancamentoFormset(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['id_fatura'] = FaturaBlog.objects.filter(id_contrato = lancamentoblog__id_contrato).all() Exception Type: NameError Exception Value: name … -
SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in Django Model
I have the following Django Model class Tag(models.Model): name = models.CharField(max_length=50, unique=True, editable=False) created_at = models.DateTimeField(default=datetime.now, editable=False) When I try to create an object like below, Tag.objects.create(name='me','created_at'=str(datetime.now())) I get the following error Tag.objects.create(name='me','created_at'=str(datetime.now())) ^^^^^^^^^^^^^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="? What am I doing wrong here? -
python: can't open file 'C:\\usr\\local\\bin\\django-admin.py': [Errno 2] No such file or directory
Whenever I say "python manage.py startproject myproject" while trying to make a website with Django, I get this error. I'm using python 3.10.4. What can i do?