Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filtering queries with Q
I have confusing problem in querying in django. I know its not a bug and it is something that I don't know. So models are: class Product(models.Model): name = models.CharField(max_length=255) class AttributeValue(models.Model): value = models.CharField(max_length=255) product = models.ForeignKey(Product, related_name='attribute_values', on_delete=models.CASCADE) I have one product object called T-shirt and it has two AttributeValue with ids 1, 2. And when I filter like this (1): Product.objects.filter(Q(attribute_values__pk__in=[1, 2])) Its returning my T-shirt object. But when I filter like this (2) Product.objects.filter(Q(attribute_values__pk__in=[1]), Q(attribute_values__pk__in=[2])) there is no queryset found here. How is this happening? Previous codes are just examples and I have project that really need to do with this second filter (2). -
predefined template customization in django
i was trying to customize the predefined template in django but am not able to edit login page, i have to include registration link to built in login template and can anyone please help me with this. And i have one doubt that is, can predefined template are modifiable or not? thanks in advance. -
Are there any caveats involved in using object.__class__ in python?
Are there any caveats involved in using object.__class__? for example in Django once I did this: model_object.__class__.objects.all() I would like to know if that's perfectly fine. Thanks. -
Django QuerySet: Format query result as custom dictionary
I am working on a RBAC system for my Django-React app. I have this certain object structure that I want to generate but I am not sure how to do so directly from Django's QuerySet API. Currently, I have this query permissions |= PermissionAssignment.objects.filter(role=role['role__id']).values( 'permission__object__id', 'permission__object__name', 'permission__operation__id', 'permission__operation__name' ) which returns this object on my frontend: permissions: [ { permission__object__id: 1, permission__object__name: 'Post', permission__operation__id: 1, permission__operation__name: 'Read' }, { permission__object__id: 1, permission__object__name: 'Post', permission__operation__id: 2, permission__operation__name: 'Write' }, ] I do not require the permission object to have that complex structure. I only need to take hold of the object name and the operations enabled to this object for the current user. So basically, I just need it to be structured as: permissions:[ "Post": { operations: ['Read', 'Write'] } ] I know I can manipulate the original result on my frontend to get what I want, but I don't see that is necessary when I can format the result on the server-side level right away, except that I am not sure how to do that in Django. -
django ImproperlyConfigured: The SECRET_KEY setting must not be empty after splitting settings.py
I know there are a lot of these questions... but I've looked through them and can't seem to find anything that fits this situation... So here I go I decided to split my settings.py into 3 files, and move them into a settings folder, and that's when everything stopped working base.py production.py development.py Here's the directory structure (this is all under the main 'project' folder, let's assume it's called "myproject" for now) myproject ... ├── pages │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── myproject │ ├── __init__.py │ ├── adapter.py │ ├── base.py │ ├── celery.py │ ├── settings │ │ ├── __init__.py │ │ ├── base.py │ │ ├── development.py │ │ └── production.py │ ├── urls.py │ └── wsgi.py ... let's start with my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.production') application = get_wsgi_application() and now base.py import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'anymail', 'storages', 'django_extensions', 'cacheops', 'django_celery_beat', 'django_celery_results', 'django_cleanup.apps.CleanupConfig', 'albums.apps.AlbumsConfig', 'user_profile.apps.UserProfileConfig', 'votes.apps.VotesConfig', 'myproject.templatetags', 'participation.apps.ParticipationConfig', 'siteinformation.apps.SiteinformationConfig', ] … -
How to implement dual display in a Django app
I am developing a Django application for a school project and it is essentially one page that takes user input and another page that responds to the user input by displaying various alerts/data. The end goal is to have the application launch on a tablet and display the user input page while having the summary data page displayed on the monitor. The issue is that as of now, these two are communicating via localStorage values. Obviously this will need to be changed down the line. I am extremely new to Django and web dev so I was wondering if this is even a feasible task and what the right approach would be? -
I need to store a car's make and model. Should I have car brands/models be database tables, or should I just hardcode them as field choices?
I'm writing an application where users put in information about their cars. Part of what I need to do is have a dropdown for the fields of car brand and car model. At first, I was going to hardcode this into tuples and then use the choices field on a models.CharField. But then I realized that this could take an unreasonable amount of time, and I would undoubtably miss a few models. Instead of hardcoding, I'm thinking of making a CarBrand and CarModel table, and then adding different brands and models via the admin site. Which approach is better? -
FormData is empty or None in Django Views
How to properly get FormData values in Django 1.8? Clearly, it has a data as i tried viewing it on the console but somehow unable to access it via Django view. Here's my client side code: reader.addEventListener("loadend", function() { var imgsrc = reader.result; storedFiles.push(imgsrc); var html = "<div class=\"col text-center\"><img src=\"" + imgsrc + "\" data-file='" + f.name + "' class='img-fluid selFile' title='Click to remove'><br/>" + i + "</div>"; selDiv.append(html); //call extract text var formdata = new FormData(); formdata.append("image", imgsrc); console.log(formdata.get("image")); $.ajax({ crossDomain: true, type: "GET", data: formdata, dataType: 'json', processData: false, contentType: "multipart/form-data", url: "/scan/scanner", beforeSend: function() { }, success: function(response) { var parseResp = JSON.parse(response); $("#extracted_text").append(parseResp.extracted_txt); }, error: function(e) { alert(e.statusText); } }); }, false); and a simple view in Django: def callWebScanner(request): print 'Django View' imgstring = request.FILES.get("image") print imgstring -
Second file upload fails to process on production server
This is an ongoing problem that is driving me nuts. I have an AJAX video upload in my Django project where users can upload video files. The problem I was immediately facing was when videos are displayed in a ListView you either get.. a.) a lagging site because of serving all the video files or b.) no thumbnail when preload is turned off. So my solution was to write a small piece of code that grabs the first frame of the video, saves it as a thumbnail, then display the thumbnails in the ListView instead of the full video files. This worked for awhile.. Until.. For some reason the video files are now only allowing one file to be processed on the production server. Once you try to upload the second video the OpenCV ret, frame = cap.read() returns False or None when ret should be True. This is saying that the video is not being read. But why? Why is it always on the second video upload and only on a production server? video_processing.py: def create_thumbnail(input_path, output_path): """ Save first frame of video for use as video thumbnail. :param input_path: video input path :param output_path: image output path :return: … -
Gunicorn can't connect to web socket?
So I am using a docker for this python chat app project. I originally had python manage.py runserver 0.0.0.0:8000 as my command in docker-compose. I found that I should switch to gunicorn if I want to deploy my app on web (like heroku). The tutorial I found say simply change the command in docker-compose to gunicorn myproject.wsgi -b 0.0.0.0:8000. I did that, and all the websocket connections broke. There's a fail to send due to websocket is still in CONNECTING state, then after a while handshake fails with a status code of 404. All the setup were the same as before, except that one line. Just wondering what else I need to change to make websocket work with gunicorn? Thanks -
__str__ returned non-string (type student)
**guys help am totaly blank/? tell me what to do **str returned non-string (type student) am using python 3.8 and django 2.2.9 when i try to modify any thing in the degree section it gev me this page in the photo i dont now why is it some thing with def str(self) or what??om so confused am using python 3.8 and django 2.2.9 <br> ``` Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/worker/degree/add/ Django Version: 2.2.9 Python Version: 3.8.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'worker'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\contrib\admin\options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\contrib\admin\options.py" in add_view 1645. return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\nfc\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File … -
AttributeError: 'tuple' object has no attribute 'get' with redirect(reverse) in django
my django app has a form view for submitting information that creates a new post, after which it should redirect to a thank you page. def submit(request, slug): account = get_object_or_404(Account, slug=slug) if request.method == "POST": # process the data and post form as JSON ret = create_or_edit_post(request, account, post=None, duplicate=False) if isinstance(ret, HttpResponseRedirect): post = account.posts.latest('id') # handle post info and post creation return redirect(reverse('post-submit-ty', kwargs={'slug': account.slug})) return ret context = { "account": account } return render(request, 'submit.html', context) since the redirect(reverse(...)) returns a tuple, this throws: AttributeError: 'tuple' object has no attribute 'get' File "django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "newrelic/hooks/framework_django.py", line 325, in wrapper return wrapped(*args, **kwargs) File "django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: since I need to pass slug kwarg (as a tuple) and redirect to the thank you page but it's looking for an http response is there a way to handle this with redirect(reverse) or HttpResponseRedirect(reverse)? thanks -
Can't link CSS file to HTML
I'm new to Django and I had problem while linking a CSS file to HTML. Despite doing it with a tutorial I wasn't able to find what's wrong with the code. The CSS file seems to work parcially. home file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="description" content="Dento - Dentist &amp; Medical HTML Template"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Title --> <title>Dento - Dentist &amp; Medical HTML Template</title> <!-- Favicon --> <link rel="icon" href="{% static 'website/img/core-img/favicon.ico' %}"> <!-- Core Stylesheet --> <link rel="stylesheet" type="text/css" href="{% static 'website/css/style.css' %}" /> </head> style.css file, for some reason this file was originally located elsewhere, so I had to change a little bit the path of the urls (those files are located in the same folder). Personally I think that the problem is related to those import but I don't know what's wrong: @import url("https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700"); @import url('bootstrap.min.css'); @import url('animate.css'); @import url('default-assets/classy-nav.css'); @import url('owl.carousel.min.css'); @import url('magnific-popup.css'); @import url('font-awesome.min.css'); @import url('style2.css'); and the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] and the staticfiles_dir: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] -
I want to show a popup for otp input if the form is valid and saves the form if the Otp validates in django
I just want when a user submit the form an otp is sent to the entered number and an model box appears for the otp input. Then if the correct otp is entered the user get saved. here's my registration.html {% extends 'basic.html' %} {% block body %} {% load crispy_forms_tags %} <div class="container mt-3"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-success" type="submit" id="sp" name="sp">Sign Up</button> </div> </form> <div class="border-top"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Log In</a> </small> </div> </div> {% endblock %} {% block js %} <script> <!-- {% if form.is_valid %}--> <!-- console.log('good');--> <!-- var otp = prompt("Please Enter The OTP", "XXXXXX");--> <!-- {% endif %}--> }) </script> {% endblock %} views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): messages.success(request, 'Welcome') return redirect('/') else: form = RegisterForm() return render(request, 'registration.html', {'form': form}) Please tell me what changes i needed. I have module for sending and verrifying the otp which are working good. Let me know if any more information is needed to understand the question or for a solution. Please tell me if you have advice, a special thank … -
Django forms.validation error not showing
I'm trying to create a registration form using djangos built in User. I'd like to have a password field and then a second field to verify the passwords match (keep in mind this is a new user so no password exists in the db yet). I think I'm really close and it seems like I need the validation error to pass from the form to the view. The form just clears our the passwords...and leaves the remaining entered data, but no validation error is thrown at all. Any thoughts and help is greatly appreciated! Form class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) ver_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': ' confirm password'})) ver_email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': ' confirm email'})) class Meta(): model = User fields = ('username', 'password', 'first_name', 'last_name', 'email') def clean(self): all_clean_data = super().clean() clean_email = all_clean_data['email'] clean_ver_email = all_clean_data['ver_email'] clean_password = all_clean_data['password'] clean_ver_password = all_clean_data['ver_password'] if clean_email != clean_ver_email: raise forms.ValidationError("Emails do not match") if clean_password != clean_ver_password: raise forms.ValidationError("Passwords do not match") return all_clean_data View def register(request): registered = False newregister = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save(update_fields=['username','password','first_name','last_name','email']) profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic … -
Cannot Resolve 'function' object has no attribute '_default_manager'
I've been struggling with this all day, I already implemented the CreateView and it works fine, now that I'm trying to do the Update with the UpdateView (CBV) I'm getting this error: Request Method: GET Request URL: http://127.0.0.1:8000/drivers/edit/2/ Django Version: 3.0.2 Exception Type: AttributeError Exception Value: 'function' object has no attribute '_default_manager' Exception Location: C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\detail.py in get_queryset, line 67 Python Executable: C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\Scripts\python.exe Python Version: 3.7.3 model.py class conductores(models.Model): nombres = models.CharField(max_length=25) apellidos = models.CharField(max_length=25) edad = models.IntegerField() phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") # validators should be a list telefono = models.CharField( validators=[phone_regex], max_length=17, blank=True) ine = models.FileField(upload_to='INE/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('nombres', 'apellidos') verbose_name_plural = "Conductores" def __str__(self): return '%s %s' % (self.nombres, self.apellidos) def get_absolute_url(self): return reverse('conductores') urls.py urlpatterns = [ path('', views.index, name='index'), # path('conductores_sort/', # views.conductores_sort.as_view(), name='conductores_sort'), path('conductores_list/', views.conductores), path('drivers/', views.ConductoresListView.as_view(), name='conductores'), path('drivers/add/', views.ConductoresCreate.as_view(), name='conductor_new'), path('drivers/edit/<int:pk>/', views.ConductoresUpdate.as_view(), name='conductor_edit'), ] views.py class ConductoresCreate(CreateView): form_class = PostConductores template_name = "AC/add_driver.html" class ConductoresUpdate(UpdateView): model = conductores fields = ('nombres', 'apellidos', 'telefono', 'edad', 'ine') -
How I can show only BooleanField(True) in serializers?
models: class User(AbstractUser): is_student = models.BooleanField('student status', default=False) serializers: class StudentsSerializer(serializers.ModelSerializer): is_student = serializers.BooleanField(required=True) class Meta: model = User fields = ['is_student', 'user_photo', 'last_updated'] get request show all with False and True -
Django: How to show model field choices in a form?
I have a model A with field F that has some choices. This model is a foreign key in Model B. I am rendering Model B using forms.ModelForm and django-crispy-forms, but am not sure how to display the choices in the HTML page. What is the correct way to do this? Sample code: class TraceType(models.Model): """Type of trace.""" trace_type = models.CharField(max_length=6, help_text='Type of trace', choices=[ ('X', 'Choice X'), ('Y', 'Choice Y'), ('Z', 'Choice Z'), ]) def __str__(self): """String representation of object.""" return self.trace_type def natural_key(self): """Serialization.""" return self.trace_type, class TraceUpload(models.Model): """Upload form model structure.""" product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=False) trace_type = models.ForeignKey(TraceType, on_delete=models.SET_NULL, null=True, blank=False) userid = models.CharField(max_length=8, help_text='User id') forms.py: class TraceUploadModelForm(forms.ModelForm): ... class Meta: model = TraceUpload fields = [ 'product', 'trace_type', ] -
Django Rest Framework PUT view saying validated_data is unfilled
I'm trying to use Django Rest Framework for updating my database using the HTTP PUT, but when on my client I get the error Exception Value: update() missing 1 required positional argument: 'validated_data' and in the python code I get an error that says Validated_data unfilled. Here is my model code: nombre = models.CharField(max_length=200) calle_numero = models.CharField(max_length=200) zona_residencial = models.ForeignKey(Zona, on_delete=models.CASCADE) telefono = models.CharField(max_length=20) numero_habitantes = models.IntegerField() tipo_residente = models.CharField(max_length=100, choices=[(tag.value, tag.value) for tag in TipoHabitanteEnum]) codigo_acceso = models.CharField(max_length=6, default="000000") status_activacion = models.BooleanField(default=False) class Meta: verbose_name = 'Residente' verbose_name_plural = 'Residentes' def __str__(self): return self.nombre here is my serializer code: class Meta: model = Residente fields = '__all__' And my view (PUT method where the error is) code: """ Modifica un residente """ try: id_residente = self.queryset.get(pk=kwargs["pk"]) serializer = ResidenteSerializer update_residente = serializer.update(id_residente, request.data) return Response(ResidenteSerializer(update_residente).data) except Residente.DoesNotExist: return Response( data={ "message": "El residente con id {} no existe".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) in the update_residente = serializer.update(id_residente, request.data) is the validated_data error is and that's why I can't update my database but I don't know how to fix it. Hope you can help me. -
why pg_config has been asked to be installed in a django/sqlite application?
I am trying to deploy an ecommerce application on heroku with no success. After trying to install pip3 install django-heroku an error appears detailing that pg_config executable not found. I thought that it may be some issues with my python installation but I dont think so, thus, I dont understand why it is asking about the pg_config if I am using sqlite? Therefore, here is the error I am getting after I try to run a pip3 installation: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. -
Integrate Django authentication with Enterprise Identity Provider PingFederate
We developed web apps in django framework. We have an enterprise Identity Provider which is PingFederate. The main home page (which is different from our site) from chrome browser and edge browser directly recognizes the user and logs them in all the internal websites. We are also on the same network share same domain. We also want to integrate SSO and want to authenticate our users directly with asking password. I researched every where and got to know the authentication is happening by kerbose authentication. Somehow the edge or chrome is sending some token or id or some TGT ticket to the Identity Provider then they will authenticate and send the username back to the client browser. Can any one please help me how to solve this. Thanks in advance. -
Ajax / jQuery Django refresh class of elements
I was not able to come up with a more fitting title, but my issue is the following: I generate a list of posts with the option to like and dislike them, depending on if they have already been liked. {% for post in posts %} <hr> <strong>{{ post.owner }}</strong> </br> {{ post.content }} </br> <i>{{ post.post_date }}</i> </br> <form action="{% url 'like' %}" method="post" class="likeform"> {% csrf_token %} <input type="hidden" id="post_id" value="{{ post.id }}"> {% if post.id not in liked_posts_ids %} <button type="submit" >Like</button> {% else %} <button type="submit" >Dislike</button> {% endif %} </form> {% endfor %} Now, as it is with all websites that use stuff like this, I don't want to refresh the whole website everytime someone clicks the like/dislike button. My current JS looks like the following: $(document).on('submit','.likeform',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'like' %}', data:{ post_id: $('#post_id').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ $(".likeform").load(" .likeform > *"); } }); The POST request works fine, but the success:function()part does not. It refreshes all buttons, which is not that nice, but it also puts all buttons in all forms. Currently there are 6 posts in my database which results in 6 like/dislike buttons under every post after $(".likeform").load(" .likeform > … -
Creating Group/Teams in Django - Py
I am having difficulty finding examples, applications for group creation on Django, and could use some help. Basically there's a 'Create a New Team' page where the logged in user can use, I am trying to auto-assign the user to the group with .user_set.add(User). My questions are: Am I creating the new teams correctly (when I debug, g1 gets overwritten each time, should I do a For Loop to make sure g+n=? doesn't exist? and Any way to access the created teams in the admin page or the Django Py Shell? Thanks in advance, I'm a beginner models.py class TeamCreation(models.Model): class meta: db_table="teams" team_name = models.CharField(max_length=100) team_key = models.CharField(max_length=70) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.team_name forms.py class TeamCreationForm(forms.ModelForm): class Meta: model = TeamCreation fields=['team_name','team_key'] views.py from django.shortcuts import render, redirect from .forms import TeamCreationForm from django.contrib.auth.decorators import login_required from django.utils import timezone from django.contrib.auth.models import Group from .models import TeamCreation @login_required def create_team(request): if request.POST: form = TeamCreationForm(request.POST) if form.is_valid(): newTeam = form.save(commit=False) newTeam.author = request.user newTeam.date_posted = timezone.now newTeam.save() #set group name g1 = Group.objects.create(name=newTeam.team_name) #autopopulate / assign author to new team g1.user_set.add(newTeam.author) #debug (hopefully print: Team Name, Key, Creator, Members print(newTeam) … -
Docker [Errno 111] Connect call failed ('127.0.0.1', 6379)
I am trying to follow the tutorial here https://channels.readthedocs.io/en/latest/tutorial/part_2.html and check if channel layer can communicate with Redis. The only different thing I'm doing is that I'm using docker-compose and running the entire thing on a docker container, and that seems to be messing up with everything. This is the error message I'm getting when I try to run async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 116, in __call__ return call_result.result() File "/usr/local/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/local/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 156, in main_wrap result = await self.awaitable(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/channels_redis/core.py", line 293, in send async with self.connection(index) as connection: File "/usr/local/lib/python3.7/site-packages/channels_redis/core.py", line 820, in __aenter__ self.conn = await self.pool.pop() File "/usr/local/lib/python3.7/site-packages/channels_redis/core.py", line 70, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/usr/local/lib/python3.7/site-packages/aioredis/commands/__init__.py", line 175, in create_redis loop=loop) File "/usr/local/lib/python3.7/site-packages/aioredis/connection.py", line 113, in create_connection timeout) File "/usr/local/lib/python3.7/asyncio/tasks.py", line 414, in wait_for return await fut File "/usr/local/lib/python3.7/site-packages/aioredis/stream.py", line 24, in open_connection lambda: protocol, host, port, **kwds) File "/usr/local/lib/python3.7/asyncio/base_events.py", line 958, in create_connection raise exceptions[0] File "/usr/local/lib/python3.7/asyncio/base_events.py", line 945, in create_connection await self.sock_connect(sock, address) File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 473, in sock_connect return await fut File "/usr/local/lib/python3.7/asyncio/selector_events.py", … -
Django Rest Framework: Transforming Model For Serializer
I have an invite model that maps Inviters to Invitees user and to_user. However I need to return just the list of users to the client. How should I transform a queryset of Invite Objects (just id, user, and to_user) into a query of users mapping to that to_user field? Here's what I have so far. class InvitesViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated, ] def list(self, request): """ List all people invited by the request.user """ invite_objects = Invite.objects.filter(user=request.user) invited_users = ??? (Users.objects.filter(id__in=invite_objects.to_user.id?) <- ? serializer = UserSerializer(invited_users, many=True) return Response(serializer.data)