Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
null value in column "group_id" of relation "group_bannedmembers" violates not-null constraint
I am building a BlogGroupApp and I am trying to add a feature of Block Users in Any Kind of Blog Group by Admin. When i try to save the form of banned user then it is keep showing null value in column "group_id" of relation "group_bannedmembers" violates not-null constraint DETAIL: Failing row contains (1, 1, null). models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class BannedMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) views.py def ban_user(request,pk): posts = get_object_or_404(User, pk=pk) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.save() new_post.banned_members.add(posts) return redirect(':home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban.html', context) When i try to ban user then it is keep showing this error. AND when i delete group from BannedMembers then it is wokring Fine, BUT I have to add group in model. I have no idea what am i doing wrong. Any help would be Appreciated. Thank you in Advance. -
How to check if input is already entered before in Django?
I am new to Django. I want to generate Qrcode for given input,and I have done it.But I want to set Error if qr code for given in put is already generate before.Here is my code.Forms.py from django import forms from generateqr.models import * import qrcode class Qrgenerate(forms.Form): input =forms.CharField() def clean_input(self): valinput=self.cleaned_data['input'] if len(valinput)<5: raise forms.ValidationError('Enter more than 5 ') else: img=qrcode.make(valinput) img.save("test.png") return valinput views.py from django.shortcuts import render from .forms import Qrgenerate import qrcode from django.http import HttpResponse # Create your views here. def showformdata(request): if request.method =='POST': fm = Qrgenerate(request.POST or None) return render(request,"home.html",{'form':fm }) [enter image description here]This is form where I want to set error if input is already entered by user before.I have tried with this code,But not work and gives ERROR Attribute 'object' is not found. def clean_input(self): valinput = self.cleaned_data['username'] try: input = Qrcode.objects.get(input==input) except user.DoesNotExist: return input raise forms.ValidationError(i'input "%s" is already in use.' % input) [1]: https://i.stack.imgur.com/mDigT.png Thanks in advance.Please help me out. -
Select all foreign keys from the foreign key table in django
Let's imagine I have 2 models: Class Tree(models.Model): title = models.CharField(max_length=255) Class Apple(models.Model): tree = models.ForeignKey(Tree, related_name="apples") How do I select all the Trees that have Apples. I mean I want to select all the Trees that exist in Apple Model from an instance of Tree. I think I want to execute this query: SELECT DISTINCT tree.id, tree.title FROM apple JOIN tree ON apple.tree = tree.id -
Any good resources for using DRF api with Vanilla Django?
I have a project for which I have made all the relevant REST APIs using DRF. I however have to implement them on the frontend which has to be made using Django templates and hitting the APIs using requests module. Is there a good resource where I can reference into this, as I can't find anything on it online. -
Post Creater is not adding in Banned Users
I am building a BlogApp and I am building a Feature of Ban Users, In which Blog Admin can ban other members in the Group. BUT when i submit the form then it is not saving and keep showing that null value in column "group_id" of relation "group_banmembers" violates not-null constraint DETAIL: Failing row contains (13, null, 1, can_create_post). models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class BanMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) can_create_blogpost = models.BooleanField(blank=True,default=True) views.py def ban_user(request,grouppost_id): posts = GroupPost.objects.get(id=grouppost_id) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.save() new_post.banned_members.add(posts.user) return redirect('home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban.html', context) group_posts.html {% for pos in posts %} <br> <br> {{ pos.title }} <br> <b>User :</b> <a href="{% url 'ban_user' pos.user.id %}">Ban {{ pos.user }}</a> <br> {% endfor %} I am trying to ban a user which posted a post in a specific Group. BUT when i click on save button for ban then it is not saving in database. I have no idea what am i … -
Django forms.ModelForm POST change object before update
Via a standard HTML POST form I successfully update an exciting record with the bellow but the situation is that I need to change one data field. On the Django website the say just make e new form instance and change the field but for what ever the reason is the field data does not change in the save() action. class ProvisioningDetails(View): def post(self, request, provisioning_ptr_id, terminal_id, site_id): form = ProvisioningForm(request.POST) if form.is_valid(): a = Provisioning.objects.get(provisioning_ptr_id=provisioning_ptr_id) f = ProvisioningForm(request.POST, instance=a) f.str1 = "some new data" f.save() return redirect( "provisionings_show_view", site_id, terminal_id, provisioning_ptr_id ) class ProvisioningForm(forms.ModelForm): class Meta: model = Provisioning fields = [ "id", "fixedip", "str1", "str2", "str3", "ip", ] def clean(self,): cleaned_data = super(ProvisioningForm, self).clean() I also tried this which does the change the data in the form but not in the database: class ProvisioningDetails(View): def post(self, request, provisioning_ptr_id, terminal_id, site_id): form = ProvisioningForm(request.POST) if form.is_valid(): a = Provisioning.objects.get(provisioning_ptr_id=provisioning_ptr_id) new = ProvisioningForm(request.POST) new.str1 = "some new data" f = ProvisioningForm(new, instance=a) f.save() return redirect( "provisionings_show_view", site_id, terminal_id, provisioning_ptr_id ) Anyone know how I can get the str1 = "some new data" save in the database -
Django: The view didn't return an HttpResponse object. It returned None instead
I keep getting this error when I try to use my 'edit' url. The view to_do_list_app.views.edit didn't return an HttpResponse object. It returned None instead. my url.py urlpatterns = [ path('', views.todo, name='todo'), path('delete/<job_id>', views.delete, name='delete'), path('cross_off/<job_id>', views.cross_off, name='cross_off'), path('uncross/<job_id>', views.uncross, name='uncross'), path('edit/<job_id>', views.edit, name='edit'), ] from django.db import models.py class Jobs(models.Model): # Relationships to_do_owner = models.ForeignKey("auth.User", on_delete=models.SET_NULL, blank=True, null=True) # Fields item = models.CharField(max_length=200) completed = models.BooleanField(default=False) def __str__(self): return self.item +' | ' + str(self.completed) Here is my veiws.py from django.shortcuts import render, redirect from .models import Jobs from .forms import ListForm from django.contrib import messages from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required def edit(request, job_id): if request.method == 'POST': item = Jobs.objects.get(pk=job_id) form = ListForm(request.POST or None, instance=item) if form.is_valid() and request.POST['item'] != '': form.save() messages.success(request, request.POST['item']+ ' er blevet redigeret i din opgave list') return HttpResponseRedirect('todo') else: item =Jobs.objects.get(pk=job_id) context = {'item': item} return render(request, 'edit.html', context) And here I have my template edith.html <form class="d-flex" method="POST" action="{% url 'edit' item.id %}"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="{{ item.item }}" value="{{ item.item }}" aria-label="Search" name="item"> <input type="hidden" value="{{ user.username }}" name="job_owner"> <input type="hidden" value="{{ item.completed }}" name="completed"> <button class="btn btn-outline-secondary" type="submit">Rediger opgave</button> </form> … -
Passing form data to a celery task
I have a simple form (with no model) in my views in which I capture the inputs the user type in order to send an email. I capture those inputs with: if result['success']: name = form.cleaned_data['name'] email = form.cleaned_data['email'] ... send_email_task() Te question is, how can I pass that data to a Celery send_email_task in order to send it. Something like: @shared_task def send_email_task(): send_mail(name + ': ' + subject, 'From: ' + email ... -
Django - How to parallelize my Import process?
I'm running a Import process which is working fine if I start it sequentially but as soon as multiple threads starting to import/scan my files for metadata I'm running into the following error: Core.models.MusicAlbums.MultipleObjectsReturned: get() returned more than one MusicAlbums -- it returned 2! So my question is how can such a flow be parallelized?: ... else: if not MusicArtists.objects.filter(title=artist_value).exists(): try: new_music_artist_object, is_created = MusicArtists.objects.get_or_create(title=artist_value) new_music_artist_object.refresh_from_db() except MultipleObjectsReturned: new_music_artist_object = MusicArtists.objects.get(title=artist_value) pass else: new_music_artist_object = MusicArtists.objects.get(title=artist_value) if not MusicAlbums.objects.filter(artist=new_music_artist_object, title=album_value).exists(): try: new_music_album_object, is_created = MusicAlbums.objects.get_or_create( title=album_value, artist=new_music_artist_object, cover=cover_value, total_discs=total_discs_value, total_tracks=total_tracks_value, copyright=copyright_value, release_date=release_date_value, genre=genre_value) new_music_album_object.refresh_from_db() except MultipleObjectsReturned: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) pass else: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) try: new_music_track_object, is_created = MusicTracks.objects.get_or_create( file=new_file_object, album=new_music_album_object, artist=new_music_artist_object, bitrate=bitrate_value, genre=genre_value, duration=duration_value, size=size_value, nb_streams=nb_streams_value, media_type=0, title=title_value, release_date=release_date_value, disc=disc_value, track=track_value ) new_music_track_object.refresh_from_db() pull_streams(object_id=new_music_track_object) except MultipleObjectsReturned: pass Basically each file gets placed onto a message queue for processing, than X worker(s) pic up one of those generated tasks and processes them. So far so good but as soon as I have 2 workers that are processing a MusicTrack out of the same MusicAlbum my process breaks or at least I get multiple entries at the database for the same thing, I get two entries for the MusicAlbum … -
I tried to aggregate the sum of a property from a model in Django
On the model page, I created a property called nzd_price, which is not really a field, but a property. On a templatetags page, I tried to aggregate the sum all the rows of a column from nzd_price for a new row with the name Total: models.py: class BrazilBill(models.Model): item = models.CharField('item', max_length = 50) price = models.DecimalField('price', max_digits = 10, decimal_places = 2) @property def nzd_price(self): return round(float(self.price) * 0.29, 2) templatetags/total_price.py: from django import template from django.db.models import Sum from financial_planning.models import BrazilBill register = template.Library() @register.filter def brazil_bill_total_brl(value): return BrazilBill.objects.aggregate(Sum('price')).get('price__sum') @register.filter def brazil_bill_total_nzd(value): return BrazilBill.objects.aggregate(Sum('nzd_price')).get('nzd_price__sum') The error: FieldError at /financial-planning/ Cannot resolve keyword 'nzd_price' into field. Choices are: id, item, price Based on Calculate the sum of model properties in Django, I also tried: @register.filter def brazil_bill_total_nzd(value): return BrazilBill.objects.aggregate(Sum('brazilbill__nzd_price')) -
How to integrate OAuth2 with back- and frontend
I'm learning OAuth2 to integrate a 3rd party provider like Facebook or Github. But I'm struggling with finding resources that describe how to integrate it when you're building an app with both a back- and frontend. In this example, let's pretend a have frontend (myfrontend.com) running something like Vue.js. And a backend (mybackend.com) running something like Django. And a 3rd party provider like GitHub. My idea is to use this flow: Front end redirect's to providers Authorize url. example: https://github.com/login/oauth/authorize?client_id=<client_id>&redirect_uri=https://mybackend.com/callback?return-to=https://myfrontend.com/home. If the user authorizes, backend receives code in /callback. Backend sends authentication request (serverside) with code to get access_token to 3rd party provider. Backend creates a user if it doesn't exist yet and saves access_token associated with that user. Backend creates a new local token for the user (for authenticating to mybackend.com) (JWT or OAuth2). Backend redirects to https://myfrontend.com/home (specified in first url) with token in body. Frontend receives token and saves in in local storage. When the frontend requires a resource from GitHub a behalf of the user, a request is sent to my backend which in turn uses the save access_token and requests the resource from GitHub. My question is this: Is this flow safe or should I … -
Trying to establish a realtion Between model tables in Django.but iam getting error while insering values |foreign-key item must be an instance
class User(AbstractUser): pass class auction_list(models.Model): item_id=models.IntegerField(primary_key=True) item_name=models.CharField(max_length=64) owner=models.CharField(max_length=64) image=models.CharField(max_length=128) def __str__(self): return f"{self.item_id}:{self.owner}{self.item_name}" class bid(models.Model): item_id=models.ForeignKey(auction_list,on_delete=models.CASCADE,related_name="currentbid") bid=models.IntegerField(max_length=16) user=models.CharField(max_length=64) def __str__(self) : return f"{self.item_id}{self.bid}{self.user}" and when i try to inser the valules i get this error inseritions i tried to do: In [16]: a3=auction_list(item_id=3,item_name="keyboard",owner="alex" ) In [17]: a3.save() In [18]: a3 Out[18]: <auction_list: 3:alexkeyboard> In [20]: b1=bid(item_id=3,bid=100,user="alex") and the error i get is In [20]: b1=bid(item_id=3,bid=100,user="alex") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-20-6befcb719aa3> in <module> ----> 1 b1=bid(item_id=3,bid=100,user="alex") ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in __init__(self, *args, **kwargs) 483 # checked) by the RelatedObjectDescriptor. 484 if rel_obj is not _DEFERRED: --> 485 _setattr(self, field.name, rel_obj) 486 else: 487 if val is not _DEFERRED: ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py in __set__(self, instance, value) 213 # An object must be an instance of the related class. 214 if value is not None and not isinstance(value, self.field.remote_field.model._meta.concrete_model): --> 215 raise ValueError( 216 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % ( 217 value, ValueError: Cannot assign "3": "bid.item_id" must be a "auction_list" instance. can some one help me understand wht is the problem here and how can i resolve these -
Celery-beat doesnt work with daily schedule
I trying to run tasks with celery-beat. When I launch it by minute or hour schedule, tasks will start correctly, but if I trying to run daily task, it display in django admin panel, but not run in time. It must to work in the following way: regular django code starts a 'start_primaries' task in Party class: def setup_task(self): schedule, created = IntervalSchedule.objects.get_or_create(every=7, period=IntervalSchedule.DAYS) self.task = PeriodicTask.objects.create( name=self.title + ', id ' + str(self.pk), task='start_primaries', interval=schedule, args=json.dumps([self.id]), start_time=timezone.now() ) self.save() Is it possible that there are some settings that limit the duration of the task's life? At the moment I have the following among the Django settings: CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 950400 CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_RESULT_EXPIRES = None CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 950400} -
is there any other way to post data?
while submitting my data i am having error saying please check you detail even though all the data i have input is correct def register(request): registered = False user_form = UserForm() user_profile_form = UserProfileForm() if request.method == 'POST': user_form = UserForm(data = request.POST) user_profile_form = UserProfileForm(data = request.POST) if user_form.is_valid() and user_profile_form.is_valid(): user_form.save() user_profile_form.save(commit = false) user_profile_form.user = user #creating that OneToOneField relation if 'profile_pic' in request.FILES: user_profile_form.profile_pic = request.FILES['profile_pic'] user_profile_form.save() registered = True return index(request) else: print('Error occured while Posting Data please check you detail!') else: user_form = UserForm() user_profile_form = UserProfileForm() return render(request,'levelfive_second_app/register.html',context = {'user_form':user_form , 'user_profile_form':user_profile_form}) -
Errno 13 Permission denied: media file in Django
I am trying to write a file to the django media folder, but on execution I get a permission denied error. The configuration works fine on the OSX development platform, but not on the Ubuntu test server. I have the following config: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' print('SETTINGS CWD = ', os.getcwd()) models.py methods: def template_to_file(self): print('MODELS CWD = ', os.getcwd()) with open(path + '/newsletter-volume-1.html', 'w') as static_file: static_file.write('Hello') def save(self, *args, **kwargs): self.template_to_file() super(Newsletter, self).save(*args, **kwargs) On the OSX development platform the file writes to the media folder and the Current Working Directory prints are as follows: SETTINGS CWD = /Users/tb/Documents/dev/backoffice MODELS CWD = /Users/tb/Documents/dev/backoffice However, on the Ubuntu platform I get: [Errno 13] Permission denied: '/home/admin/backoffice/media/newsletter-volume-1.html' SETTINGS CWD = /home/admin/backoffice MODELS CWD = / The following permissions are set as follows (admin is the owner of Django): drwxrwxr-x 9 admin admin 4096 Jun 19 09:05 . drwxr-xr-x 7 admin admin 4096 Jun 19 06:02 .. drwxrwxr-x 2 admin admin 4096 Jun 19 06:07 media Does anyone have a solution to this and an explanation as to why the Current working directory changes to '/' on the Ubuntu server? -
sometimes ValueError raised after I deployed Django app using Python 3.9.5 with Apache 2.4 on windows10 home addition
In the development environment everything working good, However as soon as I deployed the Application with Apache24 webserver on Windows 10 Home, sometimes I get this error, when I refresh the page everything working good again... This is the full error Message: ValueError at /books set_wakeup_fd only works in main thread of the main interpreter Request Method: GET Request URL: http://196.221.149.169:8080/books Django Version: 3.2.4 Exception Type: ValueError Exception Value: set_wakeup_fd only works in main thread of the main interpreter Exception Location: C:\Python39\Lib\asyncio\proactor_events.py, line 632, in init Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.9.5 Python Path: ['C:\Users\eunan\church', 'C:\Python39\python39.zip', 'C:\Python39\Lib', 'C:\Python39\DLLs', 'C:\Apache24\bin', 'C:\Python39', 'C:\Python39\lib\site-packages'] Server time: Sat, 19 Jun 2021 08:45:35 +0000enter image description here -
the username and request.user name has the same value but django python doesnt' recognise it as the same
why am i getting not the same user Here is what in my views.py def upost(request, username): if request.method == 'GET': vng_u = request.user us = username vd_u = get_object_or_404(User, username=username) p_o_u = Name.objects.filter(user=vd_u).order_by('id').reverse() if request.user.is_anonymous: return redirect('login') else: if (vng_u == us): s = "same" else: s = "not" pgntr = Paginator(p_o_u,1) pn = request.GET.get('page') pgobj = pgntr.get_page(pn) return render(request, "network/users.html", { "xp": p_o_u, "pc": pgobj, "postuser": us, "uv": vng_u, "s":s }) here is what in my html {% if uv == postuser %} same {%else%} not the same {% endif %} {{s}} <div id="post-users"><br> Viewer: <strong id="v1">{{uv}}</strong><br> Poster: <strong id="v2">{{postuser}}</strong> {% for x in xp %}<br><hr> Content: {{x.content}}<br> {{x.timestamp}} {% endfor %} </div> and here is what appears on the html web page -
What might be the problems to use Profile attributes to authenticate users in Django?
I am trying to authenticate users in Django using either username or phone_number and password. We have to extend the User model to add phone_number as a new attribute and I did it using OnetoOneField from the Profile model and used phone_number to authenticate users using custom authentication backend as: from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import check_password from django.contrib.auth import get_user_model from django.db.models import Q from .models import Profile class MyBackend(BaseBackend): def authenticate(self, request, username=None, password=None): User = get_user_model() try: user = User.objects.get(Q(username=username)|Q(email=username)) except User.DoesNotExist: try: profile = Profile.objects.get(phone = username) user = profile.user except Profile.DoesNotExist: user = None if user and user.check_password(password): return user else: return None It seems like it works while logging in using the admin login portal but I found the suggestions of using CustomUserModel to achieve this. Is it safe to do this? or Do I have to create CustomUserModel inheriting from AbstractBaseUser? -
Flutter Web and Django routing directly from URL
I have Flutter web and Django backend (REST API). I want to serve flutter web from Django directly. Every thing works fine if I start from domain (localhost:8000) and navigate to (localhost:8000/others) from web. But it shows 404 if I push URL (localhost:8000/others) direct from browser. Note: On flutter only it works properly (used Navigator 2.0). But on intregating with Django its not working. -
Django ImproperlyConfigured: Application labels aren't unique
Question How do I configure my app and label my application correctly so that I don't run into a Application labels aren't unique error and so that it works? I understand that I can rename auth. I do not wish to rename auth. settings.py INSTALLED_APPS = [ ..., core.auth, ... ] $ python manage.py shell_plus returns Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/registry.py", line 95, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth I added the following: core/auth/init.py default_app_config = 'core.auth.AuthConfig' core/auth/apps.py from django.apps import AppConfig class AuthConfig(AppConfig): name = "core_auth" label = "core_auth" verbose_name = "Core Auth" $ python manage.py shell_plus Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, … -
Tom-Select as Django Widget
I would like to use tom-select as an Django autocomplete select-widget. In the corresponding database table (Runners) are several hundred rows, so that I can't load all into the html page. In the model RaceTeam I have a ForeignKey to Runner. The select widget will be used in whole pages and in html fragments (via htmx). I tried subclass django.forms.Select, but this sucks all db rows into widget.choices. -
how to return number of distinct values django
i'm working on project for an hotel family = 'family' single = 'single' room_types = ( (family , 'family'), (single , 'single'), ) class Room(models.Model): room_no = models.IntegerField(unique=True) beds = models.IntegerField(default=2) balcon = models.BooleanField(default=False) room_type = models.CharField(max_length=15,choices=room_types,default=single) this is my views(query) lists = Room.objects.order_by().values('balcon ','beds','room_type').distinct().annotate(total=Count('beds',distinct=True)+Count('balcon',distinct=True)+Count('room_type',distinct=True)) i expect the query to return something like this beds: 4 , balcon : True , room_type : single , total : 10 beds: 3 , balcon : True , room_type : family, total : 4 and so on but it doesnt return as i expected ! is it possible to make a group by based on several fields and count based on that selected fields please ? thank you for helping .. -
django How to add multiple images with foreignkey
in our application, users must add a ad through the form Models.py: class Ad(models.Model): title=models.CharField('Заголовок',max_length=150,null=False,blank=False) content=models.TextField('Описание',max_length=500) price=models.PositiveIntegerField('Цена',help_text='0 = Договорная') date=models.DateTimeField('Дата',auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name='Обьявление' verbose_name_plural='Обьявлении' class Images(models.Model): image=models.ImageField('Изображение',upload_to='upload_images/%Y/%m/%d/') ad=models.ForeignKey(Ad,on_delete=models.CASCADE) class Meta: verbose_name='Фото' verbose_name_plural='Фото' Views.py: def add_new(request): if request.method=='POST': form=AddForm(request.POST) if form.is_valid(): valid_form=form.save() for image in request.FILES.getlist('images'): photo=Images(ad=valid_form,image=image) photo.save() return HttpResponseRedirect('/') else: form=AddForm() return render(request,'add_post.html',{'form':form}) and as a result, ad.title is added to the database, and if I write photo = Images (ad = valid_form.pk, image = image), then an error occurs. help me please -
Missing required flag: » -a, --app APP parent app used by review apps
Guys I am trying to run my app, but everytime I have this problem. I tried to run it also with only -app flag. Here is what I tried: heroku run --app movie-raterr I got a message: Error: Missing required flag: » -a, --app APP parent app used by review apps heroku run » Error: Missing required flag: » -a, --app APP parent app used by review apps When I tried to run only with -app flag I got another kind of error: heroku run bash at Run.run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@heroku-cli/plugin-run/lib/commands/run/index.js:27:19) at Run._run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@oclif/command/lib/command.js:44:31) -
how to get some filtered results from class based views in Django rest framework?
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return self.name class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=2.5) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField() isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) name = models.ForeignKey(User_details, on_delete=models.CASCADE) is_registered = models.BooleanField(default=False) is_attended = models.BooleanField(default=False) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) my serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: …