Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error occurred while reading WSGI handler: Error
when I want to open the django project, I encounter such an error. My django projects are live on the same server, but I encountered such an error on the last site I opened. web.config: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python39\python.exe|c:\python39\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <tracing> <traceFailedRequests> <clear /> </traceFailedRequests> </tracing> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="umy.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="umy.settings" /> <add key="PYTHONPATH" value="C:\Inetpub\vhosts\domain.com\httpdocs" /> </appSettings> <system.web> <compilation tempDirectory="C:\Inetpub\vhosts\domain.com\tmp" /> </system.web> </configuration> The error I get is about; Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\python39\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python39\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python39\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "umy.wsgi.application" could not be imported: Traceback (most recent call last): File "c:\python39\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File ".\umy\wsgi.py", line 9, in <module> application = get_wsgi_application() File "c:\python39\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "c:\python39\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__ self.load_middleware() File "c:\python39\lib\site-packages\django\core\handlers\base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "c:\python39\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "c:\python39\lib\importlib\__init__.py", line 127, in import_module return … -
Django-Filter: Search within an ArrayField with an Array?
I have an all_positions datapoint that uses an arrayField. So some example data looks like: all_positions: ["C", "1B"], all_positions: ["RP", "CP"], all_positions: ["CP"], I'd like to be able to make a request similar to /api/player-profiles/?all_positions=RP,CP and return the second and third examples. Essentially, I want to return all players that have ANY of the positions passed into the URL in their all_positions data. I've read about overlap, but not sure how I would integrate that into my django-rest filters. Here is what the filter currently looks like: class PlayerProfileFilter(django_filters.FilterSet): all_positions = CharInFilter(field_name='all_positions', lookup_expr='contains') -
Can't understand how django_q works
I'm having problem understanding how to use django_q to send async tasks. My goal is to reset some values in all instances of one model once per day. How do I tell django_q to go through all instances of my model and reset it fields to 0? For some more context my model is UserProfile witch has fields like calores_eaten, water_drinked, sugar_eaten etc witch stores each user daily intake of these elements. My tasks.py looks like this: from datetime import timedelta from django.utils import timezone from django_q.tasks import async_task, schedule from django_q.models import Schedule from .models import UserProfile def reset_daily_intakes(UserProfile): async_task() schedule(next_run=timezone.now() + timedelta(days=1)) But that's where Im stuck, I don't understand how to define async_task() and how to tell this function to go through all instances of UserProfile -
Docker/ Django/ Postgres - could not translate host name "db" to address: Name or service not known
Few days ago I asked a question about a Postgres error. I followed your suggestions and they helped a bit but in addition to not solving my problem some new problems arose. I have a django-postgres app which works locally with no problems. When I try to build a docker image it builds but when I try to set up the container I have the following error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known I'll show you my Dockerfile: # Origin image FROM python:3.8 RUN apt-get update # Define directory RUN mkdir /project WORKDIR /project # Install requirements RUN apt-get install -y vim RUN python -m pip install --upgrade pip COPY requirements.txt /project/ RUN pip install -r requirements.txt COPY . /project/ # Expose some ports EXPOSE 22 5432 8080 8009 8000 # default command CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And here is my docker-compose file: version: "3.3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data ports: - "5432:5432" environment: - POSTGRES_NAME=plataforma - POSTGRES_USER=admin - POSTGRES_PASSWORD=administrador web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=plataforma - POSTGRES_USER=admin - POSTGRES_PASSWORD=administrador depends_on: - db env_file: - ./plataforma/.env On settings.py … -
Djano heroku deployment issue: django
First time here on stackowerflow, hoping somebody will be able to help me :) I have tried several ways to deploy site, following several tutorials and had solved most of errors I got except one: After pushing django project via git to heroku, I have error with app crashing (https://vocnjak.herokuapp.com/). Logs give error H10 and in logs: from django.core.wsgi import get_wsgi_application, ModuleNotFoundError: No module named 'django' Here are logs: Logs Also when I run heroku run python manage.py migrate I get: ImportError: Couldn&apos;t import Django. Are you sure it&apos;s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have installed Django and all dependencies in virtual environment, and Django site is working when run locally (as python manage.py runserver) and that is bugging me. Procfile: web: gunicorn vocnjak.wsgi --log-file - requierments.txt (with everything installed): asgiref==3.5.0 backports.zoneinfo==0.2.1 dj-database-url==0.5.0 Django==4.0.1 django-crispy-forms==1.14.0 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 whitenoise==5.3.0 Thanks! -
Object (1) occurs when adding new details in admin panel
When i add new data, it will come up with object (1). If i go in the table with the many to one relation, it will not show the ID and instead show the "object (1). I have tried changing the field sets however this does not work. When i go to make a "UserAdmin" it will treat it like it a user being added. Admin.py from lib2to3.pgen2.token import OP from statistics import mode from attr import field from .forms import createUserForm from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account, sni, Question, Option class AccountAdmin(UserAdmin): list_display = ('userID', 'is_staff', 'is_admin') search_fields = ['userID'] readonly_fields = () add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('userID','name','password1','password2','dateOfBirth','homeAddress', 'is_staff', 'is_admin', 'sni'), }), ) filter_horizontal = () list_filter = () fieldsets = () ordering = ('userID',) admin.site.register(Account, AccountAdmin) admin.site.register(sni) admin.site.register(Question) admin.site.register(Option) Model.py from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True … -
Django multiple password forms
I'm trying to clone linkr.ee just for learning A page looks like this: -Each user User has a page -On this page one user can have multiple links -A link can have a password field to unlock the link if a user setted the password to True/False I created the model here: class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) url = models.CharField(max_length=255) creator_adress = models.GenericIPAddressField(null=True) password_secured = models.BooleanField(default=False) password = models.CharField(max_length=100, blank=True, null=True) So if password_secured is checked (True/False), the link will have the password field aswell. My Problem: I'm having issues with giving each link one the page the which is password secured a form. If one link has password_secured True (and password) -> Form needed for each link which has password -> if password correct (form valid) -> password_secured False -> link unlocked The Template: #here just a for loop to display every object of the specific user into the html template <a {% if i.password_secured == False %} href="{{i.url}}{% endif %}"></a> #for loop end Simple Template meaning: If password secured False -> put the href in the Link(Button) If password secured True -> Password form must be correct -> set secured … -
Can you configure Supervisor + multiple Daphne processes w/ ssl endpoints
I'm trying to configure the following setup: Django w/ channels Multiple Daphne processes as the ASGI server, with ssl endpoints Supervisor managing Daphne No other server (nginx, etc.) in front of Daphne Without using ssl, I can bind all the Daphne processes to a single file descriptor and Supervisor will expose this as single endpoint. This doesn't seem possible when using ssl endpoints unless I'm missing something. My supervisord.conf looks like this: [fcgi-program:daphne] command=/usr/local/bin/daphne -e ssl:port=8443:privateKey=/project/ssl/key.pem:certKey=/project/ssl/cert.pem -u /tmp/daphne%(process_num)d.sock --fd 0 myapp.asgi:application directory=/project/src numprocs=4 process_name=daphne%(process_num)d socket=tcp://0.0.0.0:8000 When I bring up the server, however, it only listens to the first process, and I get this error for each of the n-1 additional processes that are spawned: DEBG 'daphne1' stderr output: INFO HTTPFactory starting on 8000 INFO Starting factory <daphne.http_protocol.HTTPFactory object at 0xffffa448db40> INFO Listening on TCP address 0.0.0.0:8000 INFO Configuring endpoint ssl:port=8443:certKey=/project/ssl/cert.pem:privateKey=/project/ssl/key.pem CRITICAL Listen failure: Couldn't listen on any:8443: [Errno 98] Address already in use. INFO Configuring endpoint unix:/run/daphne1.sock INFO HTTPFactory starting on '/run/daphne1.sock' So basically, the processes start fine, but Daphne is itself grabbing the first tcp socket at 8443, and then nothing else can bind to it. Is there anyway around this without running Daphne w/o ssl and putting a … -
Django + Gunicorn + Nginx. Как закрыть 8000 порт для посетителей сайта
Gunicorn поднимает сервер на 0.0.0.0:8000. Сайт работает нормально, но есть возможность зайти на www.сайт:8000 (по 8000 порту). Я хочу убрать у посетителей эту возможность. Не пойму где искать решение проблемы? Настройки NGinx, iptables или firewalld? enter image description here CentOS7 -
Redis and channels with Windows
I'm trying to get a var to my consumers.py to send data to the client in real time as a function does API calls and returns that to the browser. I know channels needs Redis to function, but why? Why can we not just pass a list as it's built to the consumers class or any variable for that matter? From another answer: to store the necessary information required for different instances of consumers to communicate with one another. But what if I only will use one websocket connection, and only one user is allowed to be logged in at a time? This will be locally hosted only and the function is outside of consumers.py that returns the data so subscribing to groups may be where I need these. Am I missing something or is redis / memurai a must here? I just can't help but to feel there's an easier way. -
Django Custom Manager Method that returns object when asked by value
I'm trying to make a method for a model "Clase" that returns a "Clase" whose "codigo" value matches an argument. So far i have this: class CodigoClaseManager(models.Manager): """ Custom manager that enables geting a Clase by codigo """ def get_by_code(self, code): return super(CodigoClaseManager,self).get_query_set().filter(codigo=code) class Clase(models.Model): nombre = models.CharField(max_length=100) codigo = models.CharField(max_length=100) byCode = CodigoClaseManager def __str__(self): return self.nombre class Meta: managed = True db_table = 'clases' My problem is that, when i try to call this get_by_value method, it always tells me that the argument "self" is missing. >>> Clase.byCode.get_by_code(code="1234") Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: get_by_code() missing 1 required positional argument: 'self' Am I taking a wrong aproach or is it an error in my code? I have recently started learning django and would very much apreciate help, thanks. -
local variable 'comment_form' referenced before assignment in django
I created an app where user can login and post a contents he wants: and now i decided to add comment section to each post user did in the app, i followed the tutorial in djangocentral website, but it's not working after i added everything they did into my app, when i click on [Read more] it's throw me an error in the browser: local variable 'comment_form' referenced before assignment, if i deleted the: 'comment_form' inside the context of my viewPhoto view its shows nothing in viewPhoto template. How can i do this ? the model: class Comment(models.Model): post = models.ForeignKey(Photo, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) the admin.py: from django.contrib import admin from .models import Photo, Category, Comment # Register your models here. admin.site.register(Category) admin.site.register(Photo) @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_cooments'] def approve_comment(self, request, queryset): queryset.update(active=True) the form.py: from dataclasses import fields from pyexpat import model from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model … -
How can I join three Django Models to return a queryset?
I want to create a queryset that references three related models, and allows me to filter. The SQL might look like this: SELECT th.id, th.customer, ft.filename, fva.path FROM TransactionHistory th LEFT JOIN FileTrack ft ON th.InboundFileTrackID = ft.id LEFT JOIN FileViewArchive fva ON fva.FileTrackId = ft.id WHERE th.customer = 'ACME, Inc.' -- AND ft.filename like '%storage%' --currently don't need to do this, but seeing placeholder logic would be nice I have three models in Django, shown below. It's a bit tricky, because the TransactionHistory model has two foreign keys to the same model (FileTrack). And FileViewArchive has a foreign key to FileTrack. class FileTrack(models.Model): id = models.BigIntegerField(db_column="id", primary_key=True) filename = models.CharField(db_column="filename", max_length=128) class Meta: managed = False db_table = "FileTrack" class TransactionHistory(models.Model): id = models.BigIntegerField(db_column="id", primary_key=True) customer = models.CharField(db_column="Customer", max_length=128) inbound_file_track = models.ForeignKey( FileTrack, db_column="InboundFileTrackId", related_name="inbound_file_track_id", on_delete=models.DO_NOTHING, null=True, ) outbound_file_track = models.ForeignKey( FileTrack, db_column="OutboundFileTrackId", related_name="outbound_file_track_id", on_delete=models.DO_NOTHING, null=True, ) class Meta: managed = False db_table = "TransactionHistory" class FileViewArchive(models.Model): id = models.BigIntegerField(db_column="id", primary_key=True) file_track = models.ForeignKey( FileTrack, db_column="FileTrackId", related_name="file_track_id", on_delete=models.DO_NOTHING, null=True, ) path = models.CharField(db_column="Path", max_length=256) class Meta: managed = False db_table = "FileViewArchive" One thing I tried: qs1 = TransactionHistory.objects.select_related('inbound_file_track').filter(customer='ACME, Inc.') qs2 = FileViewArchive.objects.select_related('file_track').all() qs = qs1 & qs2 # … -
Finding out the difference of months to int in django
Im trying to get the difference of months in a project from it's start date to it's end date, and compute it to the monthly updates to show the percentage of a project progress, but my current code doesn't give value to compute. If I remove the .month it says unsupported operand type(s) for /: 'int' and 'datetime.timedelta' Models.py class Projects(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=255) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, limit_choices_to={'is_project_manager' : True}) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) project_pic=models.ImageField(upload_to='static/website/project-images') project_start_date=models.DateField(null=True) project_end_date=models.DateField(null=True) project_description=models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) objects=models.Manager() class Meta: verbose_name_plural = 'Project' def __str__(self): return f'{self.project_name}' class MonthlyProjectStatus(models.Model): id=models.AutoField(primary_key=True) project_name=models.ForeignKey(Projects,on_delete=models.CASCADE) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, null=True) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) attachments=models.FileField(upload_to='static/website/files', null=True) project_update=models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) class Meta: verbose_name_plural = 'Monthly Status' def __str__(self): return f'{self.project_name}' Views.py def project_details(request, pk): projects = Projects.objects.get(id=pk) employed = Employee.objects.filter(project_site=projects) invents = Project_Inventory.objects.filter(project_site=projects) months = MonthlyProjectStatus.objects.filter(project_name=projects).count() dt = projects.project_start_date.month - projects.project_end_date.month sums = (months)/(dt) * 100 context = { 'projects' : projects, 'employed' : employed, 'invents' : invents, 'dt' : dt, 'months' : months, 'sums' : sums, } template_name ='project-admin/project-details.html' return render(request, template_name, context) -
Can't get calendar api events from user
So I can currently log in with my social user account but can't seem to access the calendar api events of that user. Flow: login->main page->calendar(localhost:8000/login-> localhost:8000->localhost:8000/calendar) @login_required def calendar(request): context={} results = get_user_events(request) context['results'] = results context['nmenu'] = 'calendar' editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm if request.method=="POST": if 'editProfileForm' in request.POST: editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['is_post'] = False return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) return render(request, 'home.html', context) calendar.py from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError import os def get_user_events(request): creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) … -
Login with TokenAuthentication and AbstractBaseUser errors
my user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) national_code = models.CharField( _('national code'), max_length=10, blank=True, null=True ) phone_number = models.CharField( _('phone number'), max_length=13, blank=True, null=True ) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff'), default=False) avatar = models.ImageField( _('avatar'), upload_to='avatars', default='avatars/defaults.png' ) age = models.PositiveSmallIntegerField(_('age'), blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') @property def get_full_name(self): full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() @property def get_short_name(self): return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): send_mail(subject, message, from_email, [self.email], **kwargs) user model manager: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) user serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = … -
Django change Boolean after POST
I'm trying to clone linkr.ee just for learning django A page looks like this: Each user User has a page On this page one user can have multiple links A link can have a password field to unlock the link if a user setted the password to True/False I created the model here: class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) url = models.CharField(max_length=255) creator_adress = models.GenericIPAddressField(null=True) password_secured = models.BooleanField(default=False) password = models.CharField(max_length=100, blank=True, null=True) So if password_secured is checked (True/False), the link will have the password field aswell. My Problem: I'm having issues with giving each link one the page the which is password secured a form. If one link has password_secured True (and password) -> Form needed for each link which has password -> if password correct (form valid) -> password_secured False -> link unlocked The Template: #here just a for loop to display every object of the specific user into the html template <a {% if i.password_secured == False %} href="{{i.url}}{% endif %}"></a> #for loop end Simple Template meaning: If password secured False -> put the href in the Link(Button) If password secured True -> Password form must be correct -> set … -
Placement input text no showing
When I add another CRSF Token, it will not show the placeholder texts. Without this second token. It will not allow for me to save the form. I do not know how to make this last placeholder visible again when adding the token. Any Help would be appreciated. If any other files are needed such as the views class. I can provide this however I believe its to do with something in the html document. <!DOCTYPE html> <html> <head> <title>Register</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } … -
can't install modified pafy version in heroku django
I made a django app with pafy (I used the modified version, because the official one gives errors check this https://github.com/mps-youtube/pafy/pull/305) and when I push it to heroku I get errors here's the requirements.txt file # asgiref @ file:///tmp/build/80754af9/asgiref_1625643473416/work beautifulsoup4==4.10.0 certifi==2021.10.8 dj-database-url==0.5.0 # Django @ file:///tmp/build/80754af9/django_1625585912945/work django-bootstrap-datepicker-plus==4.0.0 django-bootstrap4==21.2 django-heroku==0.3.1 Faker==11.3.0 gunicorn==20.1.0 # psycopg2 @ file:///tmp/build/80754af9/psycopg2_1612298595717/work python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 soupsieve==2.3.1 # sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work text-unidecode==1.3 # typing-extensions @ file:///tmp/build/80754af9/typing_extensions_1631814937681/work whitenoise==5.3.0 # pafy==0.5.5 # youtube_dl==2021.12.17 youtube-dl==2021.6.6 pafy -e git+git://github.com/Cupcakus/pafy.git@develop#egg=pafy I tried removing pafy, tried other versions but it doesn't solve it here's the log -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip Obtaining pafy from git+git://github.com/Cupcakus/pafy.git@develop#egg=pafy (from -r /tmp/build_9f9c42b0/requirements.txt (line 24)) Cloning git://github.com/Cupcakus/pafy.git (to revision develop) to /app/.heroku/src/pafy Running command git clone --filter=blob:none -q git://github.com/Cupcakus/pafy.git /app/.heroku/src/pafy Resolved git://github.com/Cupcakus/pafy.git to commit 45f0deb067bf7c420cdf83a0529fd5274c12de18 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] … -
Django stuck on Watching for file changes with StatReloader
So at first I tried opening up a site and it did work perfectly, then i modified the files to create an app and then after following a tutorial it got stuck on that message and the local host site went down, I've tried specifying the command to be on 8000 but it still would not open and i also tried opening up a new terminal but it was still stuck in that same message. Here are my files and terminal: terminal urls file Home html Lookup file views file -
Django media uploads to Amazon S3 and restricting access to certain users
I am creating a flutter application with Djano backend where users can create/join groups and upload files (pictures, videos etc) to the group. I set up AWS S3 storage to handle media file uploads. However, now I'm at a point where I want only members of a group in the app to be able to see those files/pictures and restrict access to those files/pictures where you are not a member of the group. right now My bucket settings is set to public and anyone that has a link to the URL can access/view that file in the browser. How would I implement if someone grabs a hold of that URL , they shouldn't be able to access the file by going to the link. essentially, some content like profile pictures can be public and anyone can access that but no one can just go to their browser and type in a URL for a certain file link and access it. How would I go about doing this? Are there any good tutorials that you can link me or documentation that discusses this? -
I cannot post data - Django
I am currently building a Django React app and I want the users to be able to create an instance of a model (listing) from the frontend. I was trying to build the backend, but when I try on Postman I get an error : "detail":"Method "POST" not allowed." My model : class Listing(models.Model): artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) slug = models.CharField(max_length=200, unique=True) title = models.CharField(max_length=150) photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', default='photos/default.jpg') description = models.TextField(blank=True) def __str__(self): return self.title My view : class CreateListingView(APIView): parser_classes = [MultiPartParser, FormParser] queryset = Listing.objects.all() serializer_class = ListingSerializer def post(self, request, format=None): print(request.data) serializer = ListingSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) else: return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) My app Urls : from django.urls import path from .views import ListingsView, ListingView, SearchView,CreateListingView app_name = 'listings' urlpatterns = [ path('', ListingsView.as_view(),name='listings'), path('search', SearchView.as_view(),name='listingssearc'), path('<slug>', ListingView.as_view(),name='listingsdetails'), path('create', CreateListingView.as_view(),name='listingscreate') ] My project urls : urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/accounts/', include('accounts.urls')), path('api/artists/', include('artists.urls')), path('api/listings/', include('listings.urls', namespace='listings')), path('api/contact/', include('contact.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] So what did I do wrong? I don't understand why I get a 405 error. Thanks for reading! -
Cannot assign "<django.contrib.auth.models.AnonymousUser object:
I've been trying to write a test using the following code: class ViewTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(first_name='tester', username='test1', password='123', email='testuser@something.com') def test_room_creation(self): c = Client() payload = {"titlePlanning": "Teste1","styleCards": "Fibonnaci","deck": ["1","2","3"]} c.login(username='test1',password='123') request = c.post('/room', payload, content_type='application/json') response = BeginRoom.as_view()(request) self.assertEqual(response.status_code, 200) print(request) the view that I'm testing needs the following data: class BeginRoom(APIView): permissions_classes = (IsAuthenticated,) def post(self, request, format=None): data= self.request.data user = request.user name = data['titlePlanning'].strip() styleCards = data['styleCards'] cards = data['deck'] This is the Model that the view access to do the POST: class PokerRoom(models.Model): status = models.CharField(max_length=1,choices=STATUS, verbose_name=_('status') name = models.CharField(max_length=200,verbose_name=_('name of the room')) styleCards = MultiSelectField(choices=CHOICES, default=FIBONACCI) user = models.ForeignKey(User, on_delete=DO_NOTHING) deck = models.ForeignKey(Pack, on_delete=models.CASCADE) active_story = models.OneToOneField('Story', on_delete=models.SET_NULL,verbose_name=_('active_storys'), related_name='active_in', null=True) My problem is that whenever I run my test I get the following error: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fbfb77ca3d0>": "PokerRoom.user" must be a "User" instance. I thought that I only needed to login with my user and after that it would be instantiated but its not working. Can someone help me? -
How to get only the last month's records present in the database, using queryset django?
I need to get only the objects of the last month present in the DB. I don't mean the last 30 days or the last calendar month, but the most recent month recorded in the database... I've seen that django has the latest() function that returns the most recent object in the table based on in the given field(s), however I want it to return multiple objects based on the given month. revisoes = Revisao.objects.filter(apicultor__in=apicultores).order_by('-data_registro') This is the queryset I'm using, only it returns all revisions for a given beekeeper. I need it to return only revisions based on the last month of the "data_registro" field -
Slugify and PIL images not working simultaneously inside Django Model Save method
models.py def rand_slug(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) class Product(models.Model): """ The Product table contining all product items. """ title = models.CharField( verbose_name=("title"), help_text=("Required"), max_length=255, ) image = models.ImageField( verbose_name=("image"), help_text=("Upload a product image"), upload_to="rental_equipments", default="default-equipment.jpg", ) description = models.TextField(verbose_name=("description"), help_text=("Add a detailed description"), blank=True) model = models.CharField(verbose_name=("Model"), max_length=25,null=True) serial_number = models.CharField(verbose_name=("Serial Number"),null=True, max_length=25) warrenty = models.DateField(verbose_name=("Warrenty Upto"),null=True, max_length=25) is_active = models.BooleanField( verbose_name=("Post Publically"), help_text=("---Remove tick mark and save for later"), default=True, ) slug = models.SlugField(max_length=255,unique=True) created_at = models.DateTimeField(("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(("Updated at"), auto_now=True) posted_user = models.ForeignKey(User, related_name="posted_by", on_delete=models.CASCADE,blank=True, null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img=img.resize((640,480)) img.save(self.image.path) if not self.slug: self.slug = slugify(rand_slug() + "-" + self.title) in my Save method, when I use image-resize without slugify function, it works perfectly, similarly slugify without image resize also works fine.. why do both work at the same time? please help!! this problem haunting me for hours!