Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django slick report and nested categories
I am using in django the following models.py: class Expense(models.Model): name = models.CharField(max_length=50) date = models.DateField(unique=False, blank=False) slug = models.SlugField(unique=True, null=True, default='') # slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name') price = models.DecimalField(default=0.0, blank=True, max_digits = 20, decimal_places = 2) category = models.ForeignKey( 'Category', related_name="Expense", on_delete=models.CASCADE ) account = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name=u"Account", help_text=u"account") def __str__(self): return '{},{},{}'.format(self.name, self.date, self.price) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Expense,self).save(*args, **kwargs) def get_absolute_url(self): return self.slug class Category(MPTTModel): name = models.CharField(max_length=200) slug = models.SlugField(unique=True, null=True, default='') # slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name') parent = TreeForeignKey( 'self', blank=True, null=True, related_name='child', on_delete=models.CASCADE ) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) The TreeForeignKey allows me to define nested categories, such as Home -> Electricity and so on. I am using the following Slick Report view.py: class TotalExpenses(SlickReportView): report_model = Expense date_field = 'date' group_by = 'category' columns = ['name', SlickReportField.create(method=Sum, field='price', name='price__sum', verbose_name=('Total category $'))] charts_settings = [ { 'type': 'bar', 'data_source': 'price__sum', 'title_source': 'name', }, ] It works but I would like to sum only level 1 categories. Do you know how this … -
TypeError: User() got unexpected keyword arguments: 'password2' : Django JWT Authentication
I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error: TypeError: User() got unexpected keyword arguments: 'password2' My serializers.py is as follows: from rest_framework import serializers from account.models import User class UserRegistrationSerializers(serializers.ModelSerializer): password2=serializers.CharField(style={'input_type':'password'}, write_only=True) class Meta: model = User fields=['email','name','tc','password','password2'] extra_kwargs={ 'password':{'write_only':True} } def validate(self, attrs): password=attrs.get('password') password2=attrs.get('password2') if password != password2: raise serializer.ValidationError("Password and Confirm Password Does not match") return attrs def validate_data(self, validate_data): return User.objects.create_user(**validate_data) and my views.py is as follows: from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from account.serializers import UserRegistrationSerializers # Create your views here. class UserRegistrationView(APIView): def post(self, request, format=None): serializer= UserRegistrationSerializers(data=request.data) if serializer.is_valid(raise_exception=True): user= serializer.save() return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my models.py file is as follows: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, name, tc, password=None, password2=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), … -
How to install both Java 11 and Python 3.7 in Docker container using Dockerfile
I have a Django project, from inside which I am executing a jar executable file. But I am having trouble installing both Java 11 and Python using the Dockerfile. I believe the first step is to use a Linux Distro as a base image and install Java and Python on top of it. Can someone please help me with the Dockerfile for this use case? -
Django unique_together() for field1 and field2 and vice versa (field2 and field1)
It's possible to create duplicate thread with same first_person and second_person using unique_together() in django. class Meta: unique_together = ['first_person', 'second_person'] But just like that, Is it possible to make it work for same second_person and first_person too ? For example if first_person is abc@gmail.com and second_person is xyz@gmail.com then I can't create duplicate value but if I try to make second_person is abc@gmail.com and first_person is xyz@gmail.com then it again creates thread with same person that I dont want. Please let me know how to fix this. -
Django: Remove trailing zeros for a Django model field
Here is my Django field I created: class CurrencyField(models.DecimalField): INTEGER_PLACES = 15 DECIMAL_PLACES = 18 DECIMAL_PLACES_FOR_USER = 6 MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES MAX_VALUE = Decimal('999999999999999.999999999999999999') MIN_VALUE = Decimal('-999999999999999.999999999999999999') def __init__(self, verbose_name=None, name=None, max_digits=MAX_DIGITS, decimal_places=DECIMAL_PLACES, **kwargs): super().__init__(verbose_name=verbose_name, name=name, max_digits=max_digits, decimal_places=decimal_places, **kwargs) By using this function I want to remove the trailing from this field def normalize_fraction(d): normalized = d.normalize() sign, digit, exponent = normalized.as_tuple() return normalized if exponent <= 0 else normalized.quantize(1) How can I use this function inside that field class to remove the trailing zeros? -
Creating category section with django
I'm trying to add a category section to my blog post form using django, the category field is created and I haven't got any error but the dropdown is not created. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name def get_absolute_url(self): return reverse('posts') class Post(models.Model): STATUS = [ (0, 'Drafted'), (1, 'Published'), ] title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) published_on = models.DateTimeField(auto_now=True) content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=200, default='uncategorized') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('my_blog:posts') forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'author', 'category', 'content') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'content': forms.Textarea(attrs={'class': 'form-control'}), } admin.py from django.contrib import admin from .models import Post, Category, Comment admin.site.register(Post) admin.site.register(Category) This method was based on a tutorial and I'm wondering if this is the right way to create category fields. Any help, please? -
how to upload public image to digitalocean space using Django?
i upload an image to digital ochen by django and this is my code def uploadImage(request): data = request.data dish= FoodRecord(image=request.FILES.get('image')) dish.save() after upload code i can't accsess to the image with output AWSAccessKeyId and Expires after image link ,,for example this is work https://fra1.digitaloceanspaces.com/logatta-space/fossa/media/food/08eat-articleLarge-v2.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&Signature=4a7jBIKfZzYnNaghBxnE25VnUQM%3D&Expires=1667725564 this is not work https://fra1.digitaloceanspaces.com/logatta-space/fossa/media/food/08eat-articleLarge-v2.jpg becuse don't have permisions my qustion how to make my image public from pyhon code ? -
Serializers VS ModelForms in User Registration, Django Rest Framework
What to use while registering a user ? Serializer or ModelForms ? I have been using DRF since a long time now but I have been opting for old school ModelForm (forms.ModelForm) method for user registration. I just want to know that is it necessary to use modelForm for user Registration or we could use serializer as well like we do for all the APIs ? PS : I have overriden the user Modal along with the Managers : class MyAccountManager(BaseUserManager): def create_user(self, email, name, password): if not email: raise ValueError('User must have an email address') if not name: raise ValueError('User must have a name') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( name=name, email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.is_customer = False user.save(using=self._db) return user ` class User(AbstractBaseUser, CreationUpdationMixin): first_name = None last_name = None date_joined = None email = models.EmailField(unique=True) name = models.CharField(max_length=200) phone = models.CharField(max_length=20, default='') is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) is_seller = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = MyAccountManager() ` -
django custom save insert to multiple table
I have an Item table and TransactionLog table, When I create an item it should also create a log this is my models.py class Item(models.Model): itemid = models.CharField(primary_key=True, max_length=20) name = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'items' def save(self, *args, **kwargs): TransactionLog.objects.create(itemid=self.cl_itemid, trans_desc="Add Clearance Item", trans_recorded=timezone.now()) super(Item, self).save(*args, **kwargs) class TransactionLog(models.Model): log_id = models.AutoField(primary_key=True) itemid = models.ForeignKey('Item', models.DO_NOTHING, db_column='itemid', blank=True, null=True) trans_desc = models.TextField(blank=True, null=True) trans_recorded = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'transaction_log' but When I try to insert it's saying Cannot assign "'CL-20221106-0000'": "TransactionLog.itemid" must be a "Item" instance. maybe because the Item isnt created yet? -
Send email in Django now that Google changed the policy . WinError 10061] No connection could be made because the target machine actively refused it
I'm working on a Django project. I need to send my users the emails and receive the contact us form when users submit the form. I'm using Gmail. As I watched tutorials, the email which receives the emails need to turn on less secure on security section. However, as May 2022 google changed the policy and now the option is not there. https://support.google.com/accounts/answer/6010255?authuser=1&hl=en&authuser=1&visit_id=638033119094066220-3031639860&p=less-secure-apps&rd=1 So, now when I'm trying to send an email I face the following error. ConnectionRefusedError at /contact/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Django Version: 4.1.2 Exception Type: ConnectionRefusedError Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Exception Location: C:\Users\Sed AKH\AppData\Local\Programs\Python\Python38\lib\socket.py, line 796, in create_connection Raised during: main.views.contact Python Executable: C:\Users\Sed AKH\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['E:\\Projects\\Python\\Django\\weblimey', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin'] Server time: Sun, 06 Nov 2022 06:26:20 +0000 And here my code : def contact(request): if request.method == 'POST': try: contact = ContactForm() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') contact.name = name contact.email = … -
django custom save auto increament id
I posted a question few months ago django create custom id def save() I want to create an custom id using auto-increment but when I try to use his code into mine def get_default_id(): last_id = Item.objects.last().cl_itemid split_id = last_id.split('-') split_id[-1] = str(int(split_id[-1])+1) new_id = '-'.join(split_id) return new_id class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' After I insert data via postman { "office": "OSA", "sem": "1", "sy": "2022-2023", "remarks": "TEST from November 6", "resolution": "TEST", "studid": "2012-5037" } When I open my clearance_item table, this is the row displayed |cl_itemid |studid |office|sem|sy |remarks |resolution| |WTF2022-20223-10|2012-5037|OSA |1 |2022-2023|TEST from November 6|TEST My Question is where is that WTF's coming from? it should be OSA2022-20232-10 based on this format officesy-sem-10 Second is when I try to insert the same data it's saying (cl_itemid)=(WTF2022-20223-10) already exists. instead of WTF2022-20223-11 but then I change … -
DRF - Testing, error while hitting sinlgle data from id
Urls.py router = routers.DefaultRouter() router.register('zone', views.ZoneViewSet, basename='zone') app_name = 'address' API. urlpatterns = [ path('', include(router.urls)), ] Test.py RECIPES_URL = reverse('address:zone-list') def details_url(id): print(RECIPES_URL,id) return reverse(RECIPES_URL.strip(),args=[id]) print -> /api/address/zone/ 1 def test_zone_details(self): task = sample_payload() url = details_url(task.id) res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) ERROR: test_zone_details (address.tests.ZoneApiTestCase) raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '/api/address/zone/' not found. '/api/address/zone/' is not a valid view function or pattern name. -
Django Postgres database not updating fields anymore
I have the following for loop to iterate over a dictionary and save it to the database, and it used to work, but randomly stopped. I'm not getting any errors, and my database logs show that there is an UPDATE query happening, so everything seems to be working correctly but whenever I check the database if the information is updated, it isn't. It looks like INSERT and SELECT queries are still working. for key, value in data.items(): if value == 'null': pass else: UserModel.objects.filter(id=user.id).update(**{key: value}) This is the SQL query: [DATABASE] [605-1] sql_error_code = 00000 time_ms = "2022-11-06 04:02:47.750 UTC" pid="235484" proc_start_time="2022-11-06 03:58:51 UTC" session_id="636730fb.397dc" vtid="2/1215752" tid="0" log_line="595" database="d7dd2o7lqkb580" connection_source="18.206.16.69(43354)" user="u571qd3ks8ldkb" application_name="[unknown]" LOG: statement: UPDATE "accounts_account" SET "first_name" = 'testing' WHERE "accounts_account"."id" = 3323 My database is a Postgres database attached to my server and is hosted on Heroku. I would really appreciate any help in resolving this issue. -
I tried to create a Django view with async but it shows SynchronousOnlyOperation errors
I am trying to create an async django view which fetch status code from multiple urls. This is my views.py async def get_page(session, url, urlMain): async with session.get(url) as response: st_code= await response.status return url, st_code, urlMain async def create_search(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] tasks = [] async with aiohttp.ClientSession() as session: for item in data: url = data[item]['url'] urlMain = data[item]['urlMain'] tasks.append(get_page(session, url, urlMain)) results = await asyncio.gather(*tasks) for url, st_code, urlMain in results: if st_code == 200: site_data = SearchResult( url = urlMain, sitename = item, ) site_data.save() context = {'form':form} return render(request, 'index.html', context ) While running django it shows me this error. SynchronousOnlyOperation at /create-search/ You cannot call this from an async context - use a thread or sync_to_async. -
Django Admin Inline Form Fails in Test but Works in Admin Interface
So I am at a loss as to why the following example fails in a test case, but works perfectly fine in the admin interface. I have a very basic User and Login models. The Login simply records user logins into the system via Django signal. class User(AbstractUser): company = models.CharField( max_length=100, blank=True, null=True ) class Login(models.Model): """Represents a record of a user login event.""" user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="logins" ) ip = models.GenericIPAddressField() user_agent = models.TextField() date = models.DateTimeField(auto_now_add=True, db_index=True) domain = models.CharField(max_length=255) http_host = models.CharField(null=True, max_length=255) remote_host = models.CharField(null=True, max_length=255) server_name = models.CharField(null=True, max_length=255) In the admin.py I define a UserAdmin with inlines = [LoginInline]. Basically when viewing the user I can see the login history. from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.html import format_html from users.models import Login User = get_user_model() class ReadOnlyModelMixin: def has_add_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False class LoginAdmin(ReadOnlyModelMixin, admin.ModelAdmin): list_display = ( 'id', 'user_link_with_name', 'user_email', 'user_company', 'domain', 'date', 'ip', 'remote_host', 'http_host', 'server_name', 'user_agent', ) @admin.display(description='Name', ordering='user__first_name') def user_link_with_name(self, obj): url = reverse("admin:users_user_change", args=[obj.user.id]) return format_html(f'<a href="{url}">{obj.user}</a>') @admin.display(description='Email', ordering='user__email') … -
AttributeError: 'list' object has no attribute 'startswith' python manage.py collectstatic
hello when I do python3 manage.py collectastatic I get this error and I can't find how to fix it. In the terminal I get this: /usr/local/lib/python3.8/dist-packages/environ/environ.py:615: UserWarning: Engine not recognized from url: {'NAME': 'postgres://paycoin*-postgres.render.com/paycoin', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'ENGINE': ''} warnings.warn("Engine not recognized from url: {}".format(config)) 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 "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/lib/python3/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/lib/python3/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 118, in import_module if name.startswith('.'): AttributeError: 'list' object has no attribute 'startswith' when I do python3 manage.py collectastatic I get this error and I can't find how to fix it. I was expecting a folder named static to be created in VSC but I get this error -
How to implement like/dislike button (for non-logged-in users) in django
Am trying how to implement like and dislike feature in django without an end user logging into a account, using django. I have not seen documentation for the non-logging end user for like and dislike feature in django -
Additional save button on Django admin pages
How can you add an extra Save-button on admin list view pages, like shown on the image, that saves the changes but also does something extra before or afterwards? I know that it possible to achieve this functionality via "actions" but it is cumbersome to select the correct action from select-box, when you need to do it repetitively. It would be beneficial to be able to add extra save button both to the list view and the change view. -
Require minimum password complexity in django allauth
I am trying to implement a minimum set of criteria for passwords. However, even with the below, users are able to sign up with a single character password. How can I require a certain minimum password complexity when using django-allauth with a custom adapter. # adapter.py from typing import Any from allauth.account.adapter import DefaultAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.exceptions import ImmediateHttpResponse from django.conf import settings from django.forms import ValidationError from django.http import HttpRequest class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def clean_password(self, password, user=None): special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]" min_length = 1 if len(password) < 8: raise ValidationError('Password length must be greater than 8 characters.') if not any(char.isdigit() for char in password): raise ValidationError('Password must contain at least %(min_length)d digits.') % {'min_length': min_length} if not any(char.isalpha() for char in password): raise ValidationError('Password must contain at least %(min_length)d letters.') % {'min_length': min_length} if not any(char in special_characters for char in password): raise ValidationError('Password must contain at least %(min_length)d special characters.') % {'min_length': min_length} return password class SocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request: HttpRequest, sociallogin: Any): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) # settings.py # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "project.adapters.user.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/forms.html ACCOUNT_FORMS = {"signup": "project.forms.user.UserSignupForm"} # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = "project.adapters.user.SocialAccountAdapter" -
SQLite Django views.py syntax confusion for posting to database
I am learning Django and following a tutorial by Telusko. Earlier in the course he switched to Postgresql but I couldnt get it to work so I decided to move on with SQLite since it was already installed. He showed this code to Add User to the database: def register(request): if request.method == "POST": firstname= request.POST['firstname'] lastname= request.POST['lastname'] email= request.POST['email'] phone= request.POST['phone'] username= request.POST['username'] password1= request.POST['password1'] password2= request.POST['password2'] dob= request.POST['dob'] gender= request.POST['gender'] user = User.objects.create_user(username=username, email=email, phone=phone, password=password1, dob=dob, gender=gender, firstname=firstname, lastname=lastname,) user.save(); print('user created') return redirect("/") else: return render(request, 'register.html') ; But this does not work for me I get this error when I submit Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login.apps.LoginConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\yuri\Desktop\naisuback\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\yuri\Desktop\naisuback\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\yuri\Desktop\naisuback\login\views.py", line 30, in register user = User.objects.create_user(username=username, email=email, phone=phone, password=password1, dob=dob, gender=gender, firstname=firstname, lastname=lastname,) Exception Type: AttributeError at /register Exception Value: 'Manager' object has no attribute 'create_user' Sorry if I provided too much information this is … -
Como desplegar Django con React [closed]
hice una web con una plantilla en react y el back con Django, los tengo en carpetas separadas pero ahora nose como desplegarlo. Es mi primer cliente y mi primer despliego estoy medio perdido, se que tengo que usar un VPS, pero nose como hostearlo, ya que ambos funcionan en un localhost diferentes, gracias! -
Django error: Invalid block tag on line 28: 'endfor'. Did you forget to register or load this tag?
I'm stuck on this error I am a new user of Django I am following the steps correctly and learning through YT. When I run python manage.py runserver the HTML shows My index.html file <!DOCTYPE html> <header> CRUD Operation with PostgreSQL </header> <body> <center> <h1>How to create CURD Ops with PostgreSQL</h1> <h3>Learning Django and CURD</h3> <hr/> <table border = "1"> <tr> <th>Employee Id</th> <th>Employee Name</th> <th>Email</th> <th>Occupation</th> <th>Salary</th> <th>Gender</th> </tr> {% for results in data% } <tr> <td>{{result.id}}</td> <td>{{result.name}}</td> <td>{{result.email}}</td> <td>{{result.occupation}}</td> <td>{{result.salary}}</td> <td>{{result.gender}}</td> </tr> {% endfor %} </table> </center> </body> I tried to change endfor to endblock nothing works. I don't know how to solve this, Please help. -
Django - annotate the most frequent field taken from another model linked with foreignKey
I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color of the eyes of a dstID user according to his opinion. A user can votes himself. It's possible that a user doesn't receive any votes so there isn't a tuple with dstID equal to his ID. The integer number of eyeColor rapresent a specific color, for instance: 1 => blue eyes 2 => lightblue eyes 3 => brown eyes 3 => green eyes ecc. class user: userID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) class survey: srcID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookSrc') dstID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookDst') eyesColor= models.IntegerField() My goal is to annotate in the user model the most frequent type of eyeColor voted, so the eyesColor that other people think is the eyesColor of that user. If a user doesn't receive any votes I want to annotate 0. In case there are more than one color with the same voting frequency, if the user has voted himself (tuple with srcID = … -
Will I need to create a virtualenv every time I runserver with Django?
Currently taking CS50 Web Programming with Python and Javascript. I'm on the Week 3 Django lecture and trying to follow along but I'm running into trouble while trying to run python manage.py run server. I'm getting the "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" error. I'm using Windows, Django IS installed and I've reinstalled it multiple times. I've found a workaround by following the steps from https://www.youtube.com/watch?v=eJdfsrvnhTE&t=296s to set up a virtual env and can proceed after that, but in the lecture Brian doesn't need to setup a virtual env? It just loads straight through for him? Yes I have scoured through reddit, stackoverflow, youtube, and other articles online before asking this here. It's not too much trouble to do so but I'm just wondeirng why he didn't need to make a virtualenv and if I'm actually going to have to make a virtual env for every Django project going forward? Is it because things have changed with python/pip/Django? I would just find it more convenient if I could just run the run server command without having to run the extra 4 commands … -
hi, i have this error when i try to make migrations comand with django project: [duplicate]
I have not been able to find a solution to this problem since the database or mysql is not right, I do not understand it, if anyone knows a solution for this, my OS is mojave on Mac, I do not know if it is because of the version or what problem it has this bash: : command not found (base) MacBook-Pro-de-andrex:python_web andrexbaldion$ python3 manage.py makemigrations Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.18.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 22, in <module> main() File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked …