Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm stack in, Object x is not JSON serializable
I need a help please, i'm stack, i'm getting this error: Object of type CustomUser is not JSON serializable My code : def sharedContact(self, connectedUser): contactList = [] contacts = ContactCenter.objects.filter(contact_source=connectedUser) | ContactCenter.objects.filter(shared_with=connectedUser) #pprint(vars(contacts)) for contact in contacts: #pprint(vars(contact)) users = CustomUser.objects.filter(id=contact.contact_source_id) | CustomUser.objects.filter(id=contact.shared_with_id) for user in users: with schema_context(str(user.username)): tenants = Contact.objects.filter(id=contact.contact) for tenant_contact in tenants: contactList.append(tenant_contact) return contactList -
django radio choice can't be display
I working on a survey app where users with admin roles can log in to the admin dashboard to create surveys and provide the survey link to the surveyor to take the survey. I am having trouble displaying the questioner and choices on the surveyor page. I trying to display the survey question choices but the radio choice can't be displayed. The questions can be displayed but the radio choice cannot be display. Not sure what I did wrong. Previously I had my model setup like what I have posted here. But then I had trouble displaying all the questioners, so I get assistance from stack over and I've changed my model but now I can't display my radio choices. class Survey(models.Model): title = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now) archive = models.CharField(max_length=200, default='') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) class Meta: abstract = True class ChoiceQuestion(Question): choice = models.CharField(max_length=100) def __str__(self): return self.choice class TextQuestion(Question): textbox = models.CharField(max_length=100) def __str__(self): return self.textbox class CheckQuestion(Question): checkbox = models.CharField(max_length=100) def __str__(self): return self.checkbox <div class = "jumbotron container centerdv header-top"> <h2>{{survey.title}}</h2> </div> <div class="d-flex flex-column"> <form method = "post" action =#> <input type = "hidden" name … -
Can't access an item in a dictionary that does in fact exist
I have two buttons on my page, each one in its own separate form. One of the buttons, "deleteImage", works perfectly fine. The other button, "search", won't work. This is my response.POST when search is pressed. request.POST <QueryDict: {'csrfmiddlewaretoken': ['randomtoken1234'], 'search': ['food', '']}> request.POST.get("search") is failing to work for some reason, I tried printing it as well and nothing prints out. -
Difficulty in installing shuup
guys it's my first time installing the shuup and able to do the migrations but when tried the following command to initialize shuup python manage.py shuup_init it throws the below error: Traceback (most recent call last): File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'shuup_init' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\jmdee\tep\manage.py", line 21, in <module> main() File "C:\Users\jmdee\tep\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 211, in fetch_command settings.INSTALLED_APPS File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\jmdee\tep\tep\settings.py", line 15, in <module> django.setup() File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\jmdee\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 66, in … -
How to do error handling for 401, 402, 403 in Django
Hi for my Django application I am trying to do error handling for all possible types of errors in which the Django documentation only shows how to deal with 404 and 500 errors by adding the following lines in the urls.py file as shown handler404 = 'store.views.handler404' handler500 = 'store.views.handler500' This ensures that the 404.html and 500.html templates are displayed to the user when such errors come up. But then for errors such as 401, 402, 403 can I similarly add?... handler401 = 'store.views.handler401' handler402 = 'store.views.handler402' handler403 = 'store.views.handler403' Even if this is available in Django, HOW CAN I TEST TO SEE IF IT WORKS. Any help is greatly appreciated. Thanks! -
Filtering doesn't work in conjunction with Search results Django
I have implemented a filter form in my web application. I have pagination tags implemented in the HTML, with the navigation buttons set up like: {% load pagination_tags %} {% block content%} <center> <h5> Search results for "{{search_query}}" </h5> </center> <br> <div class="col"> <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Filter</button> </form> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item {% if not prev_page_url %} disabled {% endif %}"> <a class="page-link" href="?{% url_replace request 'page' prev_page_url %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active" aria-current="page"> <a class="page-link" href="?{% url_replace request 'page' n %}">{{ n }} <span class="sr-only"></span> </a></li> {% elif n > page.number|add:-4 and n < page.number|add:4 %} <li class="page-item"> <a class="page-link" href="?{% url_replace request 'page' n %}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %} disabled {% endif %}"> <a class="page-link" href="?{% url_replace request 'page' next_page_url %}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> And the pagination_tags.py file looks like this: from django import template from urllib.parse import urlencode register = template.Library() @register.simple_tag def url_replace (request, field, value): dict_ = request.GET.copy() dict_[field] = value return dict_.urlencode() The pagination works … -
cant delete with keyword arguments '{'pk': ''}' from URL
I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button I'm trying to delete employee from db using the urk pk in the exemple from this button <a class="dropdown-item" href="{% url 'emsi:employee_delete' pk=employee.pk %}"> <i class="fa fa-trash text-danger fa-fw"></i>Delete</a> this is the urls.py from django.urls import path from . import views # Employee path('dashboard/employee/', views.Employee_All.as_view(), name='employee_all'), path('dashboard/employee/new/', views.Employee_New.as_view(), name='employee_new'), path('dashboard/employee/<int:pk>/view/', views.Employee_View.as_view(), name='employee_view'), path('dashboard/employee/<int:pk>/update/', views.Employee_Update.as_view(), name='employee_update'), path('dashboard/employee/<int:pk>/delete/', views.Employee_Delete.as_view(), name='employee_delete'), this the Views.py from django.shortcuts import render, redirect, resolve_url, reverse, get_object_or_404 from django.urls import reverse_lazy from django.contrib.auth import get_user_model from pip._vendor.requests import Response from .models import Employee, Department from django.contrib.auth.views import LoginView from django.contrib.auth import logout from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import FormView, CreateView, View, DetailView, TemplateView, ListView, UpdateView, DeleteView from .forms import RegistrationForm, LoginForm, EmployeeForm, DepartmentForm from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.utils import timezone from django.db.models import Q # Employee's Controller class Employee_New(LoginRequiredMixin, CreateView): model = Employee form_class = EmployeeForm template_name = 'emsi/employee/create.html' login_url = … -
Image is not saving in input tag
I am building a BlogApp and I am new in django and HTML. I am trying to make a custom upload button using <input type="file" > BUT when i use {{ form }} then it is working BUT when i use <input type="file" name="file" > then it doesn't upload the Image. models.py class G(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) class GImage(models.Model): gimage = models.ForeignKey(G,related_name='imagess',on_delete=models.CASCADE) file = models.ImageField(upload_to='images') **My image instance name is file. forms.py class GForm(forms.ModelForm): class Meta: model = GImage fields = ['file',] template.html When i try this :- <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> BUT When i try with input tag then it doesn't work. <form id="post_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <input type="file" name="file" > {% endfor %} <button type="submit" name='submit' class="btn btn-secondary btn-lg post"> Post </button> </form> I have no idea why this is not saving. Any help would be much Appreciated. Thank You in Advance. -
Generate forms from serializer
I'm working with React in the front-end with Material-UI, and I would like to auto generate forms based on my serializer's schema. Usually, the way that CRUD works in the app is by listing the registers, and then give the option to add, edit, or remove registers. So, my idea would be to get the serializer's schema in the listing part of the CRUD and then use it to generate the forms later on. Is there anyway to do this? I'm thinking about maybe creating an npm package to help on it... Thanks -
How to display Django model's foreign key as its attribute in admin panel?
In Django Admin, my model CNAME has a foreign key to AuthUser, when I create a model instance, I must choose a User, but there display the AuthUser's Object number, how to display username in there? The model details: class CNAME(models.Model): name = models.CharField(max_length=64, unique=True, help_text=". eg:gat.google.com") desc = models.CharField(max_length=5120, null=True, blank=True, help_text="desc") desc_en = models.CharField(max_length=5120, null=True, blank=True, help_text="desc)") user = models.OneToOneField(unique=True, to=AuthUser, on_delete=models.DO_NOTHING, help_text="belong to user") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = "CNAME" verbose_name_plural = "CNAME" class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' In my admin.py I register it: admin.site.register(CNAME) class CNAMEAdmin(admin.ModelAdmin): list_display = ['name', 'desc', 'desc_en', 'user', 'ctime', 'uptime'] list_filter = [] search_fields = ['name', 'desc'] list_per_page = 10 -
How to POST a List of Objects to API in React JS/Django
So, I have a team (NY Yankees) and a list of players (players): 'yankees' ['babe ruth', 'lou gehrig', 'joe dimaggio', 'yogi berra', 'mickey mantle', 'derek jeter'] I have a form where I am sending POST request data, and it works perfectly fine, but I can only do it one at a time: function handleEnterButtonSubmitted(id) { const requestOptions = { method: "POST", headers: {"Content-Type": "application/json" }, body: JSON.stringify({ team: team, player: player, }), }; fetch('/api/player/', requestOptions) .then((response) => response.json()) .then((data) => console.log(data)); } My question is how do I take this already-working form, and turn it into an instance where I can submit various players, and they will all be associated to the "Team" object (foreign key in Django Models). How would the function "handleEnterButtonSubmitted" be different? My idea would be to use the following MaterialUI Component: <FormControl className={classes.formControl}> <InputLabel shrink htmlFor="select-multiple-native"> Native </InputLabel> <Select multiple native value={personName} onChange={handleChangeMultiple} inputProps={{ id: 'select-multiple-native', }} > {names.map((name) => ( <option key={name} value={name}> {name} </option> ))} </Select> </FormControl> This is the function: const handleChangeMultiple = (event) => { const { options } = event.target; const value = []; for (let i = 0, l = options.length; i < l; i += 1) { if … -
Using Django ORM for computed field
I have a scoreboard for a web app. Each user post is worth 10 points, and each user comment is worth 1 point. I want to sort by highest score first. So with raw SQL, it would be: select username, email, ( select 10 * count(*) from posts_post where accounts_customuser.id = posts_post.author_id ) + ( select count(*) from posts_comment where accounts_customuser.id = posts_comment.author_id ) total from accounts_customuser order by total desc, username; Of course, the idea with Django is to leverage the ORM and avoid raw SQL. I see there are aggregates, so it's close to something like this: queryset = get_user_model().objects.annotate(post_count=Count('posts'), comment_count=Count('comment')).order_by('-post_count', '-comment_count', 'username') However, that's not quite right because if I have a user with 1 post and 1 comment (11 points) and then one with 0 posts and 12 comments (12 points), they wouldn't be sorted right by the ORM with the above QuerySet. I tried leveraging F: # Note: CustomUser is what get_user_model() returns CustomUser.objects.annotate(post_count=Count('posts'), comment_count=Count('comment'), total=Sum(F('post_count') * 10 + F('comment_count')) ).order_by('-post_count', '-comment_count', 'username') However, that throws the following error: FieldError: Cannot compute Sum('<CombinedExpression: F(post_count) * Value(10) + F(comment_count)>'): '<CombinedExpression: F(post_count) * Value(10) + F(comment_count)>' is an aggregate I'm not sure where to go from here. … -
Concatenation of ObjectId and string in django template
I have a very simple question, on which i spent hours. Heres the deal: i insert a path to an image in mongodb, save said image in my static folder (under objectId.png) and pass the objectId to my template in order to display it. Heres some code, in views: return render(request,'resultat_simulation.html',{'truc':truc2}) truc2=str(truc.id), truc being the object inserted in the DB. It is passed to the template without issue. Now, the template: {% extends 'base.html' %} {% load static %} {% block body %} {{truc}} <img src="{% static 'C:\Users\smeca\Documents\projetfinal\stage\app\static\images\{{truc}}.png' %}"> {% endblock %} If instead of {{truc}}, i put the ObjectId of any image, it is rendered. I just want to append the string form of objectid to '.png' so i can loop through the images and display them all. I tried everything i found on the net to no avail. Thanks in advance. -
Generic relations serialization in django-rest-framework
could you help me please with the serialization of generic relation in Django rest framework. I need to get data for SWOT object including company and all comments for it. I have problems with retrieving comments which is a generic field. models.py: class SWOT(models.Model): name = models.CharField(max_length=500, default='') description = models.CharField(max_length=500, default='', blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) #Generic Relation for comments comments = GenericRelation(Comment) def __str__(self): return self.name class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField(verbose_name="") created_date = models.DateTimeField(default=timezone.now) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() views.py: class SwotView(generics.ListAPIView): serializer_class = SwotSerializer def get_queryset(self): swot_id = self.kwargs['swot_id'] return SWOT.objects.filter(id=swot_id) serializers.py: class CommentRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, SWOT): serializer = SwotSerializer(value) else: raise Exception('Unexpected type of comment ', type(value)) return serializer.data class SwotSerializer(serializers.ModelSerializer): company = CompanySerializer() comments = CommentRelatedField(many=True, queryset=Comment.objects.all()) class Meta: model = SWOT fields = ('id','name', 'description','company','comments') I have tried to implement the code from the example in documentation but I tackle error. I don't know why the type of the object is Comment instead of SWOT. Could you tell me please what I can do to make this code work just like in documentation or propose another solution like regular relational fields as … -
Object of type CustomUser is not JSON serializable
I'm working on a small project using Django, but i'm getting an error as you can see, i try to make a pagination starting from a list, i seems like my object is not serializable from .models import ContactCenter from django_tenants.utils import schema_context from apps.contacts.models import Contact from django.db import connection from customer.models import Client # try to delete from users.models import CustomUser from pprint import pprint # Create your views here. class ContactViewCenter(object): def sharedContact(self, connectedUser): contactList = [] contacts = ContactCenter.objects.filter(contact_source=connectedUser) | ContactCenter.objects.filter(shared_with=connectedUser) #pprint(vars(contacts)) for contact in contacts: #pprint(vars(contact)) users = CustomUser.objects.filter(id=contact.contact_source_id) | CustomUser.objects.filter(id=contact.shared_with_id) for user in users: with schema_context(str(user.username)): tenant = Contact.objects.filter(id=contact.contact) for x in tenant: contactList.append(x) return contactList second class def list(self, request, *args, **kwargs): #self.get_queryset() queryset = super().sharedContact(self.request.user.id) #queryset = queryset.filter(user = self.request.user) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Error : Object of type CustomUser is not JSON serializable -
How do I add an attribute on a Django Request object using async middleware that lazy loads and is asynchronous?
I am using Django 3.1, and I want to start taking advantage of async views. As a first step, I am turning my sync middleware classes into async middleware classes. Everything is working well except for one sync middleware class. I have an existing sync middleware class that adds an attribute to the Request object. The value of this attribute is lazily loaded, because it is only needed on about 5% of requests, and it has to make multiple calls to the database. Here is the class as it exists: from django.utils.functional import SimpleLazyObject from .services import get_account class AccountMiddleware: """ Add an account to the request """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # get_account function is synchronous request.account = SimpleLazyObject(lambda: get_account(request)) I have tried working through existing code, using 3rd party libraries, and rolling my own solution, but I cannot get the middleware to work properly. Any guidance on how I should approach this would be appreciated. Thanks! -
aioredis.errors.ProtocolError: Protocol error, got "H" as reply type byte
I have a Django project and I'm trying to implement the Redis channel. When I add the config below, my app works. CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } However, when I try to add the following config, I'm getting aioredis.errors.ProtocolError: Protocol error, got "H" as reply type byte error. CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } Here is my consumers.py file; class VideoCallSignalConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'Test-Room' # print(self.scope["user"]) # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() Btw, I'm using macOS. I already have installed Redis with brew install redis command and started the redis-server with daphne -p 6379 VideoConference.asgi:application command. -
Can't upgrade pip on Elastic Beanstalk
I've been having this problem for a couple of days now, I'm trying to deploy a django app in Elastic Beanstalk but every time I try to do it this particular error shows up: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-iHdpsP/pefile/ You are using pip version 9.0.3, however version 21.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. I have read that by putting the command in the .ebextensions directory like: container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false that would do the job, but I'm still facing the problem. -
JOIN Two tables using django ORM
I'm working on a small project using Django, how i can get source_contact and shared_with and username. i would like to do a kind of INNER JOIN ( SELECT * FROM ContactCenter INNER JOIN CustomUser WHERE shared_with = CustomUser.id OR contact_source = CustomUser.id ) How can i do that using django ORM This is my models : class CustomUser(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True, blank=False, null=False) class ContactCenter(models.Model): contact = models.IntegerField(blank=False, null=False) contact_source = models.ForeignKey(CustomUser, to_field="id", on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(CustomUser, to_field="id", related_name="sw", on_delete=models.SET_NULL, null=True, blank=False) Expected result : shared_with - contact_source - username n - n - n -
Intellisense for html does not work if file association set to django-html
I am using vscode for my django project and for templates to get help with Django Template Language, I installed the Django extension. Now after installing this extension the intelliSense for html tags is not working anymore. So, now I have to write whole html tags and its getting troublesome. Anyway to enable html intelliSense for django-html type files too? my project settings.json file code { "python.languageServer": "Pylance", "files.associations": { "**/*.html": "html", "**/templates/**/*.html": "django-html", "**/templates/*": "django-html", "**/templates/**/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "emmet.includeLanguages": { "django-html": "html" }, "beautify.language": { "html": [ "htm", "html", "django-html" ] }, } If I change 'django-html' to 'html' in above code then the html intellisense works but then the help for DTL does not work anymore. -
How can I redirect the user to the login page until they complete the authorization?
I found such a piece of code, but I don't understand how it works. And if you set the path to another page without performing authorization - this page opens. @login_required def my_view(login_url='/'): return HttpResponseRedirect('/config') I need your help. (how authorization is performed) class LoginView(View): def get(self, request, *args, **kwargs): form = LoginForm(request.POST or None) context = { 'form': form } return render(request, 'manager/login.html', context) def post(self, request, *args, **kwargs): form = LoginForm(request.POST or None) context = { 'form': form } if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) return HttpResponseRedirect('/config') return render(request, 'manager/login.html', context) -
Django runserver won't run because of bootstrap error message
When I try to run my server in Django it is not able to find my app track that I just created: ModuleNotFoundError: No module named 'track' I got the same message for the app I was working on previously. I also get error messages relating to bootstrap, the last one being this: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' I started noticing this once I removed the bootstrap configurations from another app I was working on. I just downloaded bootstrap and know very little about it, especially how it could stop a Django server from running and not recognizing my app. Any ideas??? -
Add custom filename django model (models.FileField)
I have a model for my user and another model for music style. In my model of musical styles, I need to put the image under a name other than the original name. The new name I would like is the 'email of the user who is saving' + '_' + 'milliseconds'. Staying in this format: 'test@gmail.com_1621196336' Model User: class CustomUser(AbstractUser): username = None id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) email = models.EmailField('E-mail', unique=True, null=False) Model Music Styles: class MusicStyle(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=150, null=False, blank=False) image_link = models.FileField(upload_to='musics/thumbnail_images/##CUSTOM_NAME##') Musical style is in a different model from the user model. How to do this? -
How do I go about limiting a group to a certain number of users with Django channels?
So the question is basically how would I limit the number of users to say two. I'm building a app and I basically want two users max in a game room. So at the moment on connect channel is added to group but is there a way to check if group has reached 2 users then reject web socket connection? I'm pretty much a beginner and new to channels, the documentation doesn't seem to help. Also is there a way to list total groups users? So I can display the group name and users in a lobby. -
Django deploy with Heroku for the first time
My first time deploying an app, I'm following the PrettyPrinted video "Deploy a Django App to Heroku". Whell, when I ran heroku local I'm get this error. › Warning: heroku update available from 7.52.0 to 7.53.1. [WARN] ENOENT: no such file or directory, open 'Procfile' [FAIL] No Procfile and no package.json file found in Current Directory - See run --help TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at Index.run (/snap/heroku/4048/node_modules/@heroku-cli/plugin-local/lib/commands/local/index.js:30:38) at Index._run (/snap/heroku/4048/node_modules/@heroku-cli/plugin-local/node_modules/@oclif/command/lib/command.js:43:31) My project look like this: