Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
how to create multiple objects with one request DRF
I have the following models class Product(models.Model): name = models.CharField(null=True, blank=True, max_length=500) category = models.CharField(null=True, blank=True, max_length=120) class SpecificationName(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, related_name='specifications') name = models.CharField(max_length=125) class Attribute(models.Model): spec_name = models.ForeignKey(SpecificationName, on_delete=models.CASCADE, null=True, related_name='attributes') index = models.CharField(max_length=200, blank=True, null=True) value = models.CharField(max_length=250, blank=True, null=True) after saving objects in Django admin I have an example { "name": "Apple Smart Watch", "category": "IT", "specifications": [ { "name": "Test Data", "attributes": [ { "index": "test", "value": "test2" }, { "index": "test7", "value": "test8" }, { "index": "test9", "value": "test10" } ] }, { "name": "Test Data Continued", "attributes": [ { "index": "bla", "value": "bla1" }, { "index": "bla 2", "value": "bla 4" }, { "index": "test9", "value": "test10" } ] }, { "name": "Test Spec", "attributes": [] } ] } I need to save this kind of object with one request but I am failing to do this my serializer looks like this class ProductSerializer(serializers.ModelSerializer): specifications = SpecNameSerializer(many=True, read_only=True) class Meta: model = Product fields = ['name', 'category', 'specifications'] def create(self, validated_data): return Product.objects.create(**validated_data) I searched for many answers but I did not find or applied some of them, again it did not help me. I am using just ListCreateView in … -
Select multiple options in Django
In my web app. There is a Subscription model and it has 6 subscriptions. In a single order there is two subscription selected so I want to show the selected subscriptions which are there in a order from all subscriptions in frontend. I grab all the subscriptions and the order to frontend and trying this code to select. <div class="col-sm-8"> <select class="form-control" multiple> {% for subscription in subscriptions %} <option {% for sub in order.subscriptions.all %} {% if sub == subscription.title %} selected {% endif %} {% endfor %}>{{subscription.title}}</option> {% endfor %} </select> </div> But Its not working. It showing all the subscriptions in Subscription model. But I want to selected the sub which are there in a order. Here is the frontend. -
How do you write "SELECT ... WHERE id IN (SELECT ...)" in Django?
I have trouble following the reverse related relationship in a Django query: from django.db import models class Reporter(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=500) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) "Get the reporters who wrote an article about coronavirus": SELECT * FROM myapp_reporter WHERE id IN ( SELECT reporter_id FROM myapp_article WHERE title ILIKE '%coronavirus%' ) How do I write this in Django? -
creating url shortner in django using hash
I am trying to create url shortener in django using hash (16 byte) in django. My Model : class UrlShort(models.Model): hash_url = models.CharField(max_length=100) original_url = models.CharField(max_length=100) creation_date = models.DateTimeField() expiry_date = models.DateTimeField() How will my function look if I need to store hash_url in database which is hashed from original_url with expiry_date of 30 seconds from creation_date ? -
VarsityDView is missing a QuerySet. Define VarsityDView.model, VarsityDView.queryset, or override VarsityDView.get_queryset()
My code is very simple but I'm getting error and I can't find the solution. views.py -> views.py file models.py -> models.py file -
How to import root directory file inside application in django?
My Project structure is depicted below: ├── project_name ├── app1 │ ├──views.py #I've to access root file1.py which is kept with manage.py in this file. │ ├──file1.py # But If I'm trying to import this file is being imported but I need root one │ ├──models.py ├── app2 │ ├──views.py │ ├──file1.py │ ├──models.py ├── manage.py ├── file1.py I'm using "from file1 import " in app1/views.py but the app1/file1.py is getting imported. Rather than this file I've to import project_name/file1.py file inside app1/views.py. How Can I do this? -
How to fix TypeError __str__ returned non-string
My code it still gives the error of __str__ returned non-string (type Contact) despite the fact that i cast the return statement with str() My model: class Contact(models.Model): name = models.CharField("Contact Name", max_length=50) surname = models.CharField("Contact Surname", max_length=50) company = models.ForeignKey(Customer, verbose_name='Company',on_delete=models.CASCADE) department = models.ForeignKey(Department, verbose_name='Department',on_delete=models.CASCADE) position = models.CharField("Position", max_length=50, null=True, blank=True) birthday = models.DateField("Birthday", null=True, blank=True) remarks = models.TextField("Remarks", max_length=500, null=True, blank=True) skype = models.CharField("Spype", max_length=50, null=True, blank=True) def clean(self): for field in self._meta.fields: if isinstance(field, (models.CharField, models.TextField)) and getattr(self, field.name)!=None: setattr(self, field.name, getattr(self, field.name).strip()) class Meta: verbose_name = "Contact" #####Overide save method to store names and surnames in caps def save(self, *args, **kwargs): for attr_name in ['name', 'surname', 'position']: val = getattr(self, attr_name, False) if val: setattr(self, attr_name, val.upper()) super(Contact, self).save(*args, **kwargs) def __str__(self): return self.surname + " " + self.name I also used to write the str function like this: def __str__(self): return str(self.surname + " " + self.name) but still the code returns the same error. Here is my traceback Django Version: 2.2.6 Python Version: 3.5.2 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'adminactions', 'django.contrib.admin', 'intranet', 'daterange_filter', 'gunicorn', 'notifications') Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Template error: In template /usr/local/lib/python3.5/dist-packages/django/contrib/admin/templates/admin/edit_inline/tabular.html, … -
autosuggest multiple search jquery
how to make autosuggests multiple value search? my view: def index(request): ... results = [] if request.is_ajax(): q = request.GET.get('term', '') if len(q) > 2: results = list(Tag.objects.filter(name__istartswith=q).values_list(Lower('name'), flat=True)) results = [f'{i} ' for i in results] return JsonResponse(results, safe=False) ... html: <div id="search"> <form method="get" action="{% url 'main:home' %}"> {% csrf_token %} <input type="text" name="q" placeholder="Поиск по сайту" value="{{ request.GET.q }}"> <input type="submit" value="Найти"> </form> </div> <script> ... $('#search input[name="q"]').autocomplete({ 'source': '{% url "main:home" %}', 'minLength': 2, 'appendTo': "#search" }); </script> this works correctly with one exception: I was offered https://jqueryui.com/autocomplete/#multiple, but I don’t understand what to do with it. I am not good at js, jq. please any help will be helpful -
Can not connect to smtp.gmail.com in Django
I'm trying to send email using smtp.gmail.com in Django project. This is my email settings. settings.py # Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myaccount@gmail.com' EMAIL_HOST_PASSWORD = 'mygooglepassword' views.py ... send_mail( "message title", "message content", "myaccount@gmail.com", ["myaccount@hotmail.com"], fail_silently=False) Whenever I try to send email, I get this error gaierror at /contact-us/ [Errno-2] Name or service not known I tried the followings. I set my google account's less secure app access on. I unchecked avast antivirus setting 'Setting->Protection->Core Shields->Mail Shield->Scan outbound emails(SMTP)' Tried different ports in email settings. 587 and 25 Switched the ssl and tls in email settings. But it's not sending yet. When I use 'django.core.mail.backends.console.EmailBackend' instead of 'django.core.mail.backends.smtp.EmailBackend', it prints email on console. I double checked my gmail username and password on settings. Please help me. Thank you. -
how to create new user to login from different model?
i've try to create a system for student and teachers, create new user model to login from different model , not a OneToOneField from default User model , i want to make two different registration form for visitors (Student and Teacher) forms genders_selection = ( ('male','male'), ('female','female') ) class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) email = models.EmailField() objects = UserManager() def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() class Teacher(models.Model): teacher = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(choices=genders_selection,max_length=10) age = models.PositiveIntegerField() def __str__(self): return self.user.username but this architecture wont allow similar idea , and it will required first to create User then select one of them as student or teacher !? thanks for helping