Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
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 …