Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get instance by file name for a file in ImageField
Django 3.1.6 class ResponsiveImage(models.Model): responsive_image = models.ImageField(upload_to=_raster_img_upload_to) I want to find an instance by the image file_name: file_name = 'img/raster/0a8449e7-8e50-4c02-853e-59a25592770d/img_144_96_fallback_3x_4.fallback' ResponsiveImage.objects.get(responsive_image__name=file_name) But this gets an error: {FieldError}Unsupported lookup 'name' for ImageField or join on the field not permitted. Could you help me? -
How to send the value of XMLHttpRequest.save() to django view?
I have an AJAX/XMLHttpRequest and I want to send the result of window.confirm to view and use it. Currently this is my js: $(".release_hold").click(function () { var id = $(this).val(); $.ajax({ url: "/account/release_hold/" + id + "/", dataType: "json", success: function (data) { if (data.message != null) { // alert(data.message); result = window.confirm(data.message) == true; alert(result); if (result) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "../release_hold/" + id + "/", true); # I think this should be POST. xmlhttp.send(result); } } }, }); }); Now on my views.py, I dont know if I need/how to add the result in my parameter. Once the result of windows.confirm is inserted, I can proceed. def release_hold(request, id, *args, **kwargs): ... if request.is_ajax() and request.POST : # Add result here. .... data = { 'message': "RELEASE DONE" } else: .... data = { 'message': "Are you sure you want to release record?" } return JsonResponse(data) -
DRF - How to queryset to only objects that the user is the owner of within an intermediate model?
I'm my DRF API, I have an intermediate model Ingredient that links two models, Product and Recipe. class Product(models.Model): name = models.CharField() class Recipe(models.Model): name = models.CharField() user = models.ForeignKey(User, on_delete=models.CASCADE) ingredients = models.ManyToManyField(Product, through='ingredient') class Ingredient(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.FloatField(default=0) In my current DRF generics.CreateAPIView for Ingredient, I want it to only display and allow a user to see and send a post request to create a new Ingredient entry for a Recipe that they own. But right now it keeps displaying Recipes for all users. I tried filtering the Recipe for the Ingredient model in my serializers.py with: serializers.py: class IngredientPostSerializer(serializers.ModelSerializer): recipes = serializers.SerializerMethodField() def get_recipes(self, obj): recipes = Recipe.objects.filter(user_id=self.request.user.id) return recipes class Meta: model = Ingredient fields = '__all__' -
Django email won`t send inside a view function
def contactform(request): if request.method == 'GET': form = contact_form() else: form = contact_form(request.POST) if form.is_valid(): contact_name = form.cleaned_data['aname'] contact_email = form.cleaned_data['aemail'] contact_subject = form.cleaned_data['asubject'] contact_message = form.cleaned_data['rmessage'] try: email_from = settings.EMAIL_HOST_USER recipient_list = ['xxx@gmail.com'] html_message = render_to_string('main/contact.html', {'contact_email': contact_email, 'contact_name': contact_name, 'contact_message': contact_message}) msg = EmailMessage(contact_subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() except ValueError: return HttpResponse('Invalid header found.') return render(request, "main/home.html", {'successcform': 'Success! Thank you for your message. We will reply shortly.', 'contactform': form}) return render(request, "main/home.html", {'contactform': form}) This works well, the email is sended when someone fill the contact form, but if i use the send mail code with : def signupuser(request): if request.method == 'GET': return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) email_from = settings.EMAIL_HOST_USER recipient_list = [request.POST['username']] contact_subject = [' ,thank you for registering to our site.'] html_message = render_to_string('main/signupuser.html', {'username': request.POST['username']}) msg = EmailMessage(contact_subject, html_message, email_from, recipient_list) msg.content_subtype = "html" msg.send() return redirect('currenttodos') except IntegrityError: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'todo/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) The email wont send, the user when registering dont receive any email. Simply doesn`t work … -
AttributeError at /add/...Getting 'str' object has no attribute 'get' in Django.Atrri
models.py I write this code for creating a form which has two fileds named Title and Desc from django.db import models.Here is models.py code. class Post(models.Model): title = models.CharField(max_length=200) desc = models.TextField() And Here is forms.py Code forms.py from django import forms from django.contrib.auth.forms import UserCreationForm,AuthenticationForm,UsernameField from django.contrib.auth.models import User from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','desc'] # label = {'title':'Title','desc':'Description'} widgets={'title':forms.TextInput(attrs={'class':'form-control'}), 'desc':forms.Textarea(attrs={'class':'form-control'})} Here is the views.py code views.py from django.shortcuts import render,HttpResponseRedirect from .forms import SignUpForm,LoginForm,PostForm from django.contrib import messages from django.contrib.auth import authenticate,login,logout from .models import Post def add_post(request): if request.user.is_authenticated: if request.method == "POST": form = PostForm(request.method) if form.is_valid(): title1 = form.cleaned_data['title'] description = form.cleaned_data['desc'] pst = Post(title=title1,desc=description) pst.save() form = PostForm() else: form = PostForm() return render(request,'blog_app/addpost.html',{'form':form}) else: return HttpResponseRedirect('/login/') Here is the addpost.html adpost.html {% extends 'blog_app/base.html' %} {% load static %} {% block content %} <div class="col-sm-10"> <h3 class="text-black my-5 alert alert-success">Add Post</h3> <form action="" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Add" class="btn btn-primary"> <a href='{% url "dashboard"%}' class="btn btn-danger">Cancel</a> </form> </div> {% endblock content %} But When I click on Add Button I got this errorenter image description here What is the solution of it -
I don't know why job.module_set.all is empty in modal
I don't know why job.module_set.all is empty in modal class... This is my model. class Job(models.Model): build_start_time = models.DateTimeField('build start time', default=default_start_time, blank=True) branch = models.CharField(max_length=100) def __str__(self): return '{}_{}'.format(self.branch, self.build_start_time) class Module(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) name = models.CharField(max_length=100) tag = models.CharField(max_length=100) hash_value = models.CharField(max_length=100) def __str__(self): return '{}_{}_{}'.format(self.name, self.tag, self.hash_value) This is part of my templates {% for job in latest_job_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ job.branch }}</td> <td>{{ job.build_start_time | date:'y-m-d H:i' }}</td> <td>{{ username }}</td> <td> {% for module in job.module_set.all|slice:":5" %} [{{ module.name }}] {% endfor %} </td> <td> <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#detailModal"> DETAIL </a> <!-- Detail Modal --> <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" data-backdrop="false"> <div class="modal-dialog modal-xl modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="detailModalLabel">{{ job.branch }} ({{ job.build_start_time }} {{ job.module_set.all }})</h4> Line 8. job.module_set.all is working propery(e.g. QuerySet([set1, ,set2]) but, Last Line is not working...(job.module_set.all is empty e.g. QuerySet([])) -
Unit/Functional Tests Vs Validators
I have recently started web development using Django. What confuses me the most that, why do we create tests for scenarios like "Check if password is provided", "Check if password is correct", "Check if a password is at least 8 characters long" etc. when we can do the same thing using validators in Django. Is there a specific advantage of using tests over validators? Thanks. -
define group from the current id in function based create view in django
i am trying to build chat website and in that only people in that group should see(thats not the problem). like we predefine user as request.user i want to definethe same group with id in address bar. till now created : homepage that has all group name , when click it gets current pk of group and render common template,in my views i need to define the group as id which i navigated. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', group.as_view(),name="group"), path('create/', views.create,name='create'), path('ajax/getusers',views.getusers,name='comments'), path('register/', views.register,name="register"), path('login/', views.login,name="login"), path('detail/<int:pk>', views.test,name="detail"), ] views def create(request,pk): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] group = request['pk'] message = comments(user=author,message=message,name=name,group=group) message.save() return HttpResponse('') no render template because i am using ajax just using the function models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.group_name} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' -
remove username field django auth
Im new to Django, im open to hear any aproach and suggestions. I want to extend CustomAccountAdapter on AllAuth and populate username with email. I already did it on CustomSocialAccount. class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) user.username = user.email return user Original class code def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User instance need not be completely valid and conflict free. For example, verifying whether or not the username already exists, is not a responsibility. """ username = data.get("username") first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") name = data.get("name") user = sociallogin.user user_username(user, username or "") user_email(user, valid_email_or_none(email) or "") name_parts = (name or "").partition(" ") user_field(user, "first_name", first_name or name_parts[0]) user_field(user, "last_name", last_name or name_parts[2]) return user I cant do the same on CustomAccountAdapter because populate is a bit diferent. def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username … -
Django Form does not save properly
I want to create a comment system. I can take username, doc_id, and comp_name, but I cannot get the comment_others. I think there is a problem saving the form. How can I fix it? views.py def ocr(request, id): pdf = get_object_or_404(Pdf, id=id) approval = ApprovalProcess(user_id=request.user, highest_rank=1) current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) if request.method == 'POST': form_2 = CommentForm(request.POST or None, instance=pdf) if form_2.is_valid(): comment_others = CommentFromOthers.objects.create( username=request.user, comp_name=userP[0].company, doc_id=pdf, ) comment_others.save() form_2.save() else: form_2 = CommentForm() comment_obj = CommentFromOthers.objects.filter(doc_id=pdf).order_by("-created_date") ..... models.py class CommentFromOthers(models.Model): comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) doc_id = models.ForeignKey(Pdf, on_delete=models.DO_NOTHING, null=True) comment_others = RichTextField(blank=True) created_date = models.DateTimeField(default=datetime.now()) username = models.ForeignKey(UserProfile, on_delete=models.CASCADE) forms.py class CommentForm(forms.ModelForm): comments = RichTextField class Meta: model = CommentFromOthers fields = ('comment_others',) And there are two forms on the same page. When I save this form, the other form disappears. Why it could be happening? if request.method == 'POST': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): form.save() ... approval.save() else: form = PdfRiskForm() -
ModuleNotFoundError and ImportError even beeing right
Hello, thanks for your time. i'm trying to import models on seeders.py. Can someone please tell me what am i doing wrong, i've done this a hundred times and tried every single way: from winners.models import Player or from ..models import Player models.py: from django.db import models class Player (models.Model): name = models.CharField(max_length=100) sex = models.CharField(max_length=9, choices=sex_choices) age = models.PositiveIntegerField() height = models.DecimalField(max_digits=3, decimal_places=2) weight = models.PositiveIntegerField() team = models.CharField(max_length=120) by the way i've just started on linux may i havent set a envy variable right? -
Pagination links appearing null after applying Custom Pagination in django rest framework
I used custom pagination as mentioned in Django rest framework. In that, I had to use my project name to give the path to CustomPagination, but every time it says module not found. Then I manually import the pagination file in my views. It did work but my pagination links are appearing null. I have posted the picture here below. My views: from .pagination import CustomPagination class ProductAPIView(ListAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter pagination_class = CustomPagination My pagination.py file class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data }) My settings file: # 'DEFAULT_PAGINATION_CLASS': 'RupseOnline.core.pagination.CustomPagination', 'PAGE_SIZE': 100, I have commented out the pagination class and imported it manually in views because it says module not found. -
Inherit Django application (a set of apps)
I have an architectural problem. My team have large Django DRF application (lets name it "portal-backend") combined of set of apps, not installed as a modules but created manually. The apps are: blogs, news, entries, adminapi, gallery, comments, events, ideas, microposts, reactions, moderation, profile, and so on (about 50 apps). Now I need to make some kind of "inheritance", use this product as a "base" in other team, and allow them to make changes in their nested classes. For example if they need to change class blogs.views.BlogViewSet, they can just inherit it by they own class. The "base" application must be installed with pip (if possible) or pulled from git (it's a single repo) So, the main portal-backend shouldnt be changed in other team, just used as a base and extended by inheritance Ideally my existing application should became some kind of high-level framework to create other portal-backends on the base of it with required modifications and additions on top of it. What variants I thought about: Split whole application into app-modules, put it into separate git repos, and install each app as a pip module. This method requires lots of work and has a problem that all apps are … -
how to share data between django server and python websocket server
I am writing a web app with Django in which I have to share some data with another python socket server running in parallel. I have tried using a common python file to store global variable. but since those server are two different processes it is not working. (I am not interested in using any database) -
QueryDict in Django
from django.http import QueryDict QueryDict('query=c++') Why the output is, <QueryDict: {u'query': [u'c ']}> Does querydict remove the + symbol from the string? I am using Python 2.7.17 and Django version 1.10.4. -
Django-Fetch Instagram post embedding using URL
I am making an app that requires me to take in user given Instagram URL and display the Instagram post on the HTML page. So far the only way I know is to go to an Instagram post and copy the Embed code from there manually. Is there a way to fetch the same embed code only using the URL? -
reload a page in django using ajax?
I am building a messaging app and i want to reload my page every 1 minute so that the user can see new messages if there is some i know how to do it in html but i wanna use ajax(i am not so good in it) to reload the page. here is my views.py: class MessagesView(LoginRequiredMixin,View): def get(self, request, chat_id): try: chat = Chat.objects.get(id=chat_id) if request.user in chat.members.all(): chat.message_set.filter(is_readed=False).exclude(author=request.user).update(is_readed=True) else: chat = None except Chat.DoesNotExist: chat = None return render( request, 'users/messages.html', { 'user_profile': request.user, 'chat': chat, 'form': MessageForm() } ) def post(self, request, chat_id): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = chat_id message.author = request.user message.save() return redirect(reverse('messages', kwargs={'chat_id': chat_id})) and my template is: {% extends 'profile/base.html' %} {% load tz %} {% block title %} Messages {% endblock %} {% block head %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <style> #form { position: fixed; bottom: 0; background-color:#f1f1f1; } .container { border: 1px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 1px; margin: 1px 0; } .container::after { content: ""; clear: both; display: table; } .darker { border-color: #ccc; background-color:#ddd; } .container img { float: left; max-width: 40px; height:40px; width: … -
None type object has no attribute django tenants
I wanted to a many to many field to the db, in a django tenants application getting the above error, the code is as follows @login_required() def create_tenant(request): subscription = Subscription.objects.get(user=request.user) if subscription.status == "active": if request.method == 'POST': form = ClientForm(request.POST or None, request.FILES or None) if form.is_valid(): logo = form.cleaned_data.get('logo') brand = form.cleaned_data.get('brand') seq_no = list(range(5000, 9000)) random.shuffle(seq_no) seq_no = seq_no.pop() schema_name = f'Domain{seq_no}' name = f'UID-{seq_no}' location = form.cleaned_data.get('location') tenant = Client(schema_name=schema_name, name=name, user=request.user, logo=logo, brand=brand, ) instance = tenant.save() for obj in location: print(obj) instance.location.set(obj) return redirect('create_domain') else: form = ClientForm() return render(request, 'form.html', {'form': form}) else: return redirect('home') models.py class Client(TenantMixin): name = models.CharField(max_length=100) brand = models.ForeignKey( Brand, related_name='gym_client', on_delete=models.CASCADE, blank=True, null=True ) location = models.ManyToManyField( Location, blank=True ) user = models.OneToOneField( User, related_name='clients', on_delete=models.CASCADE, blank=True, null=True ) I am getting selected locations as I can see it printing in terminal, the method I tried, I think usually works for many to many, don't know why it is throwing error. Looking for an advice, thank you -
How can I find total number of signups in a week?
I am using django build in User model have one-to-one relation with UserProfile model. I have to count number of signups in a week. How can I do this?. Thanks in advance for your addition. -
Get Dynamic Select option in Clone Node using Javscript
I'm trying to create a form where I'm giving dynamic select option i.e one select option will depend on another select option, as you can see in the Image below, if Gender is male and Child the age group is between 1-18 similarly for Adult its greater than 18. And By clicking Add member I'm cloning the whole Person div, but the script is not working for the cloned node and I'm only getting AgeGroup of the 1st div whose clone is created. I'm trying to build this form in Django if that helps. My code: document.getElementById('addMember').onclick = function() { var addOnDiv = document.getElementById('addon'); var clonedNode = addOnDiv.querySelector('.memberBody').cloneNode(true); addOnDiv.appendChild( clonedNode ); } ## for select $("select").change(function() { var selectedVal = $('#type').val(); var selectedGender = $('#gender').val(); console.log(selectedGender); console.log(selectedVal); if('Child' === selectedVal){ var childGroup = '<select name="h_ageGroup" class="custom-select"> <option value="" disabled="disabled" selected="selected">Choose option</option>........</select>'; $('#selectList').html(childGroup); } if('Adult' === selectedVal ){ var childGroup = '<select name="h_ageGroup" class="custom-select"> <option value="" disabled="disabled" selected="selected">Choose option</option> <option value=">18 Years"> >18 Years </option></select>'; $('#selectList').html(childGroup); } }); How can I get dynamic select on my cloned node too. Is there any other way through which I can achieve this ? -
SMTPServerDisconnected at /userprofileinfo/register/ please run connect() first
Login registration is working fine, but when I verify the user email I can't able to send the verification link to user to verify the email. It shows me above error that please run connect() first. Can someone help me to find out the error ... Views.py from django.shortcuts import render from userprofileinfo.forms import UserForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.views import View from django.contrib import messages from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .utils import account_activation_token from django.urls import reverse from django.contrib import auth @login_required def special(request): return HttpResponseRedirect("You are logged in, Nice!") @login_required def userlogout(request): logout(request) return HttpResponseRedirect(reverse('careforallapp:base')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('userprofileinfo:activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://'+current_site.domain+link send_mail( email_subject, 'Hi … -
Reverse for 'admin-color-product-map-edit' with arguments '('',)' not found. 1 pattern(s) tried: ['admin1/colorProductMap_edit/(?P<id>[0-9]+)$']
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys? views.py @login_required(login_url="admin-login") @user_passes_test(check_role_admin) def colorProductMap_edit(request, id): instance = ColorProductMapping.objects.get(color_p_map_id=id) print(instance.color_id) form = ColorProductMapForm(instance=instance) if request.method == 'POST': form = ColorProductMapForm(request.POST, instance=instance) if form.is_valid(): form.save() return redirect('/admin1/colorProductMap') else: form = ColorProductMapForm(instance=instance) return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance}) I properly partnered and connected with the following in my urls.py. urls.py path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"), forms.py class ColorProductMapForm(forms.ModelForm): class Meta: model = ColorProductMapping fields = ['color_id', 'prod_id'] models.py class ColorProductMapping(models.Model): color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True) color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") colorProductMap.html {% extends 'admin1/layout/master.html' %} {% block title %}Color Product Map{% endblock %} {% block main %} <h1> <center>Color Product Map</center> </h1> <div class="container"> <div class="row"> <div class="col-lg-2"></div> <div class="col-lg-10"> {%if colorProductMap_show%} <button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add Color Product Mapping </button> <div class="modal fade" id="modal-primary"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Color … -
Django | Same form multiple times on the same template
I have a project with a model called "List," and a model called "ListItem." There are multiple list items to each list. Here's what I'd like to do. I'd like the user to be able to create a new list with as many items as they deem necessary on one form. Here's the logic I have so far: models.py: class List(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class ListItem(models.Model): team_list = models.ForeignKey(List, on_delete=models.CASCADE) content = models.TextField() index = models.IntegerField() def __str__(self): return f"{self.team_list} [{self.index}]" forms.py: class NewListForm(forms.ModelForm): name = forms.CharField(max_length=50, label='Card Name') team = forms.ModelChoiceField(queryset=models.Team.objects.all()) class Meta: model = models.List fields = ['name', 'team'] class NewListItemForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea, label='Item', required=True) class Meta: model = models.ListItem fields = ['content'] views.py: def new_list(request): context = { 'title': 'New List', 'list_form': NewListForm, 'list_item_form': NewListItemForm, } if request.method == 'POST': list_form = NewListForm(request.POST) list_item_form = NewListItemForm(request.POST) if list_form.is_valid() and list_item_form.is_valid(): list_instance = list_form.save() list_item_instance = list_item_form.save(commit=False) list_item_instance.team_list = list_instance list_item_instance.index = 1 list_item_instance.save() messages.success(request, "List has been created!") return redirect('home') else: messages.error(request, "That list name is already taken") return render(request, 'lists/new_list.html', context) This works for creating 1 list and just 1 item. Ultimately, I'd like the user to … -
Django How to reuse a URL and View based on an input or state?
I currently have a url and a view to display my objects. Is it possible to create a new URL with the same view then just change the filter of objects without creating a new view? This is my view: path('search/', hrViews.hr_search, name='hr_search'), # Default path('search/with_changed_filter', hrViews.hr_search, name='hr_search'), # In here. This is as simple as I can be. -
Contacting another WebSocket server from inside Django Channels
I have two websocket servers, call them Main and Worker, and this is the desired workflow: Client sends message to Main Main sends message to Worker Worker responds to Main Main responds to Client Is this doable? I couldn't find any WS client functionality in Channels. I tried naively to do this (in consumers.py): import websockets class SampleConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): async with websockets.connect(url) as worker_ws: await worker_ws.send(json.dumps({ 'to': 'Worker' })) result = json.loads(await worker_ws.recv()) await self.send(text_data=json.dumps({ 'to': 'Client' }) However, it seems that the with section blocks (Main doesn't seem to accept any further messages until the response is received from Worker). I suspect it is because websockets runs its own loop, but I don't know for sure. The response { "to": "Client" } does not need to be here, I would be okay even if it is in a different method, as long as it triggers when the response from Worker is received. Is there a way to do this, or am I barking up the wrong tree? If there is no way to do this, I was thinking of having a thread (or process? or a separate application?) that communicates with Worker, and uses channel_layer to …