Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django adding related object to instance of a parent
RoR refugee, learning Django here. I have an application with related models, Project and Workstream. I need to create new Workstream objects related to a Project (Project can have many workstreams). I have the logic and relations for this working fine, but when I try to create a method in the Project class to add a workstream to a Project instance and provide default values, I cannot get it to work. I have the function, but get an attribute error 'Manager' object has no attribute 'add'. When I research managers, I can find no references involving functions adding to a model, only involving limiting querysets. I suspect I am not doing things The Django Way in my approach. Wrote classes and functions, got errors, researched those, found nothing useful. class Project(models.Model): STATUS_CHOICES = ( ('NS', 'Not Started'), ('IP', 'In Process'), ('PR', 'Pending Review'), ('CP', 'Complete'), ) project_id = models.AutoField(primary_key=True) client_id = models.ForeignKey('clients.Client', on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=True) status = models.CharField(max_length=2, choices=STATUS_CHOICES) def __str__(self): # Return the name of the Project. return self.name @classmethod def add_workstream(self, ws_name='New Workstream', ws_desc='TBD'): """Add a workstream. Include optional arguments for name, description and status. """ from workstreams.models import Workstream new_ws … -
Heroku and Django : error "Couldn't find that app" from terminal/CLI
I am employing my Django website into Heroku. I followed: a) heroku login b) heroku create Which produces: Creating app... done, ⬢ enigmatic-ridge-36610 https://enigmatic-ridge-36610.herokuapp.com/ | https://git.heroku.com/enigmatic-ridge-36610.git c) heroku addons:create heroku-postgresql:hobby-dev Which produces: Creating heroku-postgresql:hobby-dev on ⬢ morning-gorge-61422... ! ▸ Couldn't find that app. I tried this guide: "Couldn't find that app." when running heroku commands in console But it did not work -
Dependency injection in django Views
I want to use dependency injection for my django project. For that I'm trying pinject package. Like in ASP.NET, all the dependencies are given in the constructor, and that's very nice because it's easy to test. I would also like to archive something similar in my django project. I have a simple View: class MySimpleView(View): def __init__(self, dependency1, dependency2, **kwargs): super().__init__(**kwargs) ... A place where I define the bindings # di.py class AppBindingSpec(pinject.BindingSpec): def configure(self, bind): # do the bindings here obj_graph = pinject.new_object_graph(binding_specs=[AppBindingSpec()]) And I expected to use it like this. # urls.py urlpatterns = [ path('path/to/my/view', obj_graph.provide(MySimpleView).as_view()), ] But unfortunately, django does not allow the .as_view() to be called from an instance. Is there any simple way to inject the dependencies into my view so I can easily mock and test? -
How to transfer some variable to form?
I want to make a custom form field validation to check if entered string is an email of user variable. Smth like this: class FullEmailOrPhoneForm(forms.Form): entered_string = forms.CharField() class Meta: model = User fields = ('entered_string',) def clean_entered_string(self): email = self.cleaned_data['entered_string'] if email == user.email: ans = email else: raise ValidationError('Incorrect email') return ans My view: def reset_password_with_username(request, user): if request.method == 'POST': form = FullEmailOrPhoneForm(request.POST) if form.is_valid(): pass else: form = FullEmailOrPhoneForm() return render(request, 'registration/password_reset_with_username.html') So how can I transfer user variable from view to form validation function? -
Django model is inheriting all super model Fields, except for IntegerField
I'm having a weird issue, I have a models' hierarchy, an abstract User class: class User(AbstractBaseUser): user_name = models.CharField(max_length=32, unique=True) email = models.EmailField(max_length=255, unique=True, null=True) phone = PhoneNumberField() access_token = models.CharField(max_length=255, unique=True, null=True) notifications_token = models.CharField(max_length=255, unique=True, null=True) photo = models.ImageField(null=True) person_in_contact = models.CharField(max_length=32, null=True) active = models.BooleanField(default=False) confirmedEmail = models.BooleanField(default=False) confirmedPhone = models.BooleanField(default=False) completedProfile = models.BooleanField(default=False) visible = models.BooleanField(default=True) @property def is_active(self): return self.active # def __str__(self): # return "Client : " + self.user_name + " Email:" + self.email def get_email(self): return self.email USERNAME_FIELD = 'user_name' REQUIRED_FIELDS = ['user_name', 'phone', 'password'] class Meta: abstract = True then a person class and a company (no issue with this one) class that inherit from this one: class Person(User): GENDER = (('F', 'FEMALE'), ('M', 'MALE')) name = models.CharField(max_length=50, null=True) surname = models.CharField(max_length=50, null=True) adress = models.CharField(max_length=255, null=True) birth_date = models.DateField(null=True) gender = models.CharField(max_length=1, choices=GENDER, null=True) age = models.IntegerField(null=True) def age(self): today = date.today() return today.year - self.birth_date.year # def __str__(self): # return super().__str__() + " Name : " + self.name class Meta: abstract = True as you can see, the only field that's IntegerField() is the age field. now i have a Traveller and a Driver classes that inherit from the person … -
Django is it safe csrf middleware token shows up in url?
when making GET requests, I've noticed that my csrf tokens gets appended to my url. Is this safe? -
dictsort gives no resuts
I use a queryset fields in 2 places on my view. One is ordered by another field, the other is ordered by facet. I'd like to order the dataset in 2 ways on the page, rather than passing the queryset twice. I am trying to use dictsort to do this as is outlined here and a few other questions. I have this in my code: {% for field in fields|dictsort:"facet_order" %} field.facet_order {% endfor %} But i see nothing rendered. The loop works fine without the dictsort, and as a sanity check i have run the below with no problem: {% for field in fields %} field.facet_order {% endfor %} It yields: None None None None 1 0 None ... My code looks to me like it strongly resembles django's documentation example below: {% for book in books|dictsort:"author.age" %} * {{ book.title }} ({{ book.author.name }}) {% endfor %} What am i doing wrong here? -
How to log all Django serializer validation errors?
Similar to this, I would like to get log lines on the server when serializer validation fails. What is the best approach to add logging to Serializers? -
TypeError: encoding without a string argument for razorpay webhook secret verification error
I am trying verify if the webhook came from Razorpay but getting following error. TypeError: encoding without a string argument Here is the code: webhook_secret = MY_WEBHOOK_SECRET signature = request.headers['X-Razorpay-Signature'] jsondata = json.loads(request.body) client = razorpay.Client(auth=(MY_KEY, MY_SIGNATURE)) verify = client.utility.verify_webhook_signature(jsondata, signature, webhook_secret) I'm getting error in the last line. Can someone help me with this? Thanks! -
Difference in version of python in docker compose services
I'm trying to make a docker image of my website made with django and channels. I have 4 services: redis, http server, channel worker and daphne server. However, I have an error on the daphne server. I've found that between service, there were different python version while the docker fiel is the same This is my docker-compose.yaml : version: '3' services: redis: image: redis command: redis-server ports: - '6379:6379' web: build: ./soundover command: bash -c "python --version && python manage.py runserver 0.0.0.0:8000" volumes: - ./soundover:/soundover ports: - "8000:8000" worker_channels: build: ./soundover command: bash -c "python --version && python manage.py runworker websocket" volumes: - ./soundover:/soundover links: - redis channels: build: ./soundover command: bash -c "python --version && daphne -b 0.0.0.0 -p 8001 soundover.asgi:application" volumes: - ./soundover:/soundover ports: - "8001:8001" links: - redis And the Dockerfile: FROM python:3.6 ENV WEBAPP_DIR=/soundover RUN mkdir $WEBAPP_DIR WORKDIR $WEBAPP_DIR ADD requirements.txt $WEBAPP_DIR/ ADD manage.py $WEBAPP_DIR/ RUN pip install -r requirements.txt RUN python -m pip install git+https://github.com/django/channels.git --upgrade I had the versions displayed and this is the result : https://prnt.sc/oq4cm5 I expect the output 3.6.9 for all services. Is there a way to force the use of python 3.6 for the service channels(with daphne server) ? -
Django Heroku - ModuleNotFoundError: No module named 'django_heroku'
I am deploying on heroku a website but I am experiencing some issue. My project is called mysite-project. I did the following: 1) Create a Procfile containing: web: gunicorn mysite-project.wsgi at the base root of my project (same level where manage.py is). 2) app/settings.py import django_heroku at the top django_heroku.settings(locals()) at the bottom of settings.py 3) pip install gunicorn pip install django-heroku pip freeze > requirements.txt 4) If I run python manage.py runserver I get: ModuleNotFoundError: No module named 'django_heroku' -
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); } } …