Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django runserver problem "python manage.ph runserver"
i have a django file, and i'm trying to see that file in django but when i command "python manage.ph runserver" it's not showing anything. just emty line in cmd after i commend. i tried to fin and error in my pip but there wasn't any problem. and the file is fine as well. i tried to create and run another file from scrach but it didn't work too. so is there anyone who knows the solution ?as you can see, when i try to run the file in django, it's not responding anything -
Problems with creating slug
Hello good afternoon I am developing an application that handles two roles of administrator and developer, the administrator data as developer is created without problems but when trying to use slug the program does not recognize them. This is my model class ProfileAdministrator(models.Model): user = models.OneToOneField(Administrator, on_delete=models.CASCADE) image = models.ImageField(default='avatar.png', upload_to='profiles/') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.slug class ProfileDeveloper(models.Model): user = models.OneToOneField(Developer, on_delete=models.CASCADE) image = models.ImageField(default='avatar.png', upload_to='profiles/') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.slug @receiver(post_save, sender=Administrator) def set_profile_administrator(sender, instance, *args, **kwargs): if kwargs.get('created', False): ProfileAdministrator.objects.create(user=instance) @receiver(post_save, sender=Developer) def set_profile_developer(sender, instance, *args, **kwargs): if kwargs.get('created', False): ProfileDeveloper.objects.create(user=instance) @receiver(pre_save, sender=ProfileAdministrator) def set_slug_profile_administrator(sender, instance, *args, **kwargs): if instance.user: instance.slug = slugify(instance.user) @receiver(pre_save, sender=ProfileDeveloper) def set_slug_profile_administrator(sender, instance, *args, **kwargs): if instance.user: instance.slug = slugify(instance.user) the program works fine even when I enter the slug, it does not recognize them, but the data is created correctly -
Cannot assign "[{'id': '2'}]": "Model .field" must be a "ForeignKey" instance
I have two model BAI and EMT. BMI has a CharField called country, in my EMT model i have country_name field where i am passing as foreignkey of BMT, Now when i am trying to create a new EMT i am getting this error: Cannot assign "[{'id': '2'}]": "EMT.country" must be a "BAI" instance. my models ### Country Related Model ### class BAI(models.Model): country = models.CharField(max_length=100, null=True) currency = models.CharField(max_length=100, null=True) capital = models.CharField(max_length=100, null=True) def __str__(self): return self.country class Meta: db_table = 'app_country_banner_and_information' ordering = ['id'] ### Country Export Related Model ### class EMT(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) year = models.CharField(max_length=100, null=True) def __str__(self): return ('Export') class Meta: db_table = 'app_emt' ordering = ['id'] my views @csrf_exempt def emt(request, id=None): if request.user.profile.role == '2': if request.method == 'GET': if id is not None: try: offer = EMT.objects.get(id=id) data = { 'country': '', 'year': '', } except Exception: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) else: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) elif request.method == 'POST': data = json.loads(request.body) if id is not None: try: existInfo = EMT.objects.get( id=id, ) existInfo.country=data.get('country', None) existInfo.year=data.get('year', None) try: existInfo.save() return HttpResponse(json.dumps({"status": 1}), content_type='application/json') except IntegrityError as e: err = e.args[1] err = err.replace(" for … -
Django Social-Auth - save Stripe Email
I'm using Django Social Auth for Stripe. My goal is to create an account on my website with all those : email, stripe_account That works well except for the email: I got username = stripe_account without any email. I've read the Stripe Doc but I did not find anything on this. settings.py 'social_core.backends.stripe.StripeOAuth2', SOCIAL_AUTH_STRIPE_KEY = '****' SOCIAL_AUTH_STRIPE_SECRET = '****' SOCIAL_AUTH_STRIPE_SCOPE = ['read_only'] {% url 'social:begin' 'stripe' %} -
django custom authentication backend is not being called
I am using Django 3.1, and trying to figure out why my custom Authentication backend isn't being called. In my settings.py file I have: AUTHENTICATION_BACKENDS = ( 'sizzy.backends.EmailBackend', ) And in my sizzy.backends.py file I have: from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import ModelBackend from .models import User class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None): try: print("Trying the email backend!") user = User.objects.get(email=username) print("Got the user") if user.check_password(password): # check valid password return user print("password didn't work") except ObjectDoesNotExist: return None def get_user(self, user_id): try: print("Getting the user of the Email Bkacned") return User.objects.get(pk=user_id) except ObjectDoesNotExist: return None I then open up the manage.py shell and input: from django.contrib.auth import authenticate email = "billypop@a.pop" password = "password" user = authenticate(username=email, password=password) And it outputs: Login failed. Credentials: {'username': 'billypop@a.pop', 'password': '********************'} And I don't see any print statements. "Trying to get the Email Backend!" is never printed. Am I missing something? I tried changing my settings file to point to sizzy.backends.EmailBackendqwertyui just as a sanity check, and that threw an error instead of Login failed. So the backend is being loaded somehow I think, but never called. I've also tried changing out ModelBackend for BaseBackend, with the same results. -
MultiValueDictKeyError in accessing same form element in Django
I have some dropdowns here in my Index.html file. I have accessed the values selected in name=player1 and name=player2 dropdowns. But when I am going to access the value of name=selectcountry1 on same page in same form. Django is showing MultiValueDictKeyError. If I comment out the line in which I am accessing name=selectcountry1, all works fine. It takes the values of other dropdowns correctly. Also when I use request.POST.get('selectcountry1'), it is returning 'None', What is the problem as well as the solution. I don't want None, I want the value selected in dropdown. My HTML Page - <form method="post" action="{% url 'dynamic' %}" enctype="multipart/form-data"> {% csrf_token %} {% comment %} Defining a Form for Accepting first and second country and submit button {% endcomment %} <!--Defining Left Division for Team 1 (team1div)--> <div style="float : left; margin-top: 2%; width: 50%; padding-left: 10px;"> <div style="margin-left: 15px;"> <select name="selectcountry1" id="c1" onchange="getValue1(this)" style="width:180px;"> <option class="sel" selected value="select">Select Country 1</option> <option data-img_src='/static/India.png' value="India" >India</option> <option data-img_src='/static/Australia.png' value="Australia" >Australia</option> <option data-img_src='/static/England.png' value="England" >England</option> <option data-img_src='/static/NewZealand.png' value="NewZealand" >New Zealand</option> <option data-img_src='/static/SouthAfrica.png' value="SouthAfrika" >South Afrika</option> <option data-img_src='/static/WestIndies.png' value="WestIndies" >West Indies</option> <option data-img_src='/static/Pakistan.png' value="Pakistan" >Pakistan</option> <option data-img_src='/static/Srilanka.png' value="SriLanka" >Sri Lanka</option> <option data-img_src='/static/Bangladesh.png' value="Bangladesh" >Bangladesh</option> <option data-img_src='/static/Afganistan.jpg' value="Afganistan" >Afganistan</option> … -
Streaming multiple files through Django
I would like to stream a multiple files through Django. My ideas is to zip the files in memory then send it, as in the below code. But the problem is this will take too much time and ressources on my server. My question is: is there a better way to serve multiple urls through Django without zipping them ? import requests from django.http import StreamingHttpResponse def download(request): url = ['https://myondownlaod.com/file1.mp4','https://myondownlaod.com/file2.mp4','https://myondownlaod.com/file3.mp4'] in_memory = StringIO() for u in url: filename = os.path.basename(u) r = requests.get(u) zip = ZipFile(in_memory, "a") zip.write(r) zip.close() response = HttpResponse(mimetype="application/zip") response["Content-Disposition"] = "attachment; filename=my_zippedfiles.zip" in_memory.seek(0) response.write(in_memory.read()) return response I have seen this example which work pretty well when I tried it, but them my question would be how do you deal with multiple files. import requests from django.http import StreamingHttpResponse from django.contrib.auth.views import login_required def download(request): url = 'file_url_here' filename = os.path.basename(url) r = requests.get(url, stream=True) response = StreamingHttpResponse(streaming_content=r) response['Content-Disposition'] = f'attachement; filename="{filename}"' return response -
Global continuous 3 minutes countdown
I have a django webapp I'm working on, so I don't know of its possible to have a global countdown of 3 minutes that refreshes the page at the end of each 3 minutes continously. I tried to use js but if I refresh the page the countdown starts over again -
multiple (upload) files extensions check in Django template?
how can i check file extension in Django template side? I want to upload multiple files like (photos&videos) in a single post like Facebook. if file is video format then automatically video player detects if it is an image file then it display automatically? when i post an image file i want only that particular file to be shown i don't want video area to show along with it. when i post certain files i want only that to be displayed! models.py class Article(models.Model): title = models.CharField(max_length=300,) file_data = models.FileField(upload_to='stories', blank=True, null=True) def __str__(self): return self.title def extension(self): name, extension = os.path.splitext(self.file_data.name) return extension forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] {% for object in newss %} <div class=" card"> {% if object.file_data %} <img src="{{object.file_data.url}}" alt="article" height="400"> {% endif %} {% if object.file_data %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{object.file_data.url}}#t=0.9" /> </video> {% endif %} </div> {% endfor %} -
Django TemplateDoesNotExist, when trying to redirect user's
I have this structure,and basically what I want is to send the user to the right place depending on their group. myproject/ |-- myproject |--urls.py |--settings.py |--views.py |-- pluviais/ |--urls.py |--views.py |-- eletricistas/ |--urls.py |--views.py So when they login, my settings.py redirect to index, (LOGIN_REDIRECT_URL = 'index') myproject/urls.py from .views import index urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('pluviais/', include('pluviais.urls')), path('eletricistas/', include('eletricistas.urls')), ] document_root=settings.MEDIA_ROOT) myproject/views.py from django.contrib.auth.models import Group,User from django.shortcuts import render, redirect def index(request): users_in_group = Group.objects.get(name="tablet").user_set.all() if request.user in users_in_group: user_responsaveis_pluviais = User.objects.filter(username=request.user, groups__name='Responsáveis - pluviais').exists() user_chefes_pluviais = User.objects.filter(username=request.user, groups__name='Chefes - pluviais').exists() print(user_responsaveis_pluviais) if user_responsaveis_pluviais == True or user_chefes_pluviais==True: return render(request, '/pluviais/tablet/') else: return render(request, '/eletricistas/tablet/') As you can see the idea is simply depending on the groups that the users are in, they are redirected to the right place ( or go to pluviais/ or eletricistas/ pluviais/urls.py urlpatterns = [ path('tablet', views.intervencao, name='intervencao'), ] eletricistas/urls.py urlpatterns = [ path('tablet', views.tarefas, name='tarefas'), ] the problem is that always giving me the error TemplateDoesNotExist at /, so maybe i am doing this wrong. -
Django calculate value within Model save based on new field values
I've got a profile score of an object which is calculated within the save() because the fields to be used are based on how scoring is defined in another table. So within my model I have: def save(self, *args, **kwargs): self.profile_score = self.calc_profile_score() super().save() This uses the following: def scoring_recordset (self): query = models.Q() if self.service_care_home and self.care_residential: query = models.Q(query | models.Q(care_home_residential=True)) if self.service_care_home and self.care_nursing: query = models.Q(query | models.Q(care_home_nursing=True)) if self.service_care_home and self.care_dementia: query = models.Q(query | models.Q(care_home_dementia=True)) if self.service_care_home and self.care_respite: query = models.Q(query | models.Q(care_home_respite=True)) if self.service_home_care and self.regulated_personal_care: query = models.Q(query | models.Q(home_care_personal=True)) if self.service_home_care and self.care_nursing: query = models.Q(query | models.Q(home_care_nursing=True)) if self.service_home_care and self.care_dementia: query = models.Q(query | models.Q(home_care_dementia=True)) if self.service_live_in_care and self.regulated_personal_care: query = models.Q(query | models.Q(live_in_care_personal=True)) if self.service_live_in_care and self.care_nursing: query = models.Q(query | models.Q(live_in_care_nursing=True)) if self.service_live_in_care and self.care_dementia: query = models.Q(query | models.Q(live_in_care_dementia=True)) return Score.objects.filter(query) def field_score (self, score): if score.is_premium and not self.is_premium: return 0 if score.scoring_algorithm == 'boolean': try: if self._meta.get_field(score.field_name).value_from_object(self): return score.max_points except: #not a field so must be property if isinstance(getattr(Organisation, score.field_name), property): tmp = getattr(Organisation, score.field_name) if tmp.fget(self): return score.max_points elif score.scoring_algorithm == 'per item': tmp = 0 try: for item in self._meta.get_field(score.field_name).value_from_object(self): tmp … -
How to define ImageField in abstract model?
I have class for upload_to: class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.path, filename) I have created abstract class for preview: class PreviewAbstract(models.Model): upload_path = '' preview = models.ImageField( verbose_name='Превью', upload_to=PathAndRename(upload_path) ) class Meta: abstract = True I want to be able to inherite this model like: class ChildClass(PreviewAbstract): upload_path = 'folder_name' , but in saves images in "root" folder How can i do it? Thank you for your answers. -
How can we edit content inside textarea feild?
Here i am using django 3.0.3/python and jquery for front-end,well my question is that i simple want to add some styling inside the textarea , Most of people are familiar with medium , I simple want to convert my blog form to the form like medium , right know my blog form looks like: and I simple want to change it like : I also want all these following tools during writing a blog: Well i am not saying that give all the code in the answers, I just want to know the steps which i need to make and the things which i will be going to use to make. I will extremely thankful to all of you who will answer this question. -
Automatic form validation based on user account data
Hi I have a question if I am able to write validations in such a way that the name is taken when you click submit and you only have the options to select the tournament and group this is my models.py file class Debatants(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) email = models.EmailField(max_length=256, null=True) class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name and this is my views.py file def groups(request, pk): tournament_groups = get_object_or_404(TournamentGroup, pk=pk) users = TournamentUsers.objects.filter(user_group=tournament_groups) judges = TournamentJudges.objects.filter(user_group=tournament_groups) tournament = Tournament.objects.get(tournament_name=tournament_groups.tournament_name) form = TournamentUsersForm( initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups}) form2 = TournamentJudgesForm(initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups}) if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() if request.method == "POST": form2 = TournamentJudgesForm(request.POST) if form2.is_valid(): form2.save() form2 = TournamentJudgesForm() context = {'tournament_groups': tournament_groups, 'users': users, 'form': form, 'judges': judges, 'form2': form2, "tournament": tournament} return render(request, 'ksm_app2/groups.html', context) -
django Admin - Filter foreign key selected depending on other choice in edit form (ithout jQuery)
I am working on a project which is administered by a super admin who puts in data for different companies. Lets say, I have these models: class Company(models.Model): name = models.CharField(max_length=100) class ContactPerson(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company) class Item(models.Model): company = models.ForeignKey(Company) contact_person = models.ForeignKey(ContactPerson) I need to ensure that I (in django admin) in the edit mode I only see contact persons which belong to the selected company. Being not in the year 2005 anymore I want to avoid writing loads of super ugly jQuery code. I guess I could overwrite the admin form for Item. But still I had to make the contact_person optional, so when I create a new Item, the list of contact persons need to be empty. Then I'd select a company, save it and go back to edit. Now the contact_person list would be filled and I could add somebody. But if I now change the comany, I'd have to remove all selected contact persons. Sure, I could to this in the form... but it looks SO hacky and not like a nice django solution. Anybody got some fancy ideas? Thanks in advance! Ronny -
how can I use foreign key to import users login from google by Django-allauth
I am using 2 login methods, one is Django inbuilt authentication and another by using "allauth" of google. I want to make a separate model with only the entries from google logged-in people by using a "foreign key" and few more attributes. In Django admin page there is a table "Social accounts", which has only google logged in users, so how can I include that model? What all includes I have to use to get model like this and what should I write instead of something: class GoogleSignIn(models.Model): id= models.AutoField(primary_key=True) googleacc = models.ForeignKey(*something*, on_delete=models.CASCADE, null=True) productsTaken= models.CharField(max_length=50) ph = models.CharField(max_length=12) -
Error in django when I add two new fields to a class model
I have a class called Difference in my script "myProject.models.difference.py" that is: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) And in my script "myProject.admin.scenario.py" I have the corresponding admin class: class DifferenceAdmin(admin.ModelAdmin): list_display = ("comparator","summary",) But I need to add two fields more to my Class Difference: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) diff_class = models.CharField('diff_class',max_length=1000) diff_field = models.CharField('diff_field',max_length=500) After that I read the next error: "no such column: myproject_difference.diff_class". But if I comment the new fields diff_class, diff_field of this way: class Difference(models.Model): comparator = models.ForeignKey(ScenarioComparator, on_delete=models.CASCADE) summary = models.CharField('summary',max_length=900000) #diff_class = models.CharField('diff_class',max_length=1000) #diff_field = models.CharField('diff_field',max_length=500) Then the error disappears. ¿What must I do in order to add the new fields? -
django-haystack returns "inexact" results when keyword contains multiple words
I'm using django-haystack with Solr as backend. I ahve a model with Author, Title, ISBN as fields. If I search for ex for Harry potter I get results for books that's the author name is Harris or contains Harris in their titles but no Harry potter. but when I putt the keywords between "" ("Harry Potter" for ex) I get the right results! Any idea how I can fix this? Thanks. -
Django query to get sum of previous values
I have the following table of logs that stores operations. An override operation means an absolute value stored, while add and sub operations are variance values. The override operations are like checkpoints. Id operation quantity --------------------------------------------------------- 1 ADD 10.00 2 ADD 20.00 3 OVERRIDE 15.00 4 SUB -5.00 5 SUB -10.00 My goal is to get the following results with one query Id operation quantity calculated_total_quantity --------------------------------------------------------- 1 ADD 10.00 10.00 2 ADD 20.00 30.00 3 OVERRIDE 15.00 15.00 4 SUB -5.00 10.00 5 SUB -10.00 0.00 I tried the following query Logs.objects.all().annotate( calculated_total_quantity=Case( When(operation="OVERRIDE", then=F('quantity')), default=Window( expression=Sum(F('quantity')), order_by=F('id').asc() ) ) ) With this query I am getting wrong results: Id operation quantity calculated_total_quantity --------------------------------------------------------- 1 ADD 10.00 10.00 2 ADD 20.00 30.00 3 OVERRIDE 15.00 15.00 4 SUB -5.00 40.00 5 SUB -10.00 30.00 I know that the error is because of the Sum expression, so my questions is if there is any way to reset the Sum expression to start again when the log operations is OVERRIDE. If anyone can help me with this I will be more than grateful. -
how to redirect to a page from botton?
Hello i am newbie using DJANGO , i am trying that when i click on 'Continue' it redirects me to the template carrito.html but it aint working :/ //i've tried this <a href="/base/carrito">Continue</a> // and i've tried this <button type="button"> <a href="{% url '/carrito/' %}">Comprar!</a> </button> i get this example the routes are plantilla/base/carrito.html -
AttributeError: 'NoneType' object has no attribute 'get' when verifying access_token from FE in Django/DRF API
Been trying to fix this for a few days now. Basically, I'm trying to pass an access_token from my Django FE to the Django/DRF BE so it can be verified there for subsequent communication between the two microservices. For reasons that are not clear to me, I am getting the following error from using python-social-auth and social-auth-app-django. Error: [api] Internal Server Error: /api/social/azuread-tenant-oauth2/ [api] Traceback (most recent call last): [api] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner [api] response = get_response(request) [api] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response [api] response = wrapped_callback(request, *callback_args, **callback_kwargs) [api] File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view [api] return view_func(*args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view [api] return self.dispatch(request, *args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch [api] response = self.handle_exception(exc) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception [api] self.raise_uncaught_exception(exc) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception [api] raise exc [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch [api] response = handler(request, *args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler [api] return func(*args, **kwargs) [api] File "/usr/local/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper [api] return func(request, backend, *args, **kwargs) [api] File "/app/users/views.py", line 85, in exchange_token [api] user = request.backend.do_auth( [api] File "/usr/local/lib/python3.8/site-packages/social_core/utils.py", line 251, in … -
Application error - When I uploading my Django app on Heroku
Uploading my Django app on Heroku An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail heroku logs: rn/workers/base.py", line 129, in init_process 2020-11-05T15:09:51.536472+00:00 app[web.1]: self.load_wsgi() 2020-11-05T15:09:51.536472+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-11-05T15:09:51.536473+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-11-05T15:09:51.536473+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-11-05T15:09:51.536474+00:00 app[web.1]: self.callable = self.load() 2020-11-05T15:09:51.536474+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-11-05T15:09:51.536474+00:00 app[web.1]: return self.load_wsgiapp() 2020-11-05T15:09:51.536475+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-11-05T15:09:51.536475+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-11-05T15:09:51.536476+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 350, in import_app 2020-11-05T15:09:51.536476+00:00 app[web.1]: __import__(module) 2020-11-05T15:09:51.536476+00:00 app[web.1]: File "/app/newspaper_project/wsgi.py", line 12, in <module> 2020-11-05T15:09:51.536477+00:00 app[web.1]: from django.core.wsgi import get_wsgi_application -
How to assign users in groups from Django views?
I have CRUD operations for users, which can be done only from the admin role. I have 6 different roles, that I made by creating groups and assign users to specific group from the admin panel. My question is is there some way to include these group fields with drop down menu when admin create new user, so he can choose what group to assign the new user but not from the admin panel? any help would be appreciated :) model.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email username = models.CharField(max_length=30, blank=True, default='') is_superuser = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) is_employee = models.BooleanField(default=True) is_headofdepartment = models.BooleanField(default=True) is_reception = models.BooleanField(default=True) is_patient = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) forms.py class UserForm(ModelForm): class Meta: … -
Regrouping in Django Template With Grouping in views
I have a model with different forginekey wish I could like to group it by student. I was successfully done that but in my template, I want to nested the result or regroup it by subject according to students. model.py class Result(models.Model): examtype = models.ForeignKey(ExamType, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(SubjectAppointment, on_delete=models.CASCADE) test = models.FloatField() exam = models.FloatField() total = models.FloatField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.total = self.test + self.exam super().save(*args, **kwargs) def __str__(self): return self.student.matricnumber def get_result_total(self): return int(float(f'{self.test + self.exam}')) views.py def ReportView(request): template_name = 'teacher/report.html' score = Result.objects.values('student', 'exam', 'test', 'subject__subject__name').annotate(student_totalscore=Sum('total')).annotate(attending=Count('subject')) print(score) context = { 'score': score, } return render(request, template_name, context) report.html {% for s in score %} {% regroup score by s.student as student_list %} {% for a in student_list %} <!-- {% for b in a.list %} --> <tr> <td>{{ b.subject__subject__name }}</td> <td>{{ b.test }}</td> <td>{{ b.exam }}</td> <td></td> <td></td> <td></td> <td></td> </tr> <!-- {% endfor %} --> {% endfor %} {% endfor %} -
ordery_by is not working for boolean field in Django
i am running the query, but the ordery_by is not working for boolean field value. Any help, would be much appreciated. thank you. queryset = ShopOffer.objects.filter(added_by__user_id=user).order_by('-is_active')