Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django set ManytoManyField to default user model
I need to set a manytomany relation to default django user table.Is there any way to implement it rather than using AbstractUser method of django (extending User Model)? -
Unable to Pass SQL Object From Python to Javascript in Django
I am trying to send a single SQL object to my Javascript in Django using json.dumps however I get the error: Object of type List is not JSON serializable when I run the following code: user_data = List.objects.get(user=request.user.username) context['list'] = json.dumps(user_data) return render(request, "template.html", context) The SQL Object has three fields, the first is a username and the other two are lists. Please can you tell me how to convert this to JSON correctly. -
Display group name of user with a template
For the staff members of my website, I am displaying a list of all users registered and I want to display their group. It's working except that I get <QuerySet [<Group: UserGroup>]> instead of UserGroup. Tried to use group = form.cleaned_data['group_name'] but I get this error: invalid literal for int() with base 10: 'Viewers' at user.groups.add(group). forms.py: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) views.py: @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) # Display all active users in a table class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView): template_name = 'accounts/display_users.html' group_required = ['Staff'] queryset = User.objects.filter(is_active=True) display_users.html: {% block main %} <table class="table"> <thead class="thead-dark"> <p> <tr> <th scope="col"># id</th> <th scope="col">Username</th> <th scope="col">Group</th> <th scope="col">Email address</th> <th scope="col">First name</th> <th scope="col">Last name</th> </tr> </thead> {%for instance in object_list%} <tbody> <tr> <td>{{instance.id}}</td> <td><a href = "{% url 'accounts:update' instance.id %}">{{instance}}</a></td> <td>{{instance.groups.all}}</td> <td>{{instance.email}} … -
How to update a single field in a model using UpdateAPIView from Djangorestframework?
I'm learning generic views and creating some Api's. How can I update the field: "mobile" from Model :"Contacts"? I want to get the user id from url(mobile/update/user_id). But while creating the queryset its not working. I want to do something like mentioned here(#queryset = Contacts.objects.filter(id=Usertab.objects.filter(id=self.kwargs['id']).first().contact.id)) '''python class UpdateMobileAPIView(generics.UpdateAPIView): queryset = Contacts.objects.filter(pk=Usertab.objects.all()) serializer_class = ContactsSerializer lookup_field = 'pk' def update(self,instance,request): instance = self.get_object() serializer= self.get_serializer(instance,data=request.data,partial=True) if serializer.is_valid(): serializer.save() return Response({"message":"mobile number updated successfully"}) else: return Response({"message":"failed"}) ''' These are models class Contacts(models.Model): mobile = models.IntegerField(null=False) Landline = models.IntegerField(null=False) whats_app = models.IntegerField(null=False) class Usertab(models.Model): username = models.CharField(max_length=255,null=False,blank=False) address = models.CharField(max_length=255,null=False,blank=False) pin_code = models.CharField(max_length=255,null=False,blank=False) contact = models.ForeignKey(Contacts,related_name="contacts_user") class Email(models.Model): user = models.ForeignKey(Usertab,related_name="user_email") email = models.CharField(max_length=255,null=False,blank=False) is_verified = models.BooleanField(default=False) ''' '''this is the serializer class ContactsSerializer(ModelSerializer): class Meta: model = Contacts fields = '__all__' def update(self, instance, validated_data): instance.mobile = validated_data.get('mobile', instance.mobile) instance.save() return instance ''' TypeError: update() got an unexpected keyword argument 'pk' -
Editing an existing form
This is what my merchant_edit is. If i dont pass an args into form.save(), I get this error "Django - missing 1 required positional argument: 'request'", so I pass 'request' as an args i.e form.save(request) to escape from that error. Now my merchant_edit view creates a new data i.e new data are added instead of them to be edited, how can I make edit an exisitng form instead of creating a new form. And I get pointed to the exact pk url's i.e http://127.0.0.1:8000/merchant/10/edit for edit but it creates a new form and a new pk for the new data. def merchant_edit(request,pk): template_name = 'merchants/edit.html' merchant=Merchant.objects.get(pk=pk) if request.method=='POST': form=CreateMerchantForm(request.POST, instance=agent) if form.is_valid(): form.save(request) messages.success(request,'data Updated Successfully.') return HttpResponseRedirect(reverse_lazy('merchant')) else: form=CreateMerchantForm(instance=agent) return render(request, template_name, {'form':form}) urls.py path('merchant/<int:pk>/edit', views.merchant_edit, name='merchant_edit'), -
How to store KMeans object in Django database?
I am storing a tree in the Django database, whose nodes each contains a K means object. How do I store a K means object in Django data field? Also, for saving a tree to a database, for the left and right of the node is it possible to use foreign keys which point back to the same database? Thanks for your help. I saw something called pickle which saves to a machine learning model to a file and loads it later, but was wondering if there's another way of serializing. -
How to iterate properly in django template with this specific data
I have these variables called: srodki (simple list with 2 values), roles (array of arrays with some roles) and formsets (array of arrays with some formsets) i've separated them this way because I want the template to look like this: srodki.name role formset The thing is, that my codes iterates like this: srodki.name role formset formset These formsets have certain initial values passed to them, but instead of outputting the correct formset it just shows both of them because i dont know hot to iterate 2 of these at the same time inside another for loop (that is looping through srodki) I though about use of dictionaries but couldn't implement it correctly My views: def EventSily(request, event_id): event = Event.objects.get(pk=event_id) srodki = SiSvalue.objects.filter(event=event) roles_count = 0 SilyFormset = modelformset_factory(EventWork, fields=('event', 'role', 'worker', 'start_time', 'end_time')) roles = [] formsets = [] for each in srodki: roles_array = [] formsets_array = [] srodki_sis = each.sis role_srodka = Roles.objects.filter(srodek=srodki_sis) for role in role_srodka: roles_array.append(role.name) roles_count += 1 print(role) formset = SilyFormset(initial=[{'event' : event, 'role' : role}]) formsets_array.append(formset) roles.append(roles_array) formsets.append(formsets_array) if request.method == "POST": for formset in formsets: formset = SilyFormset(request.POST) mylist = zip(srodki, roles, formsets) context = { 'event' : event, 'mylist' : … -
fetch data with condition
I am doing a movie booking project in which i want to time of particular cinema def movies(request, id): cin = Cinema.objects.filter(shows__movie=id).distinct() movies = Movie.objects.get(movie=id) show = Shows.objects.filter(movie=id) context = { 'movies':movies, 'show':show, 'cin':cin, } return render(request, "movies.html", context ) movies.html HTML file can i do something to get time of cinema <div class="card"> <img class="card-img-top" src="{{movies.movie_poster.url}}" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">{{movies.movie_name}}</h4> <p class="card-text">{{movies.movie_rating}}</p> </div> <ul class="list-group list-group-flush"> {% for cin in cin %} <li class="list-group-item"><b>Cinema {{cin}}</b></li> {% for show in show %} <li class="list-group-item"> Time : {{show.time}}</li> {% endfor %} {% endfor %} </ul> </div> models.py file so you can get detail of my database structure ( i just want to fetch movie with its show but based on cinema separate ) class Cinema(models.Model): cinema=models.AutoField(primary_key=True) role=models.CharField(max_length=30,default='cinema_manager') cinema_name=models.CharField(max_length=50) phoneno=models.CharField(max_length=15) city=models.CharField(max_length=100) address=models.CharField(max_length=100) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.cinema_name class Movie(models.Model): movie=models.AutoField(primary_key=True) movie_name=models.CharField(max_length=50) movie_des=models.TextField() movie_rating=models.DecimalField(max_digits=3, decimal_places=1) movie_poster=models.ImageField(upload_to='movies/poster', default="movies/poster/not.jpg") def __str__(self): return self.movie_name class Shows(models.Model): shows=models.AutoField(primary_key=True) cinema=models.ForeignKey('Cinema',on_delete=models.CASCADE) movie=models.ForeignKey('Movie',on_delete=models.CASCADE) time=models.CharField(max_length=100) seat=models.CharField(max_length=100) price=models.IntegerField() def __str__(self): return self.cinema.cinema_name +" | "+ self.movie.movie_name +" | "+ self.time Output i am getting now (image attached) -
AWS django Invalid HTTP_HOST header
I'm depolying my app onto Elasticbeanstalk. When I visit the url, I get Invalid HTTP_HOST header:'mysite.com'. I've added my url to my settings.py. This is my settings file: ALLOWED_HOSTS = ['mysite.com/','.mysite.com/', '127.0.0.1:8000', '127.0.0.1', 'localhost', 'localhost:8000', '13.59.177.101', '127.0.0.1'] This is my python.config file: `container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate &&python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "project.settings" PYTHONPATH: "$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: "/opt/python/current/app/project/wsgi.py" StaticFiles: "/static/=www/static/" packages: yum: postgresql95-devel: []` My code works locally without any problem. Not sure what to do. Please help! -
Django deserialize two fields into one using custom field
Hi I am trying to patch or update a data in Django using serializers. I want to make use of Custom Field to deserialize a PointField from a data with latitude and longitude. I want to parse longitude and latitude from my data and pass it to a Point object and in turn save it my model's PointField(). #test.py from django.test import Client class CaptureTests(TestCase): def test_patch(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'adminpass'}) location = { "type": "Point", "coordinates": [120.20, 18.20, 300.20] } included_meta = { 'location': location, 'processor': 'L1B' } response = c.patch( '/captures/CAM-01/', data=json.dumps(included_meta), content_type='application/json') response = c.get("/captures/CAM-01/") results = response.json() print("RESULTS!", results) #serializers.py from django.contrib.gis.geos import Point class PointFieldSerializer(serializers.Field): # Point objects are serialized into "Point(X, Y, Z)" notation def to_representation(self, value): return f'{"type": "Point", "coordinates": [{value.longitude}, {value.latitude}, {value.altitude}]}' # return f"{"type": "Point", "coordinates": [%d, %d, %d]}" % (value.longitude, value.latitude, value.altitude) def to_internal_value(self, data): data = json.loads(data) location = data['location']['coordinates'] longitude = location[0] latitude = location[1] altitude = location[2] return Point(float(longitude), float(latitude), float(altitude)) class CaptureUpdateSerializer(serializers.ModelSerializer): location = PointFieldSerializer class Meta: model = Capture fields = '__all__' class CaptureViewSet(CaptureFiltersMixin, viewsets.ModelViewSet): def partial_update(self, request, capture_id=None): data = request.data print("DATA!", data) # {'location': {'type': 'Point', 'coordinates': … -
Error in vobject file when i use ajax form uploaded file in my python code
I am uploading vcf file by django form and want to convert into vobject but it will give error. When I have tried with take following code it will work... file = open('test.vcf', 'r') but in belowed code it is not working... file = request.FILES.get('vcf_file') with file as f: vc = vobject.readComponents(str(f.read()).encode('utf-8')) vo = next(vc, None) while vo is not None: fname = vo.contents.get('fn')[0].value email = vo.contents.get('email')[0].value if vo.contents.get('email') else '' numbers = [] if vo.contents.get('tel'): for v in vo.contents['tel']: no = v.value.replace("-", "") if no not in numbers and no[-10:] not in numbers[-10:]: numbers.append(no) print(fname, ', ', numbers, ', ', email) vo = next(vc, None) I except output like Pravin , ['+91971282123'] , VH Patel , ['+918511123341'] , but it through following error: File "/home/vahta/Desktop/phonebook/phonebook/views.py", line 151, in import_vcf vo = next(vc, None) File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 1101, in readComponents vline = textLineToContentLine(line, n) File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 925, in textLineToContentLine return ContentLine(*parseLine(text, n), **{'encoded': True, File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 813, in parseLine raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber) vobject.base.ParseError: At line 1: Failed to parse line: b'BEGIN:VCARD\r\nVERSION:3.0\r\nN:vdfn;Pravin;;;\r\nFN:Pravin vdfn\r\nTEL;TYPE=CELL:+919712823033\r\nTEL;TYPE=CELL:+919712823033\r\nEND:VCARD\r\n -
I need to implement rating feature , in which listing space can be rate , i need urgent help ,kindly help me
i need to implement rating feature in my fyp project, to rate listing kindly help me i dont know how to implement rating with stars. tommorow is my submission kindly help . i tried many api but didnot work for me class Comment(models.Model): RATING_RANGE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) listing = models.ForeignKey (Listing, on_delete=models.CASCADE,related_name='rates') user = models.ForeignKey (User, on_delete=models.CASCADE,default=1 ) content = models.TextField(max_length=250) created_date = models.DateTimeField(auto_now_add=True) approved_comment = models.BooleanField(default=False) rating = models.IntegerField(choices=RATING_RANGE, default='3') forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content','rating'] widgets = { 'content': Textarea(attrs={ 'class' : 'input', 'class' : 'form-control', 'placeholder': ' Enter comment here !!', 'cols': 100, 'rows': 5}), } listing.html <div class="comments-content"> <div class="row"> <div class="col-lg-8 col-sm-12" ><h2> Reviews ( {{ comments.count }} ) </h2> </div> </div> <div class="row" style="margin-bottom:10px;"> <div class=" col-sm-12" > <div class=" read-more-content-wrapper"> {% for comment in comments %} {% if comment.user.profile.photo.url is not None %} <span> <img src=" {{comment.user.profile.photo.url}}"> <p class="mb-0"> {{comment.content}}</p> <p class="mb-0"> Rating From 5 : {{comment.rating}}</p> By <cite title="Source Title">{{comment.user | capfirst}}</cite></span> <hr class="col-lg-12 col-sm-12 no-gutter"> <p class="mb-0"> {{comment.content}}</p> <p class="mb-0"> Rating From 5 : {{comment.rating}}</p> By <cite title="Source Title">{{comment.user | capfirst}}</cite></span> <hr class="col-lg-12 col-sm-12 no-gutter"> {% … -
How to inherit a variable from a class?
I have a two class. I need to inherit the technology field and redefine it in the child class. class SkillGroupCreateForm(forms.ModelForm): def __init__(self, *args, employee_pk=None, **kwargs): super(SkillGroupCreateForm, self).__init__(*args, **kwargs) self.fields['technology'].required = False if employee_pk is not None: self.fields['technology'].queryset = Technology.objects.exclude(skill__employee_id=employee_pk) My code class SkillCreatePLanguageForm(SkillGroupCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = self.fields['technology'].filter(group__name="Programming language") gives out an error ModelChoiceField' object has no attribute 'filter' -
How to add E-mail OTP generation and verification in django
Unable to Generate Email OTP verification in django through serializer I want to generate an otp that will be sent on Email and verified such that my user would be verified -
Django: Is it possible to create two objects with one CreateView?
Assume I have the two models Thread and Post. There exists a circular reference: A thread has a field called startpost (Post) and each Post has a reference to a Thread. Now, when a user wants to create a new Thread one has to create both a Thread and Post object. I'd like to use a ThreadCreateView, but I'm not sure how I can do it. A CreateView can only have one model in the model property. Also I wonder if I can use a ModelForm or if I have to create a custom Form with fields of both Post and Thread, which means that I would have to duplicate the constraints (that would be automatically created by a ModelForm, like max_length for a field). So, I wonder what's the best way to tackle that problem. Because of the cirucal reference the creation of the objects definitely has to happen in a transaction, but that's something else. -
Problem importing module for GRAPHENE setting 'SCHEMA' in Django 2.2
I am new to django(installed version 2.2 in my virtualenv) and graphql. I tried to follow the instructions for setting up graphql in django from the following site https://docs.graphene-python.org/projects/django/en/latest/installation/ When I try to run the server with the url http://127.0.0.1:8000/graphql/ I get the following error. ImportError at /graphql/ Could not import 'django_root.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'django_root'. I followed the instructions carefully but I am unable to get this right. Please help. I checked similar questions but it didn't help. -
How to get data from multiple models in queryset utilizing 'select_related'?
I am trying to get combined queryset for two models, basically a LEFT JOIN for two tables. I read multiple answers on how to perform LEFT JOIN on querysets and I found that the easiest way is via select_related, so that is what I did. When I print the raw query, it looks good, it contains information from both tables (both models). However the returned queryset contains only the information from the first model. I read that this is a default and it can be overridden by get_query. And this is where I am lost, because the documentation provides get_query description only for class based view and so far I worked only with function based views. These are my models: class WorkPlace(models.Model): workplace = models.TextField(unique=True) nickname = models.TextField(null=True) def __str__(self): return f'{self.workplace}' class Status(models.Model): workplace = models.OneToOneField(WorkPlace, to_field="workplace", db_column="workplace", on_delete=models.SET_NULL, null=True) status = models.TextField() def __str__(self): return f'{self.status}' This it the view: def work_place_list_view(request): qs1 = WorkPlace.objects.select_related('status') print(qs1.query) context = {"workplace_list": qs1, "title": "Seznam pracovišť"} template_name = 'megavisor/workplace_list.html' return render(request, template_name, context) This is the raw query from console: SELECT "megavisor_workplace"."id", "megavisor_workplace"."workplace", "megavisor_workplace"."nickname", "megavisor_status"."id", "megavisor_status"."workplace", "megavisor_status"."status" FROM "megavisor_workplace" LEFT OUTER JOIN "megavisor_status" ON ("megavisor_workplace"."workplace" = "megavisor_status"."workplace") The output is the … -
django - angular handling urls
I have created django api end-points for my app which will be hosted on google firebase and the frontend code will be all angular. While learning some stuff about integrating React with django I found out that django needs to be able to handle all the urls which react provides. That was easy for me because I had the code on my virtual environment together with the templates and static files. But regarding the real angular app I will not have the code on my side. Can anyone give me a general overview about these concepts. Thank you! -
How to add title & description when documenting with core api using manual schema on django rest framework
I am using the core API library in documenting the following class view as shown below using a manual schema. How do I add the title and description so that they appear? As you can see from the screenshot below the query parameters defined from the manual schema only appear in the documentation. Class View class RecieptListAPIView(APIView): schema = schemas.ManualSchema(fields=[ coreapi.Field( "year", required=True, location="query", schema=coreschema.String( description="This is the year payed." ) ), coreapi.Field( "business_id", required=True, location="query", schema=coreschema.String( description="This is the unique business id of a business." ) ) ]) """Show reciept list. /api/sbp/receipts/?year=2018&business_id=1432658 """ queryset = Receipt.objects.all() serializer_class = ReceiptSerializer def get(self,request,format=None): """Return a list of reciepts.""" query = self.request.GET.get("business_id") year = self.request.GET.get("year") reciepts = Receipt.objects.filter(bill__business__business_id=query, bill__calender_year=year)[0] serializer = ReceiptSerializer(reciepts,many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) Output -
How to change the default registration in django
I have used django's default registration. I want to edit this forms because it's appearance does not look very good to me. I want to convert the instructions into tool tip or something better looking how can I do it?I am new to django html Register {% csrf_token %} {{ form.as_p }} Register -
Using fixtures with pytest: How to share fixtures and use their parameters in different functions
I am struggling with setting up my fixtures correctly in pytest. I always get a missing 1 required positional argument: error. This is what I am trying: @pytest.mark.django_db class TestCreate: @pytest.fixture(scope='class') def user(self): username = 'testuser' password = 'mypassword' user_data = { 'username': username, 'password': password, } return user_data def setup(self, user): """Setup for tests to create user and project """ user_d = user print(user_d) username = user_d['username'] Basically I only want to access the dictionary in from my fixture. But I get E TypeError: setup() missing 1 required positional argument: 'user' I seems Pytest doesn't have access to my fixtures? Help is very much appreciated! Thanks in advance -
Django url template tag not resolving when set through jquery
I've created a comment system for blog posts in Django (the comments are stored in a Comments model) in which the author of the post or comment can delete a comment by clicking on the delete link below the comment, which results in a modal pop up asking for confirmation. {% for comment in comments %} <!-- Display comment --> <a href="#" onclick="getCommentId(this)" data-id="{{ comment.id }}" data-toggle="modal" data-target="#exampleModalCenter">delete</a> {% endfor %} <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Delete</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete the comment? </div> <div class="modal-footer"> <form id="confirm-delete-form" action="" method="POST"> {% csrf_token %} <button id="confirm-delete-btn" class="btn btn-danger" type="submit">Yes, Delete</button> </form> <button class="btn btn-secondary" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> Corresponding views.py and urls.py sections: class CommentDeleteView(DeleteView): model = Comments success_url = '/' path('comment/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete') I'm dynamically setting the action attribute of the form in jquery when delete is clicked to pass the unique comment id: function getCommentId(comment) { var comment_id = $(comment).data("id"); var url = "{% url 'comment-delete' " + comment_id + " %}" $("#confirm-delete-form").attr('action', url) } But when … -
Access to XMLHttpRequest at 'localhost:8000' from origin 'localhost:3000' has been blocked by CORS
I'm working on a project with Django Rest Framework as back-end and React as front-end. When I set a session variable initially in some function/view and later when I try to access the different view through axios call and in that view if I try to access session variable which i created previously, I get KeyError. Session doesn't seem stored. I googled I got the similar issue which I'm facing. Django rest framework Reactjs sessions not working I followed the process by adding { withCredentials: true } in axios call. Now i'm getting different error. Now the issue is not able to access the backend. I get an error saying Access to XMLHttpRequest at 'http://127.0.0.1:8000/url/' from origin 'http://localhost:3000' has been blocked by CORS policy Again I googled the issue which i'm getting and found that I've to add CORS_ORIGIN_WHITELIST in the django settings.py I have added CORS_ORIGIN_WHITELIST like this CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://127.0.0.1:3000' ) Still i'm facing the same issue. I don't know whats going wrong. Can any one please help me on this issue. Thank you. -
Editing view for combined form and inlinel_formset
I have been trying to create an editing view that allows me manage both parent and child models using an inline formset based in the documentation here From what I can appreciate the formset doesn't validate. I did try and change it so that instead of validating the entire formset it iterated through each individual form in the formset and validated them individually. This did allow me to add items to the formset but not delete them. At the moment the code results in "didn't return an HttpResponse object. It returned None instead" value error as the redirect is in the If valid statement and so if that does not result in true there is no other redirect to fall back on. Models class Shoppinglist(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=2000) created = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='lists', on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=80, unique=True) amount = models.IntegerField(default=1) shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE) def __str__(self): return self.name URL urlpatterns = [ url(r'^shoppinglists/(?P<pk>\d+)/edit/$', views.shoppinglist_edit, name='shoppinglist_edit'), ] View def packlist_edit(request, pk): try: shoppinglist = Shoppinglist.objects.get(pk=pk) except ShoppingList.DoesNotExist: raise Http404 ItemInlineFormset = inlineformset_factory(Shoppinglist, Item, extra=1, fields=('name', 'amount')) if request.method == "POST": form = ShoppinglistForm(request.POST, instance=shoppinglist) formset = … -
Is it just not possible to have a celery server respond immediately to a message?
I have several celery servers with one worker each. The workers are busy doing long (8hr; I can't split it up) tasks. I want to be able to tell each server to do something immediately; but it looks like that's genuinely not possible - broadcast would put a task to be executed after the current one finishes, I believe?