Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
manage.py runserver no output
I've updated python 3.7 to 3.8 and after that when I want to run py manage.py runserver, or any other commands which are related to manage.py, I've got no output. I read about environment variables and here is mine, which seems fine to me. -
How to make a field in django model that is either a value or a foreign key?
I don't know if that is possible, maybe I have to come up with a particular design but I am struggling with the following: These are my models class Rectangle(models.Model): height = models.CharField(max_length=255) width = models.CharField(max_length=255) class Variable(models.Model): name = models.CharField(max_length=255) value = models.CharField(max_length=255) I would like the width and the height to be either a value, or a variable that has the value. For instance, if the user nputs a height that starts with a special character, say "@variablename" it should be able to find and reference the variable, otherwise just save the value if the input was "350" for instance. Can anyone help me? Thanks in advance -
Is it possible to create foreignkey with it's self?
I have this model, class Perfume_User(models.Model): Sponsor_User = models.ForeignKey('Perfume_User', on_delete=models.CASCADE,blank=True, null=True) -
How to get a count of all objects with a specific value in field in Django template?
I want to get a count of all objects that are False for the object field adult. Here is my model: class Person(models.Model): adult = models.BooleanField(default=False) Here is what I want to achieve in the template: {{ Person.adult=False.count() }} -
How to make custom ManyToMany field filter in django admin?
I have two models: CustomUser, Shop. And I want to add filter for django admin page that contains all CustomUser shops which is_active. I tried to override admin page filter with SimpleListFilter but I got errors related with ManyToMany field 'ManyRelatedManager' object has no attribute 'id' My models: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField() shop = models.ManyToManyField(Shop, blank=True) class Shop(models.Model): address = models.CharField(unique=True) is_active = models.BooleanField(default=True) My filter: class CustomUserShopFilter(SimpleListFilter): title = 'shop' parameter_name = 'shop' def lookups(self, request, model_admin): shops = set([c.shop for c in model_admin.model.objects.all()]) return [(c.id, c.address) for c in shops if c.is_active=True] def queryset(self, request, queryset): if self.value(): return queryset.filter(customuser__id__exact=self.value()) -
How can i send e-mail to multiple people stored in MY-SQL database using Django? I have created models and views but it is not working
Views from django.conf import settings from django.shortcuts import render from django.core.mail import send_mail from django.core import mail from django.template.loader import render_to_string from django.utils.html import strip_tags import mysql.connector from . import models Create your views here. mydb=mysql.connector.connect(host="localhost",user="root",password="",db='ayush') print(mydb) mycursor=mydb.cursor() if(mydb): print("connection sucessful") else: print("connection unsucessful") def index(request): name = request.POST.get('name') models.Data.objects.create(name=name) email=request.POST.get('email') models.Data.objects.create(email=email) phone=request.POST.get('phone') models.Data.objects.create(phone=phone) subject = 'Call For Help' html_message = render_to_string('index.html', {'context': 'values'}) plain_message = strip_tags(html_message) from_email = 'From ' to=[mycursor.execute("select email from Data")] mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) return render(request, 'index.html') models from django.db import models Create your models here. class Data(models.Model): name=models.CharField(max_length=500) email=models.CharField(max_length=500) phone=models.CharField(max_length=500) def __str__(self): return '{}'.format(self.name) -
Django: Load data from MongoDB
I am working on developing a functional module in my personal blog website which aims to recommend stackoverflow questions when user type in the title and description. My question is: I have scraped the stackoverflow and stored the data that are going to be matched in MongoDB, everytime I need to compare the keyphrases extracted from the user-input description with what stored in my MongoDB database. How shall I load data from MongoDB for that usage. I am not sure if it is the right way to use the dataset in such functional module. -
'NoneType' and 'float' Error - How to avoid NoneType
I've tried to structure my code so if NoneType is a result it will be converted into 0. However, I still seem to get None past through to the next function. Why is that? Error in line 321, in get_profit_loss_value_fees result = self.get_profit_loss_value() - self.get_fees() TypeError: unsupported operand type(s) for -: 'NoneType' and 'float' def get_profit_loss_value(self): if self.get_exit_cpu() > 0: if self.type == 'Long': result = self.get_entries().aggregate( get_profit_loss_value=Sum('amount', output_field=models.FloatField() ) * (self.get_exit_cpu() - self.get_entry_cpu()))['get_profit_loss_value'] return 0 if result is None else result elif self.type == 'Short': ... else: return 0 def get_profit_loss_value_fees(self): result = self.get_profit_loss_value() - self.get_fees() return result -
Python script to automate command prompt action
I have a server at my workplace, where i want to run automated python scripts to open up command prompt and run some command prompt scripts. For example : If a new folder is created and some action is triggered by my website to send command to my server then my python script will run which will open a command prompt in the same folder and run some cmd commands. I have tried using flask for this but could find relatable commands to perform this action. Please help. -
How to Mange Python Django Meberships
I am working on an online school project in Python and Django, I got tow membership Free and Premium -those membership are not paid online(using stripe...)- I created a Membership model and all I need is blocking some pages for Free memberships and showing theme for Paid(premium) memberships So how to manage memberships in HTML page? note: again the member ships will pay me manually, and I will give them the access manually from the admin page(using a drop down menu, switch.. for example). note: there is tow apps in this Django project, Users and courses, I think you need Users app My code: MODELS.py: from django.db import models from django.conf import settings MembershipChoice=(('Free', 'free'), ('Premium', 'prm')) class Membership(models.Model): mebrshpType=models.CharField(choices=MembershipChoice, default='Free', max_length=200) def __str__(self): return self.mebrshpType class Usermembership(models.Model): user= models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership=models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True ) VIEWS.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] if password1 == password2: if User.objects.filter(username=username).exists(): messages.error(request, "هذا الكملك مستخدم اصلا") return redirect("signup") else: user = User.objects.create_user(first_name=first_name, last_name=last_name, username=username, password=password1) user.save() print("User Created") return redirect("/") else: messages.error(request, "كلمات السر غير متشابهة") return redirect("signup") else: return render(request, 'classes/signup.html') def login(request): … -
Get EB Django site to work on single instance and application load balanced environment
I have a website that I have setup on code pipeline. It has a prod and test environment. To get https redirection to work I included a set of configuration files into the .ebextensions directory of my Django app and I will include a copy of these below. I have found that running two load balanced environments is expensive, so I would love to change my test environment to single instance. I tried this a couple of weeks ago and unfortunately the https redirection configuration file seems to create an error. I assume it is because the file has been written to configure an application load balancer, not a single instance. At present I am using an environment variable to specify if I am in test or production (EnvTyp='test' or EnvType='prod'), so I am wondering if there is a way to change which configuration files you use based upon an environment variable, however I have to say that I am relatively new to EB and AWS and so my knowledge of what these files do is almost non existent. Files: https://github.com/awsdocs/elastic-beanstalk-samples/tree/master/configuration-files/aws-provided/security-configuration/https-redirect/python I have also used some configuration files from the following area: https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-https-configuration/ (eg https-backendsecurity.config, https-lbsecuritygroup.config and https-reencrypt-alb.config) It would … -
CloudFoundry: How to use multiple buildpacks? (NGINX + Django/Gunicorn)
I have Django/Gunicorn + whitenoise (for static files serving) working as a single app in Cloud Foundry using the following manifest.yml file: --- applications: - name: mydjango instances: 1 command: src/tvpv_portal/bin/start_gunicorn_django.sh memory: 2048M disk_quota: 1024M buildpacks: - https://github.com/cloudfoundry/python-buildpack.git stack: cflinuxfs3 env: DJANGO_MODE: Production For learning/experimentation, I would like to remove whitenoise and setup Nginx using the nginx_buildpack to work with Django/Gunicorn. However, I am not sure how to use multiple buildpacks on a single app. I have created a nginx.conf, mime.types, and buildpack.yml in my project directory following the directions at https://docs.cloudfoundry.org/buildpacks/nginx/index.html. nginx.conf daemon off; error_log /home/vcap/app/nginx-error.log; events { worker_connections 1024; } http { log_format cloudfoundry '$http_x_forwarded_for - $http_referer - [$time_local] "$request" $status $body_bytes_sent'; access_log /home/vcap/app/nginx-access.log cloudfoundry; default_type application/octet-stream; include mime.types; sendfile on; gzip on; tcp_nopush on; keepalive_timeout 30; port_in_redirect off; # Ensure that redirects don't include the internal container PORT - 8080 server { listen {{port}}; server_name localhost; # Serve static files. location /static/ { alias /home/vcap/app/src/tvpv_portal/static/; } # Serve media files. location /media/ { alias /home/vcap/app/src/tvpv_portal/media/; } # Reverse proxy to forward to main app. location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; } } } I tried doing cf push mydjango -b … -
duplicate error in insert data by django model in database mongo
I have field mobile in customers model django and now remove it and next makemigrations and next migrate. But when i want create new data to customers' table but it error customers index: mobile dup key. once it store in database mongodb but for the next time, it gives error what's problem and its the solution? please help me my Model: class Customers(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) userName = models.CharField(max_length=50,unique=True) email = models.EmailField(max_length=254,blank=True) birthDate = models.CharField(max_length=50,blank=True) fatherName = models.CharField(max_length=50, default='',blank=True) nationalCode = models.CharField(max_length=50, default='',blank=True) certificateId = models.CharField(max_length=50, default='',blank=True) job = models.CharField(max_length=50, default='',blank=True) education = models.CharField(max_length=50,blank=True) married_date = models.CharField(max_length=50, default='',blank=True) originality = models.ForeignKey(County, default=None, on_delete=models.CASCADE) sex = models.CharField(max_length=50,blank=True) marital_status = models.CharField(max_length=50,blank=True) state = models.ForeignKey(States, default=None, on_delete=models.CASCADE,blank=True) address_home = models.TextField(default='',blank=True) postalCode_home = models.CharField(max_length=50,default='',blank=True) fax_work = models.CharField(max_length=50,default='',blank=True) address_work = models.TextField(default='',blank=True) postalCode_work = models.CharField(max_length=50,default='',blank=True) financial_status = models.CharField(max_length=50, default='',blank=True) typeContact = models.CharField(max_length=50,blank=True) ranting_customer = models.CharField(max_length=50, default='',blank=True) relationship_code = models.CharField(max_length=50, default='',blank=True) instagram = models.CharField(max_length=50,blank=True) telegram = models.CharField(max_length=50,blank=True) filename = models.CharField(max_length=50,blank=True) url = models.CharField(max_length=100,blank=True) dateRegister = models.CharField(max_length=50,blank=True) persianDateRegister = models.CharField(max_length=50, blank=True) timeRegister = models.CharField(max_length=50,blank=True) nameRegistrant = models.CharField(max_length=50, blank=True) imageRegistrant = models.CharField(max_length=50, default='',blank=True) my views Customers.objects.create(firstName = firstName, lastName = lastName,userName = userName,email = email,education = education,birthDate = birthDate,instagram = instagram,address_home=address_home,address_work=address_work,nationalCode=national_code,postalCode_home=postal_code_home, telegram = telegram,typeContact = typeContact,sex … -
How to render label and placeholder in django UpdateView?
I've been trying to make a update profile view with UpdateView in Django. However, even though I make labels and placeholders separately, it doesn't work! Here is my code view.py: class UpdateProfileView(UpdateView): model = models.User template_name = "users/update-profile.html" fields = ( "username", "email", "departure", "order", "kakaotalk", ) def get_form(self, form_class=None): form = super().get_form(form_class=form_class) form.fields["username"].widget.attrs = {"placeholder": ""} form.fields["username"].label = "이름" form.fields["username"].help_text = "" form.fields["email"].widget.attrs = {"placeholder": ""} form.fields["email"].label = "이메일" form.fields["departure"].widget.attrs = {"placeholder": ""} form.fields["departure"].label = "부서" form.fields["order"].widget.attrs = {"placeholder": ""} form.fields["order"].label = "기수" form.fields["kakaotalk"].widget.attrs = {"placeholder": ""} form.fields["kakaotalk"].label = "카카오톡 ID" return form def get_object(self, queryset=None): return self.request.user users/update-profile.html: {% block content %} <div class="container lg:w-5/12 md:w-1/2 mx-auto my-10 flex flex-col items-center p-5 border border-gray-500 mt-24"> <form class="" method="post" action="{% url "users:updateprofile" %}" enctype="multipart/form-data"> {% csrf_token %} <span class="font-bold">{{form.username}}</span> <span class="font-bold text-red-600 text-center">{{form.username.errors}}</span> <button class="btn mt-10">수정하기</button> </form> </div> {% endblock content %} If I run server with these codes, it looks like This labels and placeholders are disappeared... And also, if I use {{form}} and {{form.errors}} instead of {{form.username}} and {{form.username.errors}} I can see labels and placeholders, but it looks like This I don't want to show the error message twice...! Therefore, in this case, how to fix these … -
Django use select for update to create an auto increment filed
Intro: I have mulitple mechants saving data in one db instance(postgres), now for merchantA, the id in his role list is: 1,3,4,5,8, for merchantB: 2,6,7,8,10 , in order to let each merchant get their own sequential increment ids,for example, in forntend merchant A's role list should like this: "merchant_id":1, "role":{ "id":1,"name":admin, "id":2,"name":dev, "id":3,"name":finance, } merchant B's role list is: "merchant_id":2, "role":{ "id":1,"name":admin, "id":2,"name":dev, "id":3,"name":finance, } Solution: I set up a ref_id field on Role model instead of using db's default id filed, and use a table to keep the counting result when a role object is created. class Role(BaseModel): name = models.CharField( null=True, blank=True, max_length=50 ) ref_id = models.IntegerField(null=True, blank=True) merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE) # use pre_save to save the count returned from AutoIDService @receiver(pre_save, sender=Role) def update_ref_id(sender, instance: Role, **kwargs): instance.ref_id = AutoIDService.next('Role', instance.merchant.id) #IDTable used to save persist count class IDTable(BaseModel): key = models.CharField(max_length=255, null=True, blank=True) ref_id = models.IntegerField(null=True, blank=True) #do the count, return current class AutoIDService: @classmethod def next(cls, table_name, merchant_id): key = table_name + str(merchant_id) with transaction.atomic(): id_table, created = IDTable.objects.select_for_update().get_or_create(key=key, defaults={'ref_id': 1}) print('created', created) if not created: print('created false') id_table.ref_id += 1 id_table.save() print('return value', id_table.ref_id) return id_table.ref_id Problem #This is the very first record …