Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve Django Error in formatting: AttributeError: 'Habit' object has no attribute 'goal'
I runserver to test my Habit Tracker app. Not sure why I get Error in formatting: AttributeError: 'Habit' object has no attribute 'goal'. Have included my models.py. I need your help understanding what I have written incorrectly and how to fix the code. thank you. class Habit(models.Model): name = models.CharField(max_length=60) goal_nbr = models.IntegerField(default=0, null=True, blank=True) goal_description = models.CharField(max_length=60, null=True, blank=True) start_date = models.DateField() end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, related_name="habit", on_delete=models.CASCADE) @property def duration(self): delta = end_date - start_date return f'{ delta } days' def __str__(self): return f"Your chosen habit is {self.name}, with a goal of {self.goal_nbr} {self.goal._description} for {self.duration} days, from {self.start_date} to {self.end_date}" class Activity(models.Model): # name = models.CharField(max_length=60) result_nbr = models.IntegerField(default=0, null=True, blank=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) user = models.ForeignKey( User, related_name="activity", on_delete=models.CASCADE) habit = models.ForeignKey( 'Habit', related_name="activity", on_delete=models.CASCADE) @property def diff_between_goal_result(self): diff_nbr = result_nbr - self.habit.goal_nbr return f'{ diff_nbr }' class Meta: constraints = [models.UniqueConstraint( fields=['created_at', 'habit'], name='one_update_per_day'), ] def __str__(self): return f"Today you achieved: {self.result_nbr} of your {self.habit.name} {self.habit.goal_description}" -
How to uninstall python 2.17.13, and keep python 3.7.6 as the default on debian 9
I installed a Django package on GCP (Debian 9 OS), that comes with the following softwares: Django (2.2.9) Git (2.25.0) Apache (2.4.41) lego (3.3.0) MySQL (5.7.29) Node.js (10.18.1) OpenSSL (1.1.1d) PostgreSQL (11.6) Python (3.7.6) SQLite (3.31.0.) Subversion (1.13.0) When I type the command python -V I get the following python version: 2.17.13 When I type python3 -V I get the following version: 3.7.6 How can I uninstall the previous version permanently and keep the current one as the default? -
django.utils.datastructures.MultiValueDictKeyError: 'password'
I'm using Django3 and py3 i'm trying to create registration and login pages by using django forms. my registrations part was succeeded i can put data in database table. but when it comes to login part im getting this error can some one please help me This is my view file: from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import auth from firstapp.models import Customers # Create your views here. def home(request): return render(request, 'home.html') def register(request): return render(request, 'register.html') def reg_success(request): name = request.POST['name'] username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] mobile = request.POST['mobile'] # return HttpResponse("<h2>UserRegistered Successfully</h2>") if request.method == 'POST': user = Customers.objects.create(name=name, username=username, password=password, email=email, mobile=mobile) user.save() print("User Created") return render(request, 'reg_success.html', {'username': username}) else: return render(request, 'register.html') def login(request): return render(request, 'login.html') def log_success(request): username = request.POST['username'] password = request.POST['password'] if request.method == 'POST': user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return render(request, 'log_success.html', {'username': username}) else: return HttpResponse("Invalid Details Given") #return redirect(login) else: return redirect(login) This is my html file for log_success.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Success</title> </head> <body> <form method="post"> {% csrf_token %} <h2 style="color:green">Welcome {{username}}</h2> <p>Here is Your Bio … -
normalization in django model between course and course location
i want to normalize my django model which includes Institutes and Location ,this model structure is right ? class Institute(models.Model): institute_name = models.OneToOneField(CustomUser,on_delete=models.CASCADE) institute_id = models.SlugField(unique=True,default=slug_generator()) institute_name.is_institute = True institute_logo = models.ImageField(upload_to='profiles',default='profile.png') city_name = models.CharField(choices=city_choices,default=erbil,max_length=40) specific_location = CharField(choices=locations,default='') or something like that : class Institute(models.Model): institute_name = models.OneToOneField(CustomUser,on_delete=models.CASCADE) institute_id = models.SlugField(unique=True,default=slug_generator()) institute_location = models.ForeignKey(Location) institute_name.is_institute = True institute_logo = models.ImageField(upload_to='profiles',default='profile.png') class Location(models.Model): city_name = models.CharField(choices=city_choices,default=erbil,max_length=40) specific_location = CharField(choices=locations,default='') def __str__(self): return self.city_choices thanks for advice -
'unique_together' refers to the nonexistent field 'slug'
in category class I'm using a function for slug to accept Arabic letters but after adding this function and using it I get that error. models.py: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) 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]) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.slug = slugify(self.title) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" and this is the slugify function: def slugify(str): str = str.replace(" ", "-") str = str.replace(",", "-") str = str.replace("(", "-") str = str.replace(")", "") str = str.replace("؟", "") return str before this I was using slugField but that didn't work for arabic. If there is another way for that without using self made function please tell me. and also I've included this at top: # -*- coding: utf-8 -*- -
Django REST: TypeError: Object of type 'Language' is not JSON serializable
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBaseUser): is_admin = models.BooleanField(default=False, verbose_name='is administrator?') born = models.PositiveSmallIntegerField(verbose_name='born year') rating = models.PositiveIntegerField(default=0, verbose_name='user rating') email = models.EmailField(verbose_name='email') nickname = models.CharField(max_length=32, verbose_name='useraname') password = models.CharField(max_length=100, verbose_name='password') # on forms add widget=forms.PasswordInput language = models.ForeignKey('Language', on_delete=models.PROTECT) country = models.ForeignKey('Country', on_delete=models.PROTECT) def __str__(self): return self.nickname class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['nickname'] class Language(models.Model): name = models.CharField(max_length=20, verbose_name='language name') def __str__(self): return self.name class Meta: verbose_name = 'Language' verbose_name_plural = 'Languages' class Country(models.Model): name_ua = models.CharField(max_length=20, verbose_name='country name in Ukranian') name_en = models.CharField(max_length=20, verbose_name='country name in English') name_ru = models.CharField(max_length=20, verbose_name='country name in Russian') def __str__(self): return self.name_en class Meta: verbose_name = 'Country' verbose_name_plural = 'Countries' Serializers: from rest_framework import serializers from main import models class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True, required=True) class Meta: model = models.HahaUser fields = ['nickname', 'password', 'password2', 'language', 'country', 'email', 'born'] extra_kwargs = { 'password': {'write_only': True} } def save(self): account = models.HahaUser.objects.create( email=self.validated_data['email'], nickname=self.validated_data['nickname'], language=self.validated_data['language'], born=self.validated_data['born'], country=self.validated_data['country'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != … -
How to create table from views and display it to HTML?
How do I create a table using this query that corresponds to each other? I'm completely stuck with this problem, I tried to solve it for several days. views.py corevalues = CoreValues.objects.all().order_by('Display_Sequence') marking = StudentBehaviorMarking.objects.all() corevaluesdescription = CoreValuesDescription.objects.values('id', 'Description').distinct( 'Description').order_by('Description') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher=teacher).filter( GradeLevel=gradelevel.values_list('Description')) \ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by( 'Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher=teacher).filter( GradeLevel__in=gradelevel.values_list('id')) The results I want to achieve: My models class CoreValues(models.Model): Description = models.CharField(max_length=500, null=True, blank=True) Display_Sequence = models.IntegerField(null=True, blank=True) . class CoreValuesDescription(models.Model): Core_Values = models.ForeignKey(CoreValues,on_delete=models.CASCADE, null=True) Description = models.TextField(max_length=500, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE) Display_Sequence = models.IntegerField(null=True, blank=True) class StudentBehaviorMarking(models.Model): Marking = models.CharField(max_length=500, null=True, blank=True) Non_numerical_Rating = models.CharField(max_length=500, null=True, blank=True) class StudentPeriodSummary(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentSubjectGrade,on_delete=models.CASCADE) It is possible to create a table using Python, right? UPDATE When I try this to my views.py: students = StudentsCoreValuesDescription.objects.filter(grading_Period=coreperiod) \ .values('id', 'Marking', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname') \ .distinct( 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname') \ .order_by( 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname') gradelevel = EducationLevel.objects.filter(id__in=coregradelevel).distinct().order_by('id') markings = StudentBehaviorMarking.objects.all() corevaluesperiod = CoreValuesDescription.objects.filter(grading_Period=coreperiod).order_by('Display_Sequence') table = [] student_name = None table_row = None columns = len(corevaluesperiod) + 1 table_header = ['Core Values'] table_header.extend(corevaluesperiod) table.append(table_header) for student in students: if not student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] == student_name: if not table_row is None: … -
External API's JWT generation from Django application
I am consuming an external RESTful API for my Django application, I want to achieve the following things Generate a JWT Open home page to do some registration (using another API) Again generate a JWT Make API calls The code to generate JWT is in node js. I just want some directions as to how this is done automatically. currently, I manually run the code to get the JWT and copy-paste it wherever it is required. I tried to run the token generation code from views.py using different libraries but no luck. Can someone please guide me on how this is done? Thanks -
How to render form with class-based view?
I have an index page: views.py class IndexView(TemplateView): template_name = "index.html" urls.py urlpatterns = [ path('', IndexView.as_view()), ] And I need to render form in this page index.html {% block content %} <!-- Other blocks --> <div id="input"> <form method="POST" class="text-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="submit btn">Submit</button> </form> </div> <!-- Other blocks --> {% endblock %} forms.py class TextForm(forms.Form): text = forms.CharField(widget=forms.Textarea) There is a topic about class-based views forms handling but it is not clear for me how to render HTML with this form -
Django pivot table without id and primary key
On the database i have 3 tables: languages cities city_language city_language Table: +-------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------------+------+-----+---------+-------+ | city_id | bigint(20) unsigned | NO | PRI | NULL | | | language_id | bigint(20) unsigned | NO | PRI | NULL | | | name | varchar(255) | NO | | NULL | | +-------------+---------------------+------+-----+---------+-------+ Model class CityLanguage(models.Model): city = models.ForeignKey('Cities', models.DO_NOTHING) language = models.ForeignKey('Languages', models.DO_NOTHING) name = models.CharField(max_length=255) class Meta: managed = False db_table = 'city_language' unique_together = (('city', 'language'),) Model doesn't have id field and primary key also my table doesn't have id column. If i run this code i got error: (1054, "Unknown column 'city_language.id' in 'field list'") If i define primary key for a column this column values should unique. If i use primary_key when i want to put same city with different languages i get With this city (name or language it depends on which column choose for primary key) already exists. I don't want to create id column for pivot table. There is no reason create id column for pivot table. Please can you tell me how can i use pivot table with correct … -
How to add Widgets to UpdateView in Django
I need to add this widget to the django UpdateView, class tlistUpdate(LoginRequiredMixin,UpdateView): fields = ('title', 'thumbnail', 'content', 'tags') model = htmlpage template_name = 'blog/create_form.html' Tried adding widgets = { 'content': SummernoteWidget(), } and content = forms.CharField(widget=SummernoteWidget()) But it did't work. -
How to create api for Implement Dependent/Chained Dropdown List?
How to Implement Dependent/Chained Dropdown List with django rest framework? -
add leaflet search box in django leaflet.forms.fields PointField
i need add leaflet search box in django form leaflet.forms.fields -> Point Field anybody can help me? thanks -
TypeError at /user/signup/ Siteuser() got an unexpected keyword argument 'is_staff'
i want to create a custom signup form with this fields: username password firstname lastname email phonenumber with User model, it doesn't store the extra fields in the mysql database. i create a AbstractBaseUser model and use it for store data, but i got this error: TypeError at /user/signup/ Siteuser() got an unexpected keyword argument 'is_staff' models.py class Siteuser(AbstractBaseUser): objects = UserManager() USERNAME_FIELD = 'username' firstname = models.CharField(max_length=100, verbose_name='First name', validators= [validate_firstname_length]) lastname = models.CharField(max_length=100, verbose_name='Last name', validators= [validate_lastname_length]) username = models.CharField(max_length=25, verbose_name= 'User name', validators= [validate_username_length, validate_username_alphadigits]) password1 = models.CharField(max_length=30, validators=[validate_password_length, validate_password_digit, validate_password_uppercase]) password2 = models.CharField(max_length=30) email = models.EmailField() phone = models.CharField(max_length= 15, validators= [validate_phonenumber]) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Siteuser.objects.create(user=instance) instance.siteuser.save() views.py def signup(request): firstname = '' lastname = '' emailvalue = '' uservalue = '' passwordvalue1 = '' passwordvalue2 = '' form = forms.Signupform(request.POST or None) if form.is_valid(): fs = form.save(commit=False) firstname = form.cleaned_data.get("first_name") lastname = form.cleaned_data.get("last_name") emailvalue = form.cleaned_data.get("email") uservalue = form.cleaned_data.get("username") passwordvalue1 = form.cleaned_data.get("password1") passwordvalue2 = form.cleaned_data.get("password2") if passwordvalue1 == passwordvalue2: if models.Siteuser.objects.filter(username=form.cleaned_data['username']).exists(): context = {'form': form, 'error': 'The username you entered has already been taken. Please try another username.'} return render(request, 'user/signup.html', context) else: user = … -
Django server starting then crashing
Hi I just updated a couple of packages (including django) when I ran python -Wa manage.py test no problems where found but when i run the server an error occurs and I can't find where it is coming from. I'm using django 3.0.4 and python 3.6 stack trace: "D:\Program Files (x86)\Jetbrains\apps\PyCharm-P\ch-0\193.6494.30\bin\runnerw64.exe" D:\Projects\coursemanager\backend\venv\Scripts\python.exe D:/Projects/coursemanager/backend/manage.py runserver --noreload 8000 DEBUG 2020-03-07 13:50:28,401 selector_events 37100 Using selector: SelectSelector Performing system checks... System check identified no issues (0 silenced). March 07, 2020 - 13:50:31 Django version 3.0.4, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Traceback (most recent call last): File "D:/Projects/coursemanager/backend/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 104, in run self.inner_run(None, **options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "D:\Projects\coursemanager\backend\venv\lib\site-packages\django\utils\module_loading.py", … -
How to optimize database performance foran application that will be accessed by thousands of users?
I'm working on a project, trying to build an application which needs to be accessed by almost 100 to 200 users which be scaled later. I'm thinking of using local and cloud database for optimizing the application. New records are appended to the local database on internet un-availability and when the transaction per second is very high on cloud db. Is it fine to go with such schema of implementing two database. What might be the possible pros and cons? -
Reverse for 'category' with no arguments not found. 1 pattern(s) tried: ['products/category/(?P<hierarchy>.+)/$']
I'm using django 3 and just added some code for sub-categories in my model and view but I get this error. I think I'm missing a change of code structure because the tutorial was for django 1.x but I couldn't found it. models.py: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', 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]) class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(verbose_name='desription') slug = models.SlugField() image = models.ImageField(upload_to='product_pics', default='default.jpg') category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] view.py: def show_category(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [x.slug for x in category_queryset] parent = None for slug in category_slug: if slug in all_slugs: parent = get_object_or_404(Category, slug=slug, parent=parent) else: instance = get_object_or_404(Product, slug=slug) breadcrumbs_link = instance.get_cat_list() category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_link] breadcrumbs = zip(breadcrumbs_link, category_name) … -
Managing data persistence in django
I'm new to Django and web applications development in general. I want to understand the way django manages data persistence. For example, let's consider the case in which I would have to design a data collection system which should be consulted online, adopting django web framework for back-end. A consistent part of this project would rely on data persistence, so here is the point: I would have to create a database from scratch (using for example SQL) and then connect it whith django, or I could just create classes inside django.db.model module? -
How to register a Django tag for a link
I am trying to create a library of snippets for bits of repeated code. The one that I started with is: <a href="/your-harmony/">Your Harmony</a> To replace this I have: *base.py TEMPLATES = [ { ... 'OPTIONS': { ... 'libraries':{ 'harmony_tags': 'harmony.harmony_tags', } ... harmony_tags.py from django import template register = template.Library() @register.inclusion_tag('/your_harmony.html') def your_harmony_menu(): return '<a href="/your-harmony/">Your Harmony</a>' user_list.html {% load harmony_tags %} ... {% your_harmony_menu %} I have restarted the server but get the error: TemplateDoesNotExist at /clients/user-list/ /your_harmony.html What am I doing wrong? -
How to find out if there has been new object created in Django?
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM. How can you achieve that in django? Here are my models: class Post(models.Model): name = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) class PostComment(models.Model): comment = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post', related_query_name='post') date_added = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) I have tried to look into channels and web sockets but all the tutorials that I have found use old versions of django and python. So I decided to simply achieve the same with ajax requests in a while loop. I am open to any suggestions about how to achieve my outcome! -
Django OperationalError no such table:
I created a profile models: This is the code class NPC_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ID = models.CharField(max_length=100) 학번 = models.CharField(max_length=5) and views def signup(request): if request.method == "POST": if request.POST["password"] == request.POST["repassword"]: user = User.objects.create_user( username=request.POST["username"], password=request.POST["password"]) ID = request.POST["ID"] 학번 = request.POST["학번"] profile = NPC_profile(user=user, ID=ID, 학번=학번) profile.save() auth.login(request, user) return redirect('list') return render(request, 'NPC/signup.html') return render(request, 'NPC/signup.html') but appear OperationalError at /NPC/signup/ no such table: NPC_npc_profile How can I solve this error? -
unable to do makemigrations command
I will give all of you the step that I do before this error happen btw my superuser=>id:myuser email: pass:myuser hostname $ django-admin.py startproject myproj hostname $ cd myproj hostname $ python manage.py startapp myapp hostname $ python manage.py migrate hostname $ python manage.py createsuperuser hostname $ python manage.py runserver hostname $ pip install psycopg2 hostname $ psql postgres=# create role myuser with createdb superuser login password 'myuser'; postgres=# create database mydb with owner myuser; postgres=# exit and then I edit the myproj\settings.py, and I run command python manage.py makemigrations myapp and the error bellow happen Traceback (most recent call last): File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'admin' During handling of the above exception, another exception occurred: 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\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\userpc\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config … -
Is it possible to store a class object reference to a Django database (sqlite3 in my case)
I have a class which would connect to an external websocket and parse data from it to thereafter send it to my own websocket. But I'm considering a situation where I would need to, for example, close the connection \ reconnect in case of exceptions \ etc. So, for these purposes I'm wondering whether I can store the reference for an object I've created (which would obviously run continuously in the background to parse data) so that I don't lose the reference itself. I've read that you could create custom database types which would allow to store the class to reconstruct it later but in my case, I need exactly the reference to be stored, because I'll try to access the object's methods such as disconnect() etc. -
Django How to Calculate DateTimeField?
How can I calculate DateTimeFields? I want the user to put the loan StartDate and LoanEndDate and the months paid and left gets automatically calculated like what I did with the money instance how to make a monthly payment table from the start and end date ?? class Agent(models.Model): amount = models.DecimalField(max_digits=10,decimal_places=5) paid = models.FloatField(null=True,blank=True) remaining = models.FloatField(null=True,blank=True) LoanStartDate = models.DateTimeField(default=timezone.now) LoanEndDate = models.DateTimeField(default=timezone.now) monthspaid = models.DateTimeField(default=timezone.now) monthsleft = models.DateTimeField(default=timezone.now) def balance_reciever(sender, instance, *args, **kwargs): amount = instance.amount paid = instance.paid remaining = amount - paid instance.remaining = remaining -
How to get user ID
I am working on a website using Django. I'm having a difficult time playing around codes, how do I get the ID of a user without passing a primary key (id, pk) in the URL. My code below does not give me a solution to getting the ID of a particular user. When I print (user) it prints the current user logged in. Is there a way to get the ID of other users? def home(request): user=Profile.object.filter(user=request.user) path('home', home_view, name='home')