Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at / relation does not exist
I can not find answer in other places. (Sorry for asking again but) what is wrong? Did anyone have such an error? ProgrammingError at /register/ relation "user_user" does not exist LINE 1: SELECT (1) AS "a" FROM "user_user" WHERE "user_user"."userna... I extended user abstract model and error saying no relation When i extend user in sqlite3 no errors such this but postgre is full databse error class User(AbstractUser): social_username = models.CharField(max_length=100, null=True, blank=True) views.py def registration(request): if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) messages.success(request,'You were successfully registered %s' % user.first_name) return HttpResponseRedirect('/') messages.error(request, 'Something went wrong while authenticating') return render(request, 'project/register.html', {'form': form}) else: form = RegisterUserForm() return render(request, 'project/register.html', {'form': form}) settings.py AUTH_USER_MODEL = 'user.User' -
Django Change Profile Picture with a button
I'm currently trying to change the user profile picture using a simple button! Here is my work so far: views.py class UserProfileView(View): form_class = UpdateCustomUserPictureForm template_name = "accounts/user_profile.html" def get(self, request, *args, **kwargs): form = self.form_class(instance=request.user) context = { 'form': form, 'user_reviews': request.user.reviewed.all() } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): pass template <div class="image-container employee-image circle" style="max-width:150px; max-height:150px; margin:0 auto"> <img class="image" style="height:100%; width:100%; object-fit:contain" src="{{ user.profile_picture.url }}" alt=""> <div class="overlay"> <a class="text" style="text-decoration:none" href=""><font size="2rem">Modifica</font></a> </div> </div> forms.py class UpdateCustomUserPictureForm(forms.ModelForm): profile_picture = forms.ImageField( widget=forms.FileInput(attrs={'class': 'form-control'}), required=False ) class Meta: model = User fields = ('profile_picture',) def __init__(self, *args, **kwargs): super(UpdateCustomUserPictureForm, self).__init__(*args, **kwargs) self.fields['profile_picture'].label = "Immagine del profilo" How can I upload and change the picture by clicking on "Modifica"? This is the result i want to obtain: -
Web Frameworks: Frontend vs Backend
I'd like to know what characterizes/differentiates a frontend web framework from a backend web framework. For instance, Django is a backend framework while Angular is a frontend framework, but why? I can make an entire application using Django, so why is it not considered a frontend framework too? -
Template form does not render in Django
I have a form that I want to display. It looks like this: #the template to be filled with the form: #base.html {% load staticfiles %} <html> <head><title>{% block title %}{% endblock %}</title></head> <body>{% block content %}{% endblock %}</body> </html> The concrete page: #home.html {% extends 'base.html' %} {% block title %}Main{% endblock %} {% block content %} <h2>Home page</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} The VIEW #views.py def home(request): context = locals() template = 'home.html' return render(request, template, context) The URLs: from django.conf.urls import url from .views import home as home_view urlpatterns = [ url(r'^home/$', home_view, name='home'),] This does not draw the {{ form.as_p }} it only draws the submit buttonAny ideas why? -
Filter on variable of ManyToMany-field inside Django Template
I have a job-object and a content-object. A job object gets created when a user wants to retrieve a set of content-objects in exchange for credits. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) class content(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) job_id_list_not_provided = models.ManyToManyField(JobId , related_name='JobIdFailed', blank=True) free_content = models.CharField(max_length=500, null=True, blank=True) paying_content = models.CharField(max_length=500, null=True, blank=True) For all content-objects part of the job, the JobId-object is added to the job_id_list - not keeping credit levels in mind. Different user can all run multiple jobs on the content objects. For too-big jobs exceeding the credit amount of the user, the content-objects that would push the credit level below zero, get also the JobID-object added to the job_id_list_not_provided field of the content-object. For a a specific user, we can retrieve the two sub-sets of found and not-found content-objects with following queries: views.py: found_results_list = results_list.filter(job_id_list_not_provided__user= None).distinct() not_found_results_list = results_list.filter(job_id_list_not_provided__user=request.user).distinct() My challenge: Result lists are over 100-objects in size, so I would like to use pagination to get a nice view on my page When not considering pagination, I could simply pass the 2 lists (found and not found) and loop over each list with a template … -
Django 2.0 - DateArchiveView date object for template
My app has ArchiveIndexView, YearArchiveView, MonthArchiveView and DayArchiveView. Except in ArchiveIndexView, I wanna add a Back link which will point back to its successor in all the views. So in the template of MonthArchiveView, I did it like this: <a href="{% url 'year_archive' date_list.0.date.year %}">Back</a> which would point back to YearArchiveView. But in DayArchiveView, there is no date_list attribute as of Django 2.0 documentation so how can I implement date object to be used in the template? -
django like button counting irregularly
I have a django application where I implemented a like button for posts posted on the blog. I recently discovered that when ever a like button is clicked by a registered user, the like increases exceedingly. Instead of the number of likes to get increased by 1 it increases by maybe 90+ and when the button is clicked agin for it to change to unlike it still increases so the like function becomes uneven. Below is my code for the like function Html {% with total_likes=obj.likes.count likes=obj.likes.all %} <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ obj.id }}" data-action="{% if request.user in likes %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} like {% else %} unlike {% endif %} </a> JQuery <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "posts:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // … -
DRF annotate Count on many-to-many through table gives more occurrences than when you use _set.all().count()
I have these models: class Topic(BaseModel): name = models.CharField(max_length=60) public_name = models.CharField(max_length=60, blank=True, null=True) class Content(BaseModel): title = models.CharField(max_length=120) series = models.CharField(max_length=120, blank=True, null=True) season = models.CharField(max_length=45, blank=True, null=True) episode = models.CharField(max_length=45, blank=True, null=True) tags = models.ManyToManyField(tags_models.Tag, through='ContentHasTags') topics = models.ManyToManyField(topics_models.Topic, through='ContentHasTopics') class ContentHasTopics(BaseModel): content = models.ForeignKey(Content) topic = models.ForeignKey(topics_models.Topic) order = models.IntegerField(default=99) class Meta: unique_together = ('content', 'topic',) ordering = ('order',) The problem I have is that if I use the next function: @property def get_contents_count(self): return self.contenthastopics_set.all().count() In many cases I have 7 as a result (and is true), but when I use the annotate query like this for Django Rest Framework (in the viewset), it gives me like 28 results, some other topics have 5 contents using the _set.all().count(), but annotate gives me 10 as a result, and so on. queryset = models.Topic.objects.all().annotate( themes_count=Count('themehastopics') ).annotate( contents_count=Count('contenthastopics') ).annotate( tags_count=Count('topichastags') ) How is the right way to annotate the query with the Count correctly added? -
Django save multiple view variables
I'm trying to save URL parameters to my model. Already tried many things and currently getting argument error. Can't find proper documentation on this most likely because I am not sure what the proper search term is. All I need to do is save webhook POST to my URL. I will use @require_POST decorator to require POST only. Atm this is not the issue. The issue is simply saving the webhook. models.py from django.db import models from django.contrib.auth.models import User class Webhook(models.Model): clientAccnum = models.CharField(max_length=120, blank=True) clientSubacc = models.CharField(max_length=120, blank=True) eventType = models.CharField(max_length=120, blank=True) eventGroupType = models.CharField(max_length=120, blank=True) subscriptionId = models.CharField(max_length=120, blank=True) time_stamp = models.DateTimeField(blank=True) time_stamp_local = models.DateTimeField(blank=True) views.py def webhook(request): template_name = 'payment/index.html' hook = Webhook.save() hook.client_acc_num = request.GET.get('clientAccnum') hook.client_sub_acc = request.GET.get('clientSubacc') hook.event_type = request.GET.get('eventType') hook.event_group_type = request.GET.get('eventGroupType') hook.sub_id = request.GET.get('subscriptionId') hook.time_stamp = request.GET.get('timestamp') hook.time_stamp_local = timezone.now() hook.save() return render(request, template_name) -
Django admin TabularInline disable fields based on values
I am looking to disable fields in Django Admin TabularInline forms. My model has an optional end_date field which should, if set disable the input fields to avoid further modifications of values. Currently I tried modifying get_formset, but I am unable to get the values to finally disable fields using e.g.: formset.form.base_fields['contract_number'].disabled = True I am using the following code: class ServerLicenseInline(admin.TabularInline): model = ServerLicense autocomplete_fields = ('contract_number',) ordering = ('start_date', 'end_date') extra = 0 can_delete = False def get_formset(self, request, obj=None, **kwargs): formset = super(ServerLicenseInline, self).get_formset(request, obj, **kwargs) ... I was looking in obj and formset to find the values but without chance right now. Does someone have an idea how to achieve this? Thanks! -
django tables2 export to xlsx: How to set exported filename using FBV?
Django==1.11.7 django-tables2==1.10.0 tablib==0.11.2 Using function based views, how to set the exported filename? The tables 2 documentation gives a solution for class based views, but is not clear on function based views: http://django-tables2.readthedocs.io/en/latest/pages/export.html?highlight=function%20based%20views It mentions an "export_name", but where does this need to be set? Trying this: def export_payment_list(request): _table = PaymentTable4Export(Payment.objects.all().order_by('-payment_date')) RequestConfig(request).configure(_table) exporter = TableExport('xlsx', _table) return exporter.response('table.{}'.format('xlsx'), filename='my_test') ... results in an error: Exception Type: TypeError Exception Value: response() got multiple values for argument 'filename' Thank you for your help -
Fabric: executing makemigrations & migrate raises Secret Key Error
I'm working on a fabfile.py to stop repetition and deploy automatically. I'm using the prefix("workon vpenv"): provided by fabric but here is the problem: when running git pull everything works well, but when I run run("python manage.py makemigrations --settings=config.settings.production") I get the following error: [venuepark.com] run: python manage.py makemigrations --settings=config.settings.production [venuepark.com] out: Traceback (most recent call last): [venuepark.com] out: File "manage.py", line 22, in <module> [venuepark.com] out: execute_from_command_line(sys.argv) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line [venuepark.com] out: utility.execute() [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 307, in execute [venuepark.com] out: settings.INSTALLED_APPS [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ [venuepark.com] out: self._setup(name) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup [venuepark.com] out: self._wrapped = Settings(settings_module) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ [venuepark.com] out: mod = importlib.import_module(self.SETTINGS_MODULE) [venuepark.com] out: File "/home/tony/.virtualenvs/vpenv/lib/python3.6/importlib/__init__.py", line 126, in import_module [venuepark.com] out: return _bootstrap._gcd_import(name[level:], package, level) [venuepark.com] out: File "<frozen importlib._bootstrap>", line 994, in _gcd_import [venuepark.com] out: File "<frozen importlib._bootstrap>", line 971, in _find_and_load [venuepark.com] out: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked [venuepark.com] out: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked [venuepark.com] out: File "<frozen importlib._bootstrap_external>", line 678, in exec_module [venuepark.com] out: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [venuepark.com] out: File "/home/tony/vp/vp/config/settings/production.py", line … -
Django Admin Copying an Object and Prompting User for Updating Fields
I'm currently trying to set up an action where admins can copy an object. I was using the following code as an example for building out this functionality: from django.contrib import admin from course_tracker.course.models import SemesterDetails import copy def copy_semester(modeladmin, request, queryset): for sd in queryset: sd_copy = copy.copy(sd) sd_copy.id = None sd_copy.save() for instructor in sd.instructors.all(): sd_copy.instructors.add(instructor) for req in sd.requirements_met.all(): sd_copy.requirements_met.add(req) for attr_name in ['enrollments_entered', 'undergrads_enrolled', 'grads_enrolled', 'employees_enrolled', 'cross_registered', 'withdrawals']: sd_copy.__dict__.update({ attr_name : 0}) sd_copy.save() copy_semester.short_description = "Make a Copy of Semester Details" My problem is that I have a few fields that need to be unique, and so ideally I'd like to prompt the user with popups or something where they can add in titles or descriptions that are necessary for these unique fields. How can you add this in Django? Or would I need to utilize JavaScript for this? -
Django Rest Framework - authentication_classes by method in viewsets
I want to disable authentication on creation in my UserViewSet, so that even non authenticated user can create an account. I'm using django-oauth-toolkit to authenticate in my application, and I use their authentication class as default in my settings (which is great) I have tried to use the @authentication_class decorator (https://stackoverflow.com/a/39717881/5438372), but it doesn't seem to work with ModelViewSet And I also tried to override the get_authenticator method, in the same spirit as this : Django rest framework permission_classes of ViewSet method, but ViewSet.action doesn't seem to be available at authentication. How can I do this ? I there something wrong with my approach ? Here is my code : <models.py:> class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScope,) lookup_field = 'username' def get_queryset(self): current_user = self.request.user if current_user.is_staff: user_set = User.objects.all() else: user_set = User.objects.filter(username=current_user.username) query = self.request.query_params.get('q', None) if not query: return user_set return user_set.filter( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) <settings.py:> REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } <permission.py:> class IsSelfOrStaffPermission(permissions.BasePermission): """ Permission to allow user actions on his own profile """ def has_object_permission(self, request, view, obj): return obj == request.user or request.user.is_staff -
Django ModelForm how do I change the label_suffix per each label
In Django ModelForm how do I change the label_suffix per each label. Some of them will have *, others not. (by default Django uses : ) -
how to use django value inside javascript json
i have a javascript json var new ={ input:{ 'mdata':{ label:'properties', properties:{ name:{ label:'name', type : 'text' }, value:{ label:'value', type:'number', defaultValue:100 } } } } } now i hard coded default Value has 100 ,but i wanted to get from django tags, how can i get this???? -
Django: Read from serial port
I want my Django app to read from serial port, and if some specific data arrives, it should render a specific view, or just render a template is enough too. Is there some solution without celery? I tried this in views.py : def handle_data(data): if data == "SPECIAL": return specialview() # i need request object here def read_from_port(ser): while True: reading = ser.readline().decode() handle_data(reading) thread = threading.Thread(target=read_from_port, args=( serial_port,)) thread.start() def specialview(request): blah blah blah I though if I could just acces the current request object, I can pass it, but the solutions I found here: https://nedbatchelder.com/blog/201008/global_django_requests.html does not work. I am open to any solution except use of celery. -
How do you limit choices in a Django Inlineformset_factory based on User?
I have a Timesheet app and I want to limit the Projects a User can allocate their time to the Projects they are working on. MODELS My models look like this class Project (models.Model): name = models.CharField( verbose_name = 'Project Title', max_length = 80 ) code = models.CharField( verbose_name = 'Project Code', max_length = 15 ) supervisor = models.ForeignKey ( User, on_delete=models.CASCADE ) staff = models.ManyToManyField ( User, related_name= "project_resources" ) def __str__(self): return u'%s' % (self.name) class Meta: ordering = ['name'] class Timesheet (models.Model): user = models.ForeignKey ( User, on_delete=models.CASCADE) start_date = models.DateField ( verbose_name = "Start Date" ) def __str__(self): return u'%s | %s' % (self.user, self.start_date) class Meta: ordering = ['user','start_date'] class TimesheetRow (models.Model): ''' specifies a timesheet row which is unique based on Timesheet, Project and Labour Category ''' timesheet = models.ForeignKey( Timesheet, on_delete=models.CASCADE ) project = models.ForeignKey( Project, on_delete=models.CASCADE ) labor = models.ForeignKey( LaborCategory, on_delete=models.CASCADE ) sunday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) monday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) tuesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) wednesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) thursday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) friday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) saturday … -
django - creating a model from a python class
is anyone aware of a way to create a django model from an existing python class without creating it by hand? Or if not, what is the best method to approach this problem? At the moment I'm searching a way to save the objects returned from libnmap (e.g. NmapHost) in django without creating a wrapper functions which converts a libnmap.objects.NmapHost into the according model. In addition, the django model should inherit all the functions and relationship of the original class. (e.g. a NmapHost has several NmapService objects linked to it) -
Django 1.8 request.user is removed
I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request. These two are passed in the header of the request. The middleware class is the following : from models import MongoToken class TokenAuthenticationMiddleware(object): def process_request(self, request): if "HTTP_AUTHORIZATION" not in request.META: return tokenkey = get_authorization_header(request).split()[1] token = MongoToken.objects.get(key=tokenkey) user = User.objects.get(username=request.META.get("HTTP_USERNAME")) if token.key == tokenkey and token.user.is_active: request.user = user request.token = tokenkey I also put this in my MIDDLEWARE_CLASSES bloc of the settings.py files: MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'myproject.middleware.MongoAuthenticationMiddleware', 'myproject.middleware.TokenAuthenticationMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And when the considered view is reached, my token is here because thanks to the header params but the user is Null. Then I am wondering if I did something wrong with this because it does not work. Thank you for your help. Alex. -
button dropdown list-item type="submit"
I am working on a django application and have a form inside my page. I have one action called "move" (next to delete, archive...) and based on the value that is given ( an ID) the right ID is passed through to my application: HTML (bootstrap): <button class="SelectionAction" type="submit" name="move" value="id1">Move to id1</button> <button class="SelectionAction" type="submit" name="move" value="id2">Move to id2</button> <button class="SelectionAction" type="submit" name="move" value="id3">Move to id3</button> views.py: tag_selection_form = TagSelectionForm(request.POST or None) if tag_selection_form.is_valid(): if 'move' in request.POST: new_tag_id = request.POST['move'] new_tag_list = Tag.objects.get(user = request.user, id = new_tag_id) for item in tag_selection_form.cleaned_data['my_object']: item.tag_list.remove(tag_list) item.tag_list.add(new_tag_list) if 'delete' in request.POST: ... if 'archive' in request.POST: ... ... My Problem: I want to "stack" all the individual move buttons underneath one foldable (dropdown) button, something like this. The dropdown on its own works, but I can not add type="submit" to an <li><a>something</a></li> and placing <button></button> inside the <li></li> messes up the css. <div class="dropdown div-inline SelectionAction"> <button class="btn dropdown-toggle" type="button" data-toggle="dropdown">Example <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><button class="SelectionAction" type="submit" name="move" value="id1">Move</button></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> What is the best way forward for this matter? -
How to handle multiple input elements with the same name in django
I'm working on an admin system with django and I need to use a repeating form elemets in stets to have many of the same record like for example contact persons for an establishment as seen below <div id="m_repeater_2"> <div class="form-group m-form__group row" id="m_repeater_1"> <label class="col-lg-2 col-form-label">Contact People:</label> <div data-repeater-list="" class="col-lg-10"> <div data-repeater-item="" class="form-group m-form__group row align-items-center"> <div class="col-md-12"> <div class="form-group m-form__group"> <label for="example_input_full_name">Contact Name:</label> <input name = 'contactName' type="name" class="form-control m-input" placeholder="John Doe" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Designation:</label> <input name = 'contactDesignation' type="text" class="form-control m-input" placeholder="Managing Director" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Email:</label> <input name = "contactEmail" type="email" class="form-control m-input" placeholder="john@sf.com" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Number:</label> <input name = "contactNumber" type="number" class="form-control m-input" placeholder="0965555555" > </div> <div class="d-md-none m--margin-bottom-10"></div> </div> <div class="col-md-4"> <div data-repeater-delete="" class="btn-sm btn btn-danger m-btn m-btn--icon m-btn--pill"> <span> <i class="la la-trash-o"></i> <span>Delete</span> </span> </div> </div> </div> </div> </div> <div class="m-form__group form-group row"> <label class="col-lg-2 col-form-label"></label> <div class="col-lg-4"> <div data-repeater-create="" class="btn btn btn-sm btn-brand m-btn m-btn--icon m-btn--pill m-btn--wide"> <span> <i class="la la-plus"></i> <span>Add</span> </span> </div> </div> </div> </div> My problem is when two or more of the 'm_repeater_2' are generated I need to know the best way to go about getting each … -
Django: Adding many-to-many relations within post_save
I'm working on a Django 2.0 and I'm trying to create a simple Event app with auto opt-in functionality. I.e. Members with certain statuses are automatically signed up for the Event when it is created. To do that, I used Django's post_save signal to create a queryset of the affected Members and add them to the Event's many-to-many field, participants. @receiver(signal=post_save, sender='events.Event') def auto_opt_in(sender, instance, created, **kwargs): # Only applies to new Events that are opt-out if created and instance.is_opt_out: from database.models import Member # Build queryset of affected members members = Member.objects.none() for status in instance.opt_out_member_statuses: members = members.union(Member.objects.filter(member_status=status)) # Add members to Event instance.participants.add(*members) instance.save() My problem now is that the Members are not actually added to the Event. If I put print(instance.participants.all()) after the last line, it outputs the correct result. However, the changes do not appear to be committed to the database. What am I missing? Are you not allowed to make changes to the instance? If so, what's the point? Thanks -
Calculate Min and Max of Sum of an annotated field over a grouped by query in Django ORM?
To keep it simple I have four tables(A,B,Category and Relation), Relation table stores the intensity of A in B and Category stores the type of B. I need to query A, group by the query by Category and calculate Sum of Intensity of A in each category (which is possible using Django ORM), then I want to annotate Min and Max of calculated Sum in each category. My code is something like: A.objects.all().values('B_id').annotate(AcSum=Sum(Intensity)).annotate(Max(AcSum)) Which throws the error: django.core.exceptions.FieldError: Cannot compute Min('AcRiskIntensity'): 'AcRiskIntensity' is an aggregate Django-group-by package with the same error. For further information please also see this stackoverflow question. I am using Django 1.11 and PostgreSQL. Is there a way to achieve this using ORM, if there is not, what would be the solution using raw SQL expression? -
Django Signals and celery , is Sync
I am using celery to scrap some URLs , and pushing the scrap data to an API but because of quick calls on this API i need to use Django Signals if it Sync