Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search input on every pages django
i want to add search in my website and i want search from my pages (html) ** note : i want take the label tag , i mean i have label tag called ' test ' and when user write in search bar 'test' i want view the label to user always i got this message in result page : not found so i create this form in home html page <form class="" action="{% url 'test_search_page'%}" method="get"> <div class="md-form mt-0 search-bar" id="search_form"> <input id="search_box" autocomplete="off" onkeyup="searchFunction()" class="form-control" type="text" placeholder="Write Here to Search ..." aria-label="Search" name="search"> </div> </form> and this is my view.py code : def search(request): input= 'search' my_template_keyword = ['label'] if 'search' in request.GET and request.GET['search'] and input == my_template_keyword: return render(request, 'home_page/testforsearch.html', {'search:':search}) finally this is my code in html result page : ` <div class="container"> {% if search%} {{search}} {%else%} <h2>not found</h2> {%endif%} </div> ` -
Query django model to retrieve set lists
I want to get all objects associated with a user and split the retrieved list into three different lists in the UI according to some additional logic. I'm currently doing this by setting a @property on the model and then in doing a bunch of loops and if/else in the template. This is obviously sub optimal, because I'd like to not include the section headers if there is nothing in the actual section, but since I'm pulling in one large list, there's no empty state. Current: model class Entry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) publish_date = models.DateField(null=True, blank=True) favorite = models.BooleanField(default=False) view entries = Entry.objects.filter(user=request.user) template <strong>FAVORITES</strong> {% for obj in entries %} {% if obj.group == 'favorites' %} ... {% endif %} {% endfor %} <strong>PUBLISHED</strong> {% for obj in entries %} {% if obj.group == 'published' %} ... {% endif %} {% endfor %} <strong>DRAFT</strong> {% for obj in entries %} {% if obj.group == 'draft' %} ... {% endif %} {% endfor %} How should I add a method on the model (e.g. get_groupings) that could return a dict with three separate querysets in it ('entries['favorites]=') in a database efficient way? -
EXEC spawning gunicorn: No such file or directory when deploy a Django project
I try to deploy a django project with nginx and gunicorn. But when I start gunicorn I get error gunicorn.service: Failed at step EXEC spawning /home/project/projectenv/bin/gunicorn: No such file or directory /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/project/project/ ExecStart=/home/project/projectenv/bin/gunicorn --access-logfile - --error-logfile error.log --workers 2 --bind unix:/home/project/project.sock project.wsgi:application [Install] WantedBy=multi-user.target ls /home/project/projectenv/bin/gunicorn - it's ok. Structure of the project home oddsportal oddsportalenv bin ... oddsportal app ... oddsportal settings wsgi ... manage.py ... -
Why isn't Heroku reading my Django urls.py?
I successfully deploy using git push heroku master, but when I click "open app" inside heroku, I receive this message. I've looked at so many different threads and solutions I think I'm starting to make a mess of my settings file. ModuleNotFoundError at / No module named 'politicalexperimentpollapp.urls' Request Method: GET Request URL: https://politicalexperiment.herokuapp.com/ Django Version: 2.2.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'politicalexperimentpollapp.urls' Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] My folder structure: /Users/Jamie/politicalexperimentpoll/ politicalexperimentpollproject (contains wsgi, urls.py, settings.py, etc.) politicalexperimentpollapp (contains urls.py) manage.py Procfile runtime.txt requirements.txt venv .vscode urls.py in project folder: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('politicalexperimentpollapp.urls')), path('admin/', admin.site.urls), ] urls.py in app folder: from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('', views.index, name='index'), path('tr', views.tr, name='tr'), ... ] settings.py import django_heroku import os SECRET_KEY = x DEBUG = True ALLOWED_HOSTS = ['127...my ip', 'politicalexperiment.herokuapp.com'] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'politicalexperimentpollapp', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'politicalexperimentpollproject.urls' TEMPLATES = … -
WhiteNoise "Resource interpreted as Stylesheet but transferred with MIME type text/html" when in K8S, but fine with local gunicorn deployment
When I run WhiteNoise locally with gunicorn the assets for the admin portal work just fune. Using this command: gunicorn -b :5000 --log-level=debug config.wsgi:application However, when I run them in K8S with Skaffold, I get the following: I've tried just about every solution that comes up when googling the warning message. Not sure what I'm doing wrong here, but trying to resolve it. This is all after running python manage.py collectstatic. Project structure (Django under server) settings.py import os import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False ALLOWED_HOSTS = [ 'localhost', '192.168.99.106', '127.0.0.1' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-party packages 'rest_framework', # Local packages 'authentication' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['PGDATABASE'], 'USER': os.environ['PGUSER'], 'PASSWORD': os.environ['PGPASSWORD'], 'HOST': os.environ['PGHOST'], 'PORT': os.environ['PGPORT'] } } REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
Is it possible to use 'disabled' argument on a choice field in UpdateView
I have been trying to disable the dropdown field (Choice) in my UpdateView. Tried out many things some of which on my own using the little expertise(!) gained so far and majorly from the suggestions available of the net (including SO). But as is clear (the reason I am posting a query here) a solution has so far eluded me. This page talks about the issue and the answer by Mike Mahmud talks about possible solution. In response to Mike's post, @bcsanches asked if the solution may be applied for UpdateView. Unfortunately there has not (so far) been a reply to the query. My question is: Can we apply the '**disabled' argument on a dropdown field?** When I tried to use this: 'plant': forms.Select(attrs={'disabled': 'disabled', 'style': 'background:lightgrey'}) it leads to error "This field is required" on form submission. When I used 'readonly' as this: 'plant': forms.Select(attrs={'readonly': 'readonly', 'style': 'background:lightgrey'}) there is no effect (the user can select the choice field and manipulate selections). When I used 'readonly' on widget TextInput (which I presume is not the right thing to do for a dropdown), I get only the field's FK field's value (which incidentally is a char field in the Plant … -
initMap is not a function when I try to add multiple click listeners to markers django
I've used Google maps in my Django project's HTML page and it works great, added multiple markers and it was good. When I tried to catch the clicking event for each marker, it gave me this error initMap is not a function, Here is my code: <style> #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <div id="map"></div> <script> // Initialize and add the map function initMap() { var gmarkers = []; const cairo = {lat: {{the_lat}}, lng: {{the_long}}}; const map = new google.maps.Map( document.getElementById('map'), {zoom: 15, center: cairo}); // The marker, positioned at Uluru {% for item in all_data %} var location{{ item.val.station_geohash }} = { lat:{{item.val.station_latitude}}, lng:{{ item.val.station_longitude }} }; var marker{{ item.val.station_geohash }} = new google.maps.Marker({ position: location{{ item.val.station_geohash }}, map: map, draggable: false, title: "{{item.val.station_name}}", animation: google.maps.Animation.DROP, }); gmarkers.push(marker{{ item.val.station_geohash }}); google.maps.event.addListener(marker{{ item.val.station_geohash }}, 'click', function () { var name = marker.title; alert(name) } {% endfor %} ); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=***************************&callback=initMap"> </script> -
Finding Django template inheritance chain?
Given the path to a Django template, is there any easy way to find a list of the template's inheritance chain? For example, if mytemplate.html inherited from user-section-base.html, which inherited from global-base.html, it would be something like: >>> print(get_template_chain('myapp/mytemplate.html')) >>> ['/project/myapp/templates/myapp/mytemplate.html', '/project/myapp/templates/myapp/user-section-base.html', '/project/myapp/templates/myapp/global-base.html'] I'm trying to write a static site generator that automatically regenerates static pages from Django templates, and I need to detect when the underlying template changes since last generation. For a single flat template with no inheritance, this is trivial, but for a template that inherits from a parent, which also inherits from a parent, I need to track changes of those files as well. However, I can't find any simple way to retrieve this, short of manually parsing the {% extends ... %} tags directly. What's the best way to do this? -
Babel/Core-JS not finding own files -- AWS EB Django
I'm having a hard time getting ReactJS and all its dependencies working properly on an AWS Elastic Beanstalk environment. Currently, I'm trying to get Babel to work. It doesn't seem to know where it has installed itself to -- what folder it's in. For example, you should be able to use "@babel/preset-env" for a preset name, but I've found I need to give the full path, "/opt/elasticbeanstalk/eb_infra/node_modules/@babel/preset-env", or else it won't be able to find it. (Similar with other presets/plugins.) I've gotten most things into a working state using this approach, except for core-js. It seems to be looking in /tmp/ to find its own modules. Weird, but I was able to add a symbolic link from there to its actual location. But now, it can't find core-js/modules/es.string.split. I looked in the real modules folder and sure enough, that file doesn't exist. So my question is, what is the file es.string.split (apart from the obvious -- some polyfill for String.split), why is it not looking for e.g. es6.string.split (which also doesn't exist), why is it missing, etc. etc. How do I get this to work. Error message I'm getting: [Application update [...]/Command 02_compress] : Activity execution failed, because: CommandError: An … -
Django view doesn't output correctly
I have a view which should output if the domain on the database is online or offline. def pingDomain(request, page): page_object = get_object_or_404(Table, page=page) try: subprocess.check_call(['ping', '-c', '1', page_object.page]) except subprocess.CalledProcessError: host_online = True else: host_online = False context = { 'online': host_online, } return render(request, 'home.html', context) On the html template <th class="center-align red-text text-darken-4" scope="row"> {% if online %} <i class="small material-icons green-text">check_circle</i> {% else %} <i class="small material-icons red-text">close</i> {% endif %} </th> The problem is, on the html template, it shows that the domains are offline but are actually online. Where did I make a mistake? Anyone familiar with this? -
Django DictReader change " " values in name[""] == " " in None
I want to replace from all 40 columns the null data from an uploaded csv file. Can i loop trough all columnnames in one and replace the " " with none at the moment i have: f = io.TextIOWrapper(form.cleaned_data['data_file'].file, encoding='utf-8') f.readline() reader = csv.DictReader(f) for item in reader: if(item['columnname'] == ''): item['columnname'] = None but i dont want to do that for 40 column names.. But is this possible? Can i loop trough all columnnames in one and replace the " " with none at the moment i have: f = io.TextIOWrapper(form.cleaned_data['data_file'].file, encoding='utf-8') f.readline() f.readline() reader = csv.DictReader(f) for item in reader: if item == '': item = None if(item['columnname'] == ''): item['columnname'] = None -
Toggling favorite item(s) on a list of items - how can i autosave items by the user, without using a submit <input>
I have a list of items displayed on a web page and i want the user to be able to favorite items on that list and for it to autosave/update in the db. How could this be done without having a submit input/btn? function myStar(id) { document.getElementById("Star_"+ id).classList.toggle("hidestar"); document.getElementById("Starfill_"+ id).classList.toggle("showstar"); } Thanks -
How to use complete database from MySQL without using models in Django
I am new to Django, and I was given a complete MySQL database with all relations and tables set. I am trying to put this data from MySQL database into my admin site. I want to know if there is any other way to retrieve data from MySQL database without using Django models. MySQL Database MySQL database I tried to use autogenerated model, but it did not work for me. Data doesn't show up in the admin site. (P.S. I do not necessarily require data to be in admin site, I am just trying to use it any ways possible) Auto-generated model by django python manage.py inspectdb > models.py admin.py from django.contrib import admin # Register your models here. from .models import Ligand admin.site.register(Ligand) Please, let me know if you know any ways to use data from MySQL database that was not created using Django model. Thanks in advance -
channels_rabbitmq connection immidiatly killed
I am running django channels on daphne behind nginx with via docker-compose. I am using rabbitmq for the channels layer. When channels attempts to connect to rabbitmq on my production server, the connection is immidiatly killed. channels log output (repeated every second): web_channels_1 | 2019-10-22 14:15:03,991 INFO Channels connecting to RabbitMQ at amqp://user:bitnami@rabbitmq:5672 web_channels_1 | 2019-10-22 14:15:03,994 ERROR An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly. web_channels_1 | 2019-10-22 14:15:03,995 WARNING Connect/run on RabbitMQ failed: OSError(9, 'Bad file descriptor'); will retry in 1.000000s This is only a problem on the production server running debian 9, i cannot reproduce it on any of my local machines, also running debian 9. The problem also persist when using the build in django debugging server instead of nginx + daphne. Django channel layer settings: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_rabbitmq.core.RabbitmqChannelLayer", "CONFIG": { "host": 'amqp://user:bitnami@rabbitmq:5672', }, }, } Docker-compose rabbitmq service: rabbitmq: image: 'bitnami/rabbitmq:latest' networks: - database_network restart: always The network has a bridge driver and is shared with the daphne service amongst several others. If anyone has any idea what this could be, it would be really appreciated. -
django-hitcount | How to count hit, when clicking on button
I'm creating a blog, and I want to count a download, when an user pressed on a button/link. I want to use django-hitcount, because it has that spam-protection with ip, session etc. I'm already counting the views of my PostDetailView and it's working, but on the same page is a download button and I want to count how many users clicked on this button. I already tried to fix the problem using the documentation (https://django-hitcount.readthedocs.io/en/latest/installation.html#counting-hits), but I'm still not sure how to do it. I want to increase the "downloads" variable, when a hit counts. class Post(models.Model, HitCountMixin): title = models.CharField(max_length=40) content = RichTextField(max_length=20000) downloads = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) -
Check if varible is an list in queryset django
I'm trying to check if my variables are in my querySet. Varialbes coming from a form: def magazine_new(request): if form.is_valid(): post.mag_no = request.POST.get('mag_no') post.cn1 = request.POST.get('cn1') post.cn2 = request.POST.get('cn2') post.cn3 = request.POST.get('cn3') post.cn4 = request.POST.get('cn4') Then, I want to check if these CNs exist in this mag_no I tried this, but didn't work. if Magazine.objects.filter(prodc_magt_no__in = [post.cn1,post.cn2,post.cn3,post.cn4] and mag_no=post.mag_no): form.save() return redirect('someview') else: return HttpResponse('Dind't exist or match to this magazine no') return render(request,'cnCreate.html',{'form':form}) I'm having the error "too many values to unpack (expected 2)" or in order tests, this query didn't work. How to do this query to check if these Cns exists in prodc_magt_no field in database The magazine must be the same: post.mag_no = mag_no -
Could not add new columns to model
I'm using PostegreSQL. What I've tryed already: python manage.py flush python manage.py makemigrations python manage.py migrate python manage.py makemigrations app python manage.py migrate app python manage.py migrate --run-syncdb There aren't any effect. The table have no recently added columns. Have no importaint data in tables, can remove it. -
Django CreateView with a ManyToMany field?
I've been working on something for a few days, I saw some similar posts here, but I am still having trouble getting it! I will post a small snippet. I have a Recipe model, with many fields but I will post the one that I am referring to. ingredients = models.ManyToManyField('recipes.Ingredient', related_name='in_recipes') And then I have an Ingredient model of course, with name, description, etc. I want to be able to have a CreateView where I can add any amount of ingredients to a single recipe. I got as far as only being able to list the Ingredients already in my database. I was looking for a single Recipe form that includes the Ingredient form and fields. Any help would be greatly appreciated! -
Checkboxes True or False not loading into form properly
I'm using a ModelForm to load a Form and all of the values are pulling properly except the checkboxes. They always load in unchecked whether or not their state is True or False. I've tried creating the checkbox fields like: <label> <input type="checkbox" checked='{{ form.instance.hot }}'> <span>Hot{{ form.hot }}</span> </label> Which results in the checkbox always being checked instead matching what's in the table for that client. models.Client class Client(models.Model): #Account Information client_status =[("1", "Active"), ("0", "Inactive")] WHOPAYS =[("0", "Not Applicable"), ("1", "They Pay"), ("2", "We Pay")] hot = models.BooleanField(default=False, required=False) region = models.ForeignKey('Region', to_field='region_id', on_delete=None, null=True, blank=True) sub_account = models.ForeignKey('self', on_delete=models.CASCADE, related_name='sub_account_of_client', null=True, blank=True) created = models.DateField('Account Creation', auto_now_add=True) client_class = models.ForeignKey('ClientClass', on_delete=None, null=True, blank=True) category = models.ForeignKey('ClientCategory', on_delete=None, null=True, blank=True) they_pay = models.BooleanField('They Pay', default = False, required=False) we_pay = models.BooleanField('We Pay', default = False, required=False) csr = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service')) #Upload location /<ClientID>/documents/* documents = models.FileField(null=True, blank=True, upload_to=client_directory_path) notes = models.TextField(null=True, blank=True) active_status = models.CharField('Status', max_length=1, choices=client_status, default="1") client = models.CharField('Client/Company Name',max_length=200, null=True, blank=True) account_number = models.CharField(max_length=50, null=True, blank=True) #Contact Information first_name = models.CharField('First Name', max_length = 200, null=True, blank=True) last_name = models.CharField('Last Name', max_length = 200, null=True, blank=True) … -
DRF: Accept date data in any format like rather than default "YYYY-MM-DD" format and convert save in default format
I created a model ProjectInvoice class ProjectInvoice(models.Model): date = models.DateField() ......................... then I wrote a serializer class ProjectInvoiceSerializer like this class ProjectInvoiceSerializer(serializers.ModelSerializer): class Meta: model = ProjectInvoiceBooking fields = ['date',...] def update(self, instance, validated_data): instance.date = validated_data.get('date', instance.date) how can i modify the code so that i can accept date data in any format like rather than default "YYYY-MM-DD" format and convert save in default format -
Django add extend permissions
I need to make some specific permissions to view sections of the site. How can they be created so that they can be adjusted through the admin panel? -
ModelForm field included even when not in fields
I have the following model: class Test(models.Model): name = models.CharField(max_length=100) And the admin: class TestForm(forms.ModelForm): confirm_name = forms.CharField(max_length=100) ... @admin.register(Test) class TestAdmin(admin.ModelAdmin): form = TestForm fields = ('name',) create_fields = ('name', 'confirm_name') def get_fields(self, request, obj=None): fields = super().get_fields(request, obj) if not obj: fields = self.create_fields return fields Everything works fine. But when you add a record and then try to edit it, I get the error "Please correct the error below." without showing any field errors. I checked the form errors and it says confirm_name should not be empty. Why is it still being included if it's not added in fields? -
How to configure Mysql to avoid an error: Illegal mix of collations
Every time I run the django unit test, a test database is created. During the test, I encounter an error django.db.utils.DatabaseError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='") I know there's a solution for a production database. Is it possible to override the mysql configuration so that the correct encoding is applied by default to each new test database? -
Getting error on django rest framework Unsupported lookup 'text' for JSONField or join on the field not permitted, perhaps you meant exact or iexact?
I'm getting this error=> Unsupported lookup 'text' for JSONField or join on the field not permitted, perhaps you meant exact or iexact? Unable to figure how to solve this. I'm getting this above error when trying to query on field that has nested json data. I'm using DB Mongodb and Djongo engine to connectand framework id Django rest framework. Please guide me to solve this issue. View===== @api_view(['GET']) def gettweets(request): if request.method == 'GET': tweets = TwitterMaster.objects.all() tt = request.query_params.get('tt') if tt: condition = Q(data__text__contains=tt) #condition = Q(tweet_text__contains=tt)&Q(tweet_favorite_count=13) tweets = tweets.filter(condition) # srz = serializers.serialize('json',tweets) #print(tweets.query) serializer = TwitterdashappSerializer(tweets, many=True) totCount = 0 if serializer.data is not None: totCount = len(serializer.data) respData = {"totCount":totCount} return Response({"message": "success", "data":respData},200) return Response({"message": "OOPS","error_code":"gettweets_404"},404) Model => from djongo import models from jsonfield import JSONField class TwitterMaster(models.Model): tweet_id = models.BigIntegerField(primary_key=True) data = JSONField(default='', blank=True) location = models.CharField(max_length=250, blank=True, null=True) latitude = models.CharField(max_length=250, blank=True, null=True) longitude = models.CharField(max_length=250, blank=True, null=True) Serializer======= class TwitterdashappSerializer(serializers.Serializer): tweet_id = serializers.CharField() data = serializers.JSONField() location = serializers.CharField() latitude = serializers.CharField() longitude = serializers.CharField() def create(self, validated_data): instance = TwitterMaster.objects.create(**validated_data) return instance -
How to clear suggestions from login form in django
I'm working on a project in Django and I have a login form. I have added and deleted some users with register new user form. Now when I enter new login it shows me suggestions of the names that I added earlier I want to remove these suggestions. I have no clue what to do.