Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration with "--fake-initial" is not working if AddField referes to "same" column
I'm playing with django (I'm a quite new beginner) and while surfing the web I read it could be possible to keep our internal camelCase naming conventions inside the mySQL database and also for the models' name inside models.py Well, after some days I can conclude it's better to leave things as they were designed and use the standard output generated by inspectdb without any change to its code (I removed the .lower() functions :-) ) Anyhow, just out of curiosity, I would appreciate if somebody can explain me why what follows is not working. Briefly, it seems to me that the code responsible for the migration is not checking correctly(?) if a column name is already inside the database, or at least it does its comparison in case-sensitive manner. Is that by design? I'm using this guide from the internet https://datascience.blog.wzb.eu/2017/03/21/using-django-with-an-existinglegacy-database/ The mysql is running with the option " --lower-case-table-names=0" and the collation is case-insensitive. Inside the models.py I have this class City(models.Model): id = models.AutoField(db_column='ID', primary_key=True) name = models.CharField(db_column='Name', max_length=35) countrycode = models.ForeignKey(Country, db_column='CountryCode') district = models.CharField(db_column='District', max_length=20) population = models.IntegerField(db_column='Population', default=0) def __str__(self): return self.name class Meta: managed = True db_table = 'city' verbose_name_plural = 'Cities' ordering … -
What happens is ordering is not specified in Django model Meta
If the ordering field in the inner Meta class of a model is not specified does does the generated SQL query return results with items at randomized positions? If true then pagination (slicing for offsets) will return duplicates on next pages, right? -
Django development server unreachable
I run django on my windows 7 machine without virtual environment. After typing - "python manage.py runserver" it shows me that development server is running at http://127.0.0.1:8000 but whenever I try to access it shows me an error like - "This site can’t be reached. 127.0.0.1 took too long to respond." I also tried on different ports like - 8001, 8080 but couldn't get into it. -
Django 2, No module named error when trying to import my own modules
I'm a beginner in Django and I have an issue when I try to import my own module in views.py. I'm actually using Pycharm IDE. You will see below the structure of my project I want to use some class which are in IOCVisualizeEntities project in views.py. I read that I must declare the IOCVisualizeEntities application in INSTALLED_APPS (in settings.py) like this: INSTALLED_APPS = [ 'IOCVIsualizeView.apps.IocvisualizeviewConfig', 'IOCVIsualizeEntities', ... ] but I have the error 'No module named 'IOCVIsualizeEntities' where I run the server. Thanks for your help, project structure -
Django REST Framework changing the name of nested resources
Given the following models: from django.db import models class Library(models.Model): name = models.CharField(blank=True, max_length=50) class Book(models.Model): name = models.CharField(blank=True, max_length=50) library = models.ForeignKey(Library, models.SET_NULL, blank=True, null=True) How would I create a serializer in Django REST Framework with the the Library model nested but under a different name? For example library being renamed to biblio? { "name": "The Ordeal of Change", "biblio": { "name": "National library" } } Current serializers: from rest_framework import serializers class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = ('name',) class BookSerializer(serializers.ModelSerializer): store = LibrarySerializer(read_only=True) class Meta: model = Book fields = ('name', 'store') -
How to Design a Website: Steps to follow?
I'm very new to web-designing and web-development. Is there any standard procedure for web development? I mean, do we have to first complete the design of the website and then start connecting it to the backend? or Do we design the website and connect it to the backend, include links and add necessary page URLs to the button, do all these things parallelly? Please forgive me if I'm asking this question very vaguely, but I'm trying to develop a website in Django, doing things parallelly, but things are not going well. So, I just want to know which is the better and efficient method. Thanks. -
Django REST Framework update foreign key field on PUT
I'm using Django 2.x and Django REST Framework My models.py file contents class ModeOfPayment(models.Model): title = models.CharField() class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField() mode_of_payment = models.ForeignKey( ModeOfPayment, on_delete=models.PROTECT, blank=True, default=None, null=True ) and serializers.py class ModeOfPaymentSerializer(serializers.ModelSerializer): class Meta: model = ModeOfPayment fields = ('id', 'title') class AmountGivenSerializer(serializers.ModelSerializer): mode_of_payment = ModeOfPaymentSerializer() class Meta: model = AmountGiven depth = 1 fields = ( 'id', 'contact', 'amount', 'mode_of_payment', ) def update(self, instance, validated_data): mode_of_payment = validated_data.pop('mode_of_payment') instance.mode_of_payment_id = mode_of_payment.id return instance and views.py class AmountGivenViewSet(viewsets.ModelViewSet): serializer_class = AmountGivenSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission,) filter_fields = ('contact__id',) def get_queryset(self): queryset = AmountGiven.objects.filter( contact__user=self.request.user ) return queryset But when I post data using postman with PUT method to update the existing record It still says { "mode_of_payment": [ "This field is required." ] } -
How to extends and include in organizing django templates?
I have code like this, in my django templates folder: base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% block home %} {% endblock home %} </body> </html> top.html <div id="top"> <h1>This is the navbar content</h1> </div> left.html <div id="left"> <p>This is the menu content</p> </div> Now i want to include each of these templates into a home template like this home.html {% extends "myapp/base.html" %} {% block home %} {% include "myapp/top.html" %} {% include "myapp/left.html" %} {% endblock home %} And this is my render function in views.py views.py def home(request): return render(request, 'myapp/home.html') But when i run the server the include statement inside of 'home.html' doesn't work. What is going on? Thanks. -
Django app with Nginx and uwsgi: Getting 502 Bad Gateway and can't start uwsgi
I am trying to deploy my Django application on Alibaba ECS using nginx and uwsgi. When I access my public IP, sometimes I get the application running but mostly I am getting 502 Bad Gateway error. One interesting case is when the application is running and I make changes to my Django application, it doesn't instantly reflect on the server but again I get the error on refreshing the page. This happens always. Also, I can't get to start uwsgi. When I do sudo systemctl start uwsgi, I get the following result: Job for uwsgi.service failed because the control process exited with error code. See "systemctl status uwsgi.service" and "journalctl -xe" for details. systemctl status uwsgi.service gives the following result: ● uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; disabled; vendor preset: enabled) Active: inactive (dead) systemd[1]: Stopped uWSGI Emperor service. systemd[1]: Starting uWSGI Emperor service... systemd[1]: uwsgi.service: Main process exited, code=exited, status=203/EXEC systemd[1]: Failed to start uWSGI Emperor service. systemd[1]: uwsgi.service: Unit entered failed state. systemd[1]: uwsgi.service: Failed with result 'exit-code'. systemd[1]: uwsgi.service: Service hold-off time over, scheduling restart. systemd[1]: Stopped uWSGI Emperor service. systemd[1]: uwsgi.service: Start request repeated too quickly. systemd[1]: Failed to start uWSGI Emperor service. journalctl … -
Couldn't import Django when launching test server
When running the command: python manage.py runserver To launch a test server, I get the following error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Steps I took to get this error: 1) I downloaded the Django project from my Linux VPS (without the virtual environment). I am using Windows 10 on this current system. 2) I created a new virtual environment in that folder using: virtualenv myprojectenv 3) The env was created successfully, I now have the following folders/files: myproject myprojectenv static manage.py 4) I activate the env (myprojectenv\scripts\activate), success - my commandline changes to (myprojectenv) C:\ (path to my folder) 5) I install Django using pip install django Django successfully installed, when checking the version, it returns 2.1.1: python -c "import django; print(django.get_version()) 2.1.1 6) I go back to the main dir where manage.py is, I try to run the test server with python manage.py runserver And I get the error (specified above). So, what have I done wrong here? I have the env folder correctly in that directory, Django installed. It still can't find it. I thought the problem may be … -
How to store variables in Django?
I want to save some defined variables in Django (simply said, a model class with only one instance). For that currently I'm using model.object.get( pk=1 ) and creating a model for that Other option I know about is creating a simple text file and storing variables(as a dict etc.). And reading through that whenever some change is required. Is there some other easier way of doing that ? -
SMTPSenderRefused at /password_reset/
SMTPSenderRefused at /password_reset/ (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError r13-v6sm6514618wmf.35 - gsmtp', 'webmaster@localhost') enter image description here -
nginx "ERR_TOO_MANY_REDIRECTS" after add ssl
After i add Let's Encrypt certificate to my website with CertBot i get ERR_TOO_MANY_REDIRECTS when i try to visit the domain of my website. some info : -mywebsite build with django, nginx and gunicorn. server { server_name www.mydomain.com mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.mydomain.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = mydomain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.mydomain.com mydomain.com; return 404; # managed by Certbot } please tell me if you need any other code/info thanks Note : i have read all the questions with the same problem and i still can't know what is wrong -
Python Django flask-cors Control-Allow-Origin'
Trying to execute simple json request on local server combined with Python and django. my apiview.py from rest_framework import generics from django.shortcuts import get_object_or_404 from .jsonserializer import GroupSerializer, SubgroupSerializer, ProductsSerializer from .models import pGroups, pSubgroups, Products from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route("/Group/") # @cross_origin() # Create your views here. class GroupList(generics.ListCreateAPIView): queryset = pGroups.objects.all() serializer_class = GroupSerializer Jquery script let dropdown = $('#locality-dropdown'); dropdown.empty(); dropdown.append('<option selected="true" disabled>Choose product group</option>'); dropdown.prop('selectedIndex', 0); const url = 'http://127.0.0.1:8000/Group/'; // Populate dropdown with list of provinces $.getJSON(url, function (data) { $.each(data, function (key, entry) { console.log(entry.name); dropdown.append($('<option></option>').attr('value', entry.abbreviation).text(entry.name)); }) }); And after all i log in console smthng like : Failed to load http://127.0.0.1:8000/Group/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. What i'm trying is : Flask cors but seems im missing something in apiview.py . P.S I'm complete beginner in web. -
web scraping using request showing empty tables?
from lxml import html import requests page = requests.get('http://www.freejobalert.com/upsc-advt-no-17/31908/') tree = html.fromstring(page.content) tables = tree.xpath('//table/text()') print(tables) here i wants to get all the table from above url. But it is coming empty list wheather many tables are available in web page. -
how to use python package django-dotenv
I've created a .env file to store my django secret key. I've installed django-dotenv and edited my manage.py and wsgi.py as told in https://github.com/jpadilla/django-dotenv . I'm wanting to upload my project to heroku and I did but I got the error related to secret key. That being said how can I modify my settings.py to access .env data using this package? I couldn't get enough information regarding this. -
Django deployment issues w/Plesk "No WSGI daemon process called '<>' has been configured"
I've been successful in deploying various Django sites with apache before, but I'm on a server which has a Plesk distribution installed. So, in getting setup I have deployed a pretty basic application: Basic contents of the Django Application The permissions that have been blacked out all contain the same username. However, the apache error_logs for this domain is showing the following error: 2018-09-30 13:55:06 [wsgi:error] No WSGI daemon process called 'daemonuplordvexxos' has been configured: /var/www/vhosts/winduplordvexxos.com/api.winduplordvexxos.com/apiuplordvexxos/wsgi.py My additional apache directives are as follows (where I have setup https): Additional Apache Directives Googling the vital line No WSGI daemon process called 'daemonuplordvexxos' has been configured has yielded zero luck. My wsgi.py file is a standard from Django 2.1.1 install: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiuplordvexxos.settings') application = get_wsgi_application() -
Django upgrade from 1.10 to 1.11 DeprecationWarning
I am trying to upgrade my project from Django 1.10 to 1.11: >>> django.VERSION (1, 10, 0, 'final', 1) When I run python -Wall manage.py test, I get the following error message: C:\Users\Environments\lib\site-packages\django\contrib\auth\base_user.py:52: DeprecationWarning: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? class AbstractBaseUser(models.Model): I have looked around but could not find a solution to address this complaint. Given that I am extending the user class, this should not be particular to my project. So, has anyone found a way to resolve this? class User(AbstractBaseUser, PermissionsMixin): """ Custom user class """ USER_TYPE = ( ('owner', 'Owner'), ('developer', 'Developer'), ('general contractor', 'General Contractor'), ('general contractor\'s employee', 'General Contractor\'s Employee'), ('consultant', 'Consultant'), ('subcontractor', 'Subcontractor'), ('home owners', 'Home Owners'), ('construction financier', 'Construction Financier'), ('lawyer', 'Lawyer'), ('accountant', 'Accountant'), ) email = models.EmailField(verbose_name = 'email address',unique = True, db_index = True) # email is the unique field that can be used for identification purposes joined = models.DateTimeField(auto_now_add = True) is_active = models.BooleanField(default = True) is_admin = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) #is_staff = models.BooleanField(default = False) user_type = models.CharField(max_length = 30, choices = USER_TYPE) group = models.ManyToManyField(Group, related_name = 'users') permission = models.ManyToManyField(Permission, related_name = 'users') objects … -
Unable to render content inside the Django block content Django 1.7
I am trying to render some content inside the Django template. But for some reason nothing is being rendered inside the block tags. I am really confused as what could i be doing wrong. I am using Django 1.7 and Python 2.7. This is what i tried so far views.py def show_product(request, product_slug, template_name="catalog/product.html"): print('Product info') print('productslug',product_slug) p = get_object_or_404(Product, slug=product_slug) print('p',p.sku) categories = p.categories.filter(is_active=True) print('categories',len(categories)) page_title = p.name meta_keywords = p.meta_keywords meta_description = p.meta_description return render_to_response(template_name, locals(), context_instance=RequestContext(request)) product.html {% extends "tags/catalog.html" %} {% block content %} <div class="product_image"> <h1>{{ p.name }}</h1> </div> {% endblock %} settings.py """ Django settings for lstm project. Generated by 'django-admin startproject' using Django 1.11.10. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition TIME_ZONE = 'Africa/Kenya' USE_TZ = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog', 'utils', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
How do I reuse single model field validators for forms without using ModelForm?
How can I reuse model field validators when creating a form. I can't use ModelForm because the form only uses part of the model's fields and I also have additional form fields. Minimal example I have a model for an (encryption) key that is always 32 characters in length and I want to use this restriction in the model and forms that accept that key. I am looking for a idiomatic way to do this in Django 2.1. models.py class EncryptionKey(models.Model) key = models.CharField("Encryption Key", max_length=32, min_length=32) forms.py class NewUserForm(forms.Form): first_name = forms.CharField(label='First Name', required=True, max_length=256) last_name = forms.CharField(label='Last Name', required=True, max_length=256) key = # How do I reuse the key from the model here? -
Unable to retain the form filter value after successfully searching the Users based on User Groups in Django
I am able to search the security user groups successfully. But while pressing the search button, the search value is getting vanished with the search results. I want the search value to be retained in the search field until I manually remove it or refresh the page. I am overriding the django admin Groups model and this is the field that I am trying to search from the UserListView. models.py: class User(AbstractBaseUser, PermissionsMixin): groups = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='user_group', blank=True, null=True) views.py class UsersListView(AdminRequiredMixin, TemplateView): model = User context_object_name = "users" template_name = "list.html" def get_queryset(self): queryset = self.model.objects.all().select_related("groups") request_post = self.request.POST if request_post: if request_post.get('groups'): queryset = queryset.filter(groups_id=request_post.get('groups')) return queryset def get_context_data(self, **kwargs): context = super(UsersListView, self).get_context_data(**kwargs) context["groups_list"] = User.objects.all() return context Templates: This is how I am searching the groups field in template. HTML Code: <div class="filter_col col-4"> <div class="form-group"> <label for="exampleInputEmail1">User Group</label> <select class="form-control" id="id_groups" name="groups"> <option value="" selected="selected">--Select an User Group--</option> {% for group in groups_list %} <option value="{{group.groups.id}}" {%ifequal group.groups.id request.POST.group.groups|add:"0"%} selected {%endifequal%}>{{ group.groups.name }}</option> {% endfor %} </select> </div> </div> Can someone please help, when I select the security group option (Admin, Staff, etc) in the search filter and press the search button. The search … -
mutation when having multiple foreign key
I am learning graphql and graphene-django today. I could query and mutate the simple table but could not mutate when the table has foreign key relationship. I have a model like this class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150, blank=False, null=False) slug = models.SlugField() email = models.EmailField(max_length=150, blank=False, null=False) class Brand(models.Model): ZERO = 'Zero' ZEROTOTEN = 'ZTT' TENTOTWENTY = 'TTT' NUMBER_OF_FRANCHISES = ( (ZERO, '0'), (ZEROTOTEN, '0 - 10'), (TENTOTWENTY, '10 - 20'), ) company = models.ForeignKey(Company, related_name='company_brand', on_delete=models.CASCADE) name = models.CharField(max_length=150, blank=False, null=False) franchising_date = models.DateTimeField() number_of_franchises = models.CharField(max_length=5, choices=NUMBER_OF_FRANCHISES, default=None) class BusinessModel(models.Model): company = models.ForeignKey(Company, related_name='company_business_model', on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, related_name='industry', on_delete=models.SET_NULL) segments = models.ForeignKey(Segment, on_delete=models.SET_NULL, null=True) total_investment = models.CharField(max_length=50, choices=TOTAL_INVESTMENT, default=None) franchise_fee = models.CharField(max_length=50, choices=FRANCHISE_FEE, default=None) With such kind of model, I have my following schema with input type but no idea on how can i create a table for brand and business model also as they are linked with company. class CompanyInput(graphene.InputObjectType): name = graphene.String(description='Name of your company') email = graphene.String(description='Email of your company') phone_number = graphene.String(description='Phone number of your company') director = graphene.String(description='Director of your company') franchise_head = graphene.String(description='Franchise Head of your company') class BrandInput(graphene.InputObjectType): company = graphene.List(CompanyInput) name = graphene.String() … -
dajngo TypeError: required() got an unexpected keyword argument 'username'
There is no errors in the code but when it runs it doesnt work. I have a project with a similar code and it works perfectly. error: Traceback (most recent call last): File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/pablo/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: required() got an unexpected keyword argument 'username' this is the code: vews.py: def profile_view(request, username): user = User.objects.get(username=username) profile = Profile.objects.get(user=user) own_profile = Profile.objects.get(user=request.user) if request.method == 'POST': if 'follow' in request.POST: own_profile.following.add(profile) profile.followers.add(own_profile) if 'unfollow' in request.POST: own_profile.following.remove(profile) profile.followers.remove(own_profile) posts = Post.objects.all()[:10] return render(request, 'accounts/profile.html', {'profile': profile, 'own_profile': own_profile, 'posts': posts}) urls.py: from django.urls import path from .views import login, logout, signup, edit_profile, profile_view app_name = 'accounts' urlpatterns = [ path('login/', login, name='login'), path('logout/', logout, name='logout'), path('signup/', signup, name='signup'), path('editprofile/', edit_profile, name='edit_profile'), path('<str:username>/', profile_view, name='profile'), ] -
Iterating lists in django template
I have different lists context = { 'query' : request.POST['query'], 'link' : link, 'description' : description, 'title' : title, 'thumbnail' : thumb, 'range' : range(len(title)), } and I want to iterate through them something like for i in range(20): link[i] title[i] in django template. How can i do it. -
select_related on nullable fields does not work as expected in view
I am using select_nullable in a Django view to retrieve a relationship that can be null, so I am explicitely passing it as a parameter: source_text = get_object_or_404(Text.objects.select_related('language'), pk=source_text_pk) The problem is that when I'm accessing it in a template it generates a database query, i.e.: # items/templates/items/source.html {{source.language.code}} Testing it with: # items/tests/test_views.py ... source_text = TextFactory() context = {'source': source_text} with self.assertNumQueries(0): # render the template with given context to trigger possible db hits from django.template.loader import render_to_string rendered = render_to_string("items/source.html", context) Generates: ... AssertionError: 1 != 0 : 1 queries executed, 0 expected Captured queries were: 1. SELECT "languages_language"."id", "languages_language"."name", "languages_language"."code" FROM "languages_language" WHERE "languages_language"."id" = 16 Involved models are defined as: # items/models.py class Text(models.Model): language = models.ForeignKey('languages.Language', on_delete=models.SET_NULL, blank=True, null=True) # languages/models.py class Language(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=35) def __str__(self): return "name: {} \tcode: {}".format(self.name, self.code) How should I use select_related to not generate a database query in the view?