Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 500 error: WSGIRequest object has no attribute 'scope'
When I deployed the application on the server using uwsgi, I got an error AttributeError at / 'WSGIRequest' object has no attribute 'scope' There is no such problem on the local machine, everything works. The part of code getting this error: class UserActivityMiddleware(MiddlewareMixin): def process_response(self, request, response): activities = [activity for activity in ACTIVITIES if re.match(activity['path'], request.scope.get('path')) and activity['method'] == request.scope['method']] if activities: ..... -
ModuleNotFoundError: No module named sqlparse
When I try to run the command: python manage.py runserver I get an error stating that there is no module named sqlparse. I ran the command pip install sqlparse and conda install sqlparse and it says that it's already installed but the error persists.enter image description here enter image description here -
I am trying to connect via ssh to Mysql database like I did before from jupiter notebook.Why is my query command not working?
I connected before to a server via ssh before with this code on my Jupiter notebook. Now when I try to put it on my Django server or in a python file and execute it in the terminal the query is not working and runs until I stop the script manually. host = 'xxx' localhost = '127.0.0.1' ssh_username = 'xxx' ssh_password = 'xxx' user='xxx' password='xxx' database='xxx' print(1) from sshtunnel import SSHTunnelForwarder import MySQLdb as db import pandas as pd def query(q): with SSHTunnelForwarder( (host, 22), ssh_username=ssh_username, ssh_password=ssh_password, remote_bind_address=(localhost, 3306) ) as server: conn = db.connect(host=localhost, port=server.local_bind_port, user=user, passwd=password, db=database) return pd.read_sql_query(q, conn) print(2) df_1 = query('select * from oriv7_satcar_trip limit 5') print(3) print(df_1) The script runs fine until it gets time to query.I can not understand why it freezes like that when It worked before in Jupiter notebook -
Django update forms: set the initial choice field to the user's current group
I have a form for updating user's info, especially for permission group. My form works fine, but I want to set user's current group by default in the group choice. forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'group_name', 'is_active', 'password',) views.py @login_required @group_required('Staff') def updateUserView(request, id): i = User.objects.get(id=id) if request.method == 'POST': form = UpdateForm(request.POST, instance=i) if form.is_valid(): user = form.save() messages.success(request, "User has been updated!") user.groups.clear() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=i) return render(request, 'accounts/update_user.html', {'form': form}) -
Sharing links with accompanying thumbnail on your own site
I need some direction. I'm building a social media site with django and I'm trying to design it like twitter/facebook, so that when someone posts a link - say from the New York Times - it displays the headline of the article along with the accompanying thumbnail. Problem is: I don't even know what this is called, or how to begin. Can someone point me in the right direction? Even just a term I can google to learn more? -
'Required parameter {0} not set'.format(identifier))
I'm setting up my AWS for my static files. Basically, when user upload a picture it will directly stored the pictures on my AWS S3. I've done all the procedures, but it gives me an error saying Value error at //profile/ and Required parameter name not set. On my local machine it works, but it wasn't working when I deploy it. I tried to restart my database then migrate it to heroku command but still get the same error models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete =models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') update = models.DateTimeField(default = timezone.now) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) views.py def profile(request): profile = Profile.objects.get_or_create(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form':u_form, 'p_form':p_form } return render(request,'users/profile.html',context) settings.py STATIC_URL = '/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT=os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' AWS_LOCATION = 'static' AWS_ACCESS_KEY_ID= os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY= os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME= os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I expect the functionality will be the same as … -
How to fix 'ModuleNotFoundError: No module named 'mainpage' ' when starting gunicorn?
Well, i'm trying to start $ sudo docker-compose -f prod.yml up, and receive an error ModuleNotFoundError: No module named 'mainpage' when Gunicorn starts gis workers. The path to my wsgi.py is right, it was my last error :D, an i've fixed it. Well i set my wsgi path right. I've tried to run it through manage.py runserver and it works well. I've tried to run it through manage.py runserver outside the docker and it works well. this is my project structure: IRM ├── app │ ├── backend │ │ ├── api │ │ ├── combinator │ │ ├── crowler │ │ ├── IRMback │ │ │ ├── __init__.py │ │ │ ├── settings.py │ │ │ ├── urls.py │ │ │ ├── views.py │ │ │ ├── wsgi.py │ │ ├── mainpage │ │ ├── manage.py │ │ └── ... │ ├── frontend │ │ └── ... │ requirements │ ├── base.txt │ ├── local.txt │ └── prod.txt │ docker │ ├── local │ └── Dockerfile │ ├── prod │ └── Dockerfile ├── docker-compose.yml └── prod.yml this is my prod.yml version: '3' volumes: pgdata: services: web: build: context: . dockerfile: docker/prod/python/Dockerfile volumes: - ./app:/app ports: - "8000:8000" command: gunicorn -w … -
How to use enumerate(zip(seq1,seq2)) in jinja2?
I'm trying to color some sequences of RNA using Django. I'm using enumerate and zip to find equals index in list. for example: for i, (a, b) in enumerate(zip(seq1, seq2)): if a == b and i not in green: <p style="color: green;">{{i}}</p> elif a != b and i not in red: <p style="color: red;">{{i}}</p> I recive this error in my template: 'for' statements should use the format 'for x in y': for i, (a, b) in enumerate(zip(seq1, seq2)): -
Is there a django-orm lookup for querying nested jsonfield key?
My table has a JsonField column named meta_data. One of its entries is: {'abc':'zyz', 'name':{'pranav':'age', 'john':'age'}} To query on Jsonfield i use __has_key lookup: table.objects.filter(id__in=id_list, meta_data__has_key='name') I want to findout if there is some django lookup that helps me check if there is the key 'pranav' inside 'name' like: table.objects.filter(id__in=id_list, meta_data__has_key__has_key='pranav') or something like that Thanks for any input on this...! -
Django how to preserve request body across redirects?
I have a view like so: class ConfirmCancellationView(View): def post(self, request): #has request.foo - the thing to cancel return render(request, "confirm_cancellation.html") The html for this view: <form method="post" action="{% url 'cancel_entry' %}"> {% csrf_token %} <button class="btn--primary" type="submit" id="cancel">Yes, cancel instruction</button> </form> The problem is, while my ConfirmCancellation has the information I want to cancel (called fooin the code ), the SAME request is not passed to my cancel_entry view. It complains that foo is not an attribute... How do i make it so that the same request, containing foo, is passed to the redirect url? -
How to configure DJANGO_SETTINGS_MODULE on macOS
Django: 2.2.4 macOS: Mojave 10.14.5 Hello I am having difficulty setting up Django, and in particular trying to run the server on a fresh install. Here are the steps I have taken. // Create and a enter into a new directory mkdir mysite && cd mysite // Create a virtual environment and activate it virtualenv venv -p python3 source venv/bin/activate // Install Django pip install Django // Create a new django project django-admin startproject mysite . // Run the server django-admin runserver And from there this is the error message... django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I then set the environment variable export DJANGO_SETTINGS_MODULE=mysite.settings but I then get the following error ModuleNotFoundError: No module named 'mysite' What am I doing wrong? I have also tried running django-admin runserver --settings=mysite.py -
type error when creating django custom models superuser
type error createsuperuser() is missing 1 required positional argument username -
How can I display objects from different models?
I am doing website for game tournaments. I have models for matches,teams and players. I don't understand how to create view for the single match. I tried to change queryset, but I don't know how to do it properly. I did view for the sigle team, for the whole list of matches, but not for the single match. views.py from django.views.generic import ListView, DetailView from . import models from django.shortcuts import get_list_or_404, get_object_or_404 class TestView(ListView): model = models.TestTeam template_name = 'home.html' class TeamView(ListView): model = models.TestPlayer template_name = 'team.html' # Single team players displaying # There are displayed players who has team's slug in their kwargs def get_queryset(self): queryset = super().get_queryset() if 'slug' in self.kwargs: team_slug = self.kwargs['slug'] queryset = queryset.filter(team__slug=team_slug) return queryset class MatchListView(ListView): model = models.TestMatch template_name = 'home.html' class MatchDetail(DetailView): model = models.TestMatch template_name = 'match.html' models.py from django.db import models from django.urls import reverse from django_extensions.db.fields import AutoSlugField class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') slug = AutoSlugField(populate_from='name') def __str__(self): return self.name class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, default='Team') # photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin … -
Enable CORS in a Django Apache Project
I have an Django project that runs on Apache. With Javascript and Python i make request on diffrent sites. I always get following error: Access to XMLHttpRequest at 'site' from origin 'site2' has been blocked I already tried diffrent things. I installed django-cors-headers and edited my files: Settings.py: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'webpack_loader', 'corsheaders', 'projects', 'viewer', 'api_manager', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] In my HTML i added following to the form: <form class="d-flex flex-column" id="loginForm"> {% csrf_token %} </form> With the following method i was able to get a CSRF Token: static getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } And the call which needs CORS i already tried to add the correct Headers: xhr.addEventListener('readystatechange', function () { if (this.readyState === 4) { if (this.status != 200) { console.log("Error", this.statusText); } } … -
I need help using django_cron
I am currently working with HDFS, Apache Livy and Django, the goal of this is to send a request to get some code running which is stored in HDFS and which calls Livy to create Batches. For now, everything is working, I have a basic wordcount stored in HDFS, with a .txt file, and on a htlm page I just have a simple button to click on to launch the whole process. I succeed in creating the wordcount result, and my next step is to get informations from Livy, for instance the ID of the sessions (or batches) currently starting/running/dead/success some sort of callback, but I need the it to self actualize so i can know what states are every sessions in. To do so, I thought I could use Django-cron, therefore I can't manage to set it correctly. I have no errors but nothing more is happening. Could anybody help me to understand what I'm missing ? Currently working on Centos7 but I'm using a conda environment in python 3.6, with django latest release, so are livy and HDFS (latest release) Here are my current files : livy.html {% load static %} <html> <body> <div id="div1"> {{result.sessions}} </div> <form … -
How do i add this feature to my Django project?
I'm creating a social media platform with Django, and so far i have it that users can sign up and sign in, however i want to make it so that when a user is online, it will pop up to all other users that this user is online. Does anyone have any tips on how i'd go about this? Thanks. -
Django bulk update with data two tables over
I want to bulk update a table with data two tables over. A solution has been given for the simpler case mentioned in the documentation of: Entry.objects.update(headline=F('blog__name')) For that solution, see https://stackoverflow.com/a/50561753/1092940 Expanding from the example, imagine that Entry has a Foreign Key reference to Blog via a field named blog, and that Blog has a Foreign Key reference to User via a field named author. I want the equivalent of: Entry.objects.update(author_name=F('blog__author__username')) As in the prior solution, the solution is expected to employ SubQuery and OuterRef. The reason I ask here is because I lack confidence where this problem starts to employ multiple OuterRefs, and confusion arises about which outer ref it refers to. -
Creating an installable Django app with a 3rd party dependency
I am in the process of creating an installable Django app on pypi which can be added to INSTALLED_APPS. The app works correctly up to this point. The problem now is that I wish to use Django Rest Framework within my app. Does this mean that users will have to add my app as well as Django Rest Framework to their INSTALLED_APPS when installing my app? Is there a way to simply add my app to INSTALLED_APPS without the user being aware of or needing to worry about anything else. They don't need to know that I use Django Rest Framework under the hood? Django Rest Framework will have been installed when the user pip installs my package. -
stuck on : "System check identified 1 issue (0 silenced)." django app with mysql DB
setup a django opensource project fromhere as a docker container with sql db and everything build fine. until the final stage,the server won't go up. Dockerfile: # Preparation RUN apt-get update # Install server dependencies RUN apt-get install -y curl git git-core python-virtualenv gcc python-pip python-dev libjpeg-turbo8 libjpeg-turbo8-dev zlib1g-dev libldap2-dev libsasl2-dev swig libxslt-dev automake autoconf libtool libffi-dev libcairo2-dev libssl-dev RUN pip install virtualenv --upgrade #RUN apt install libjpeg8-dev zlib1g-dev -y libcairo2 RUN pip install pillow # Install database Run apt-get install -y libmariadbclient-dev zlib1g-dev libssl-dev # Install main dependencies Run apt-get install -y libffi-dev libxslt-dev libsasl2-dev libldap2-dev Run apt-get install -y libmariadbclient-dev zlib1g-dev python-dev libssl-dev python-virtualenv # Install other useful tools RUN apt-get install -y git vim sudo curl unzip RUN apt-get install -y sqlite3 # Cleaning RUN apt-get clean RUN apt-get purge ADD settings_local.py /root/settings_local.py # Install the backend RUN mkdir ~/badgr \ && cd ~/badgr \ && git clone https://github.com/concentricsky/badgr-server.git code \ && cd code \ && pip install -r requirements.txt \ && cp /root/settings_local.py apps/mainsite/ EXPOSE 8000 docker-compose.yml: version: '3' services: db: image: mysql:5.7 environment: - MYSQL_DATABASE=libraries - MYSQL_ROOT_PASSWORD=root - MYSQL_PASSWORD=root ports: - '3306:3306' volumes: - /var/lib/mysql webapp: build: . volumes: - .:/code links: - db ports: … -
how to separate between cards using bootstrap4
i have a template that display list of data stored from the database as a cards using bootstrap 4. the problem is that it display cards stacked above each other this is the problem list.html {% block body %} <div class="container"> <div class="row"> {% for obj in object_list %} <div class="col-md-4 p-2"> <div class="card bg-light text-right"> <div class="card-header"> <h2>hdhdh: {{ obj.suspect_name}} </h2> </div> <div class="card-body"> <h4 class="card-title"> fna :{{obj.suspect_father_name}}</h4> <h6 class="card-subtitle mb-2">mna :{{obj.suspect_mother_name}}</h6> <p class="card-text">{{obj.summary}}</p> <a href={{obj.get_absolute_url}} class="btn btn-danger">details</a> <a href="{% url 'update' obj.pk %}" class="btn btn-danger">edit</a> {%include 'blog/delete.html' %} <a href="{% url 'delete' obj.pk %}" class=" btn btn-danger confirm-delete" title="Delete" data-toggle="modal" data-target="#confirmDeleteModal" id="deleteButton{{obj.id}}">delete</a> </div> </div> </div> {% endfor %} </div> -
Left Join on multiple columns Django model ORM foreign key
I am trying to understand the Django ORM. I have 3 models that I am trying to join. class User(models.Model): id = models.IntegerField(primary_key=True) gender = models.CharField(max_length=25) class Movie(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=300) genre = models.CharField(max_length=300) class Recommendation(models.Model): id = models.IntegerField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) rec1 = models.IntegerField() rec2 = models.IntegerField() Now in my Recommendation I have 2 fields that are recommendations (rec1 and rec2) and correspond to Movie.id. I want to join these models to be able to show the movie.title and movie.genre for each recommendation (for each user, with their user information). I tried using two Foreign Keys, but am wondering if I fully understand that concept. In SQL I would use a LEFT JOIN on rec1 = Movie.id and rec2 = Movie.id, but I don't understand how to implement this in the Django ORM. Expected outcome User 1, gender 'F': recommendations 'Lion King', 'Batman' -
How to update ModelAdmin variable on every page refresh?
I have to fetch some data from external API and display it as columns in django admin page. I tried running code as assigning to a class-level variable but it only fetched data at the start of django server and it doesn't work as a function-level call, because somehow requests library freezes django here. So both of these examples won't work for me: class NewModelAdmin(admin.ModelAdmin): variable = requests.get(...) # it's executing only once class NewModelAdmin(admin.ModelAdmin): def some_column(self, obj): variable = requests.get(...) # it's freezing the app ... some_column.short_description = 'Some Column' some_column.admin_order_field = 'some_column' -
Custom admin to filter user transactions
How to create user report for multiple users in the Django Admin? I have an app which filters the transactions from the user itself. But as the administrator, I also want to see the transactions for all of my users. How can I do that in the Django-admin? Do I need to custom the admin.py file? or make another custom views for the admin itself? The flow will look like this: +-----------------+ +-----------------+ | User 1 +--------->+ List trx user 1 | +-----------------+ +-----------------+ | User 2 +--------->+ List trx user 2 | +-----------------+ +-----------------+ | User 3 +--------->+ List trx user 3 | +-----------------+ +-----------------+ How can I achieve it? here's my views.py @login_required() def ReportView(request): if request.is_ajax(): endDate = None startDate = request.GET.get('startDate') if request.GET.get('endDate') == '' or request.GET.get('endDate') is None : endDateConverter = datetime.today() else: endDate = request.GET.get('endDate') endDateConverter = datetime.strptime(endDate, "%Y-%m-%d").date() startDateConverter = datetime.strptime(startDate, "%Y-%m-%d").date() from_user = DaftarTransaksi.objects.filter(user_id=request.user.id, created__date__gte=startDateConverter, created__date__lte = endDateConverter) daftar_barang = ListProductTransaksi.objects.filter(transaksi_id__in=from_user) return render(request, 'report_details.html', {'daftar_barang': daftar_barang, 'num': startDateConverter}) from_user = DaftarTransaksi.objects.filter(user_id=request.user.id) daftar_barang = ListProductTransaksi.objects.filter(transaksi_id__in=from_user) context = { 'daftar_barang': daftar_barang, 'from_user': from_user, } return render(request, 'report.html', context) And this is my admin.py from django.contrib import admin from home.models import DaftarBarang, DaftarTransaksi, ListProductTransaksi admin.site.site_header … -
Auto insert the logged user in a Foreign Key
I'm creating an API for something like 9gag project that I'm doing, and upon uploading a post the logged user to be auto inserted in the created_by field that I have in my Post model I've tried ton of things, from the Django doc's -- https://docs.djangoproject.com/en/2.2/topics/class-based-views/generic-editing/#models-and-request-user , tried overriding the save_model method in the admin.py but nothing seems to work. models.py class Post(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, blank=True) title = models.CharField(max_length=200) tag = models.CharField(max_length=20, choices=TAGS) uploaded = models.DateTimeField(auto_now=True) likes = models.IntegerField(default=0, unique=False, blank=True, editable=False) image = models.ImageField(upload_to='images', blank=False) views.py class PostCreated(LoginRequiredMixin, CreateView): model = Post fields = ['id'] def form_valid(self, form): form.created_by = self.request.user.pk return super().form_valid(form) and when I upload something i always get "created_by": null -
Use ManyToMany field in add object raise needs to have a value for field "id" before this many-to-many relationship can be used
I have two models : Exam and Question. Each question has point that automatically calculate in each exam. So this is my files: #Models.py class Exam(models.Model): questions = models.ManyToManyField(Question) title = models.CharField() class Question(models.Model): title = models.CharField() answer = models.TextField() points = models.PositiveSmallIntegerField() #Forms.py class ExamForm(ModelForm): class Meta: model = Exam fields = '__all__' #Views.py if form.is_valid(): new_exam = form.save(commit=False) # Some modify goes here. new_exam.save() form.save_m2m() return redirect('view_exam') I did customize save() method of Exam model to this: def save(self, *args, **kwargs): self.point = 0 for question in self.questions: self.point += question.point super(Exam, self).save(*args, **kwargs) But I got this error: "<Exam: NewObject>" needs to have a value for field "id" before this many-to-many relationship can be used. How can I do this without raising any error?