Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BranchSemanticsTemplate has no field named 'semantics_tmplt'
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Migration # Generated by Django 3.1.7 on 2021-03-20 10:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('clients', '0001_initial'), ('semantics', '0001_initial'), ] operations = [ migrations.CreateModel( name='BranchSemanticsTemplate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('archived', models.BooleanField(db_index=True, default=False, verbose_name='Archived')), ('flag', models.BooleanField(default=False, verbose_name='Flag')), ('branch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='clients.branch', verbose_name='Branch')), ('semantics_level_two', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='semantics.semanticsleveltwo', verbose_name='Level 2')), ], options={ 'verbose_name': 'Branch template - branch- semantics - semantics template', 'verbose_name_plural': 'Branch template - branch- semantics - semantics template', }, ), migrations.AddConstraint( model_name='branchsemanticstemplate', constraint=models.UniqueConstraint(fields=('branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt'), name='semantics_branch_template'), ), ] Traceback (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, … -
How to add placeholder for search field in admin.py
How can I add placeholder in django for a search field I am using in admin.py with Django3.1 as: class MyAdmin(admin.ModelAdmin): list_display = ['community'] search_fields = ['community'] Is there any way to do something like this? class MyAdmin(admin.ModelAdmin): search_fields = ['community'] search_input_placeholder = 'Please input community id' -
Finding correlation in Django
I am working on a practice Django prooject. I have a small data frame with three columns Price, Sale, Reviews. I need to calculate correlation between all columns. User will see a Bootstrap form with select menu with three options Price, Sale, Reviews. If user selects Price it will calculate correlation with other two variables. here is my code Templates: <form action="/home/corelation/" method=post> {% csrf_token %} <div class="form-group"> <label for="variable">Voucher</label> <select name="variable" id="variable" class="form-control"> <option>Price</option> <option>Sale</option> <option>Reviews</option> </select> </div> <button type="submit" class="btn btn-success">Submit</button> </form> Views.py def corelation(request): if request.method == "POST": data = {'Price':[40, 50], 'Sale':[33, 27], 'Reviews':[25, 11]} df = pd.DataFrame(data) var_input = request.POST.get('variable') corr = df.corr() var_corr = corr['var_input'].sort_values(ascending = False) print(var_corr) Error Exception Type: KeyError Exception Value: 'var_input' -
django-cte leading zeros in query
How can I add leading zeros to an integer field in a Django query? I want to add an extra field in the Django query below with leading zeros add to the id. something like idwithzeros = str(id).zfill(6), but this is not working Example: Here I use django-cte (https://github.com/dimagi/django-cte): def ProjectTree(ProjectID): def get_tree(childs): return Project.objects.filter( # start with root nodes id = ProjectID ).values( "id", "parent", path=F("id"), depth=Value(0, output_field=IntegerField()), ).union( # recursive union: get descendants childs.join(Project, parent=childs.col.id).values( "id", "parent", path=Concat( childs.col.path, Value(";",output_field=TextField()) ,F("id"), output_field=TextField(), ), depth=childs.col.depth - Value(1, output_field=IntegerField()), ), all=True, ) childs = With.recursive(get_tree) return (childs.join(Project, id=childs.col.id) .with_cte(childs) .annotate( path=childs.col.path, depth=childs.col.depth, ) .order_by("path") ) -
'choices' must be an iterable containing (actual value, human readable name) tuples django 3.1
whene i want to makemigration it show me this error user.User.allowd_to_take_appointement: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. user.User.type_of_user: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. this is my models.py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class AllowdToTakeAppointement(models.TextChoices): YES = ('yes', 'Yes') NO = ('no', 'No') class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement, default=AllowdToTakeAppointement.YES) def is_doctor(self): return self.type_of_user == TypeOfUser.DOCTOR def can_add_appointment(self): return self.type_of_user == AllowdToTakeAppointement.YES i'm using django 3.1 -
Submit Button in django bootstrap form doesn't work
I'm begginer in making django projects. I'm creating easy app which plots earthquakes positions on map with data from api. One of features of my app is the possibility to paste range of dates to my api query. I made the form which includes the datepicker and the code in views that i suppose should handle it. I have problem because my submit button that should grab data from datepicker doesn't work. Or may be i did something wrong in my views and it cannot take data from post method to variable datebeg and dateend Any idea? views.py def graph(request): #=========data========================================================================= datebeg='2021-03-19' dateend='2021-03-20' if request.method == 'post': datebeg=request.POST['datebeg'] dateend = request.POST.get("dateend") if datebeg=='': datebeg='2021-03-21' if dateend=='': dateend='2021-03-21' graph.html <body> <div class="container my-container"> <form action="{% url 'graph' %}" method="post"> {% csrf_token %} <div class= "row my-row"> <div class="col-4 my-col"> Trzęsienia ziemi z zakresu dat: </div> <div class="col-4 my-col"> od: <input type="date" placeholder="0" name="datebeg" size="1" /> </div> <div class="col-4 my-col"> do: <input type="date" placeholder="0" name="dateend" size="1" /> </div> <a class="btn btn-primary" type="submit" href="{% url 'graph'%}" >Pokaż na mapie</a> </div> </form> </div> graph/urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('', views.graph,name='graph'), ] -
How to create a firefox health check
I have written some functional tests for a django app which I test with selenium in a docker container. I use circleci for ci/cd. I have also written a health test for selenium hub to ensure it is up and running before the testing can begin. It looks like below: #!/usr/bin/env python3 import logging import time import urllib.request logger = logging.getLogger("selenium-hub-health-check") status = 0 while status != 200: try: f = urllib.request.urlopen('http://selenium-hub:4444/wd/hub/status') status = f.status logger.info("The Selenium hub is ready!") f.close() logger.info("Closing this session") time.sleep(1) except Exception as e: logger.error(e) time.sleep(1) pass This one runs fine. However, recently, I have started noticing the error below in one in four tests which I believe comes from the firefox service that I'm also using as the browser not being ready. ERROR: test_visitor_can_access_the_about_page (functional_tests.navigation.ftest_endpoints.EndpointsVisitorTest) When a user goes to the browser and types the domain with the ---------------------------------------------------------------------- Traceback (most recent call last): File "/teke/common/tests/base_function_tests.py", line 8, in setUp self.browser = webdriver.Remote( File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Error forwarding the new … -
What is the best way to implement "liking" a post with Django?
I am making a blog as my first project with the Django REST framework and I want to add the ability to like a post. I have seen two different ways that liking a post can be implemented using Django. Firstly, there is the option of creating a different model for likes, as in the following example: class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) post = models.ForeignKey(Post) Secondly, I've also seen likes created in the following way: likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="app_posts") Which version is best? Is the difference not especially important? Is one method more standard and widely practiced? -
How do you fix a memory leak within Django tests?
Recently I started having some problems with Django (3.1) tests, which I finally tracked down to some kind of memory leak. I normally run my suite (roughly 4000 tests at the moment) with --parallel=4 which results in a high memory watermark of roughly 3GB (starting from 500MB or so). For auditing purposes, though, I occasionally run it with --parallel=1 - when I do this, the memory usage keeps increasing, ending up over the VM's allocated 6GB. I spent some time looking at the data and it became clear that the culprit is, somehow, Webtest - more specifically, its response.html and response.forms: each call during the test case might allocate a few MBs (two or three, generally) which don't get released at the end of the test method and, more importantly, not even at the end of the TestCase. I've tried everything I could think of - gc.collect() with gc.DEBUG_LEAK shows me a whole lot of collectable items, but it frees no memory at all; using delattr() on various TestCase and TestResponse attributes and so on resulted in no change at all, etc. I'm quite literally at my wits' end, so any pointer to solve this (beside editing the thousand or … -
How can i get all the product categories a suppliers product belongs
I am working a Supplier Management System. I need to make a particular type of query which I am having issue implementing. I have the user models, and then the user_type which is of two types the suppliers and the admin. Of Course, the filter I need to implement is based of the supplier because only the supplier is able to create product in which they have to specify what categories as well. My Problem: How can I get all categories a supplier products belongs to. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) def get_email(self): return self.email class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" class Category(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name -
How to validate accessToken in Azure AD
I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework. Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API. So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the API. So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not? Is it just we need to make an API call to … -
Django-OIDC with keycloak - OIDC callback state not found in session oidc_states
I am trying to implement Keycloak SSO with Django API using OIDC. Getting below error message after requesting the call to Keyclock as a response SuspiciousOperation at /^oidc/callback/ OIDC callback state not found in session oidc_states! The same thing I did in the Flask framework and it's working as expected. Please find the below details. Django Log: [20/Mar/2021 15:30:57] "GET / HTTP/1.1" 404 2229 [20/Mar/2021 15:31:03] "GET /hi HTTP/1.1" 302 0 [20/Mar/2021 15:31:03] "GET /oidcauthenticate/?next=/hi HTTP/1.1" 302 0 failed to get or create user: Claims verification failed [20/Mar/2021 15:31:11] "GET /oidccallback/?state=UziLDF2ZcE9p2WrUIihUahgUsWdQ8zYQ&code=22d5a22b-16a6-42e3-81ba-9b569a3f1c81.2cd52631-8c4c-4f2e-a718-c908611336a3.81db1495-24af-402d-8244-a82f32bf4355 HTTP/1.1" 302 0 Not Found: / [20/Mar/2021 15:31:11] "GET / HTTP/1.1" 404 2229 Settings: Django settings for keycloakexample project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_vg@)t*rri()^^wm7yl*i&$%gk2h1h%!xk$xms19ceb3*2z&g^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition … -
Public Key not found Django
I'm trying to place this secret key in my env DJPADDLE_PUBLIC_KEY=-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY----- my settings.py from decouple import config DJPADDLE_PUBLIC_KEY = config('DJPADDLE_PUBLIC_KEY') but i get this error DJPADDLE_PUBLIC_KEY not found. Declare it as envvar or define a default value. This is how it looked like previously in my settings file DJPADDLE_PUBLIC_KEY = '''-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY-----''' -
How to add additional fields, like count of objects to ModelSerializer with many=True
I don't know how to add additional fields to my ModelSerializer, which accepts many=True. Here is all my code: ViewSet def list(self, request, *args, **kwargs): contracts = self.request.user.all_contracts serializer = ContractGetSerializer(contracts, many=True, context={'request': request}, ) return Response({"results": serializer.data}, status=status.HTTP_200_OK) ContractGetSerializer serializer. It also has inner Many=True fields class ContractGetSerializer(serializers.ModelSerializer): files = FileModelSerializer(many=True) is_author = serializers.SerializerMethodField('is_author_method') contract_signing_status = serializers.SerializerMethodField('get_recipient_signing_status') def is_author_method(self, foo): return foo.owner.id == self.context['request'].user.id class Meta: model = Contract fields = ['id', 'is_author', 'title','contract_signing_status','files', ] Now my ContractGetSerializer returns a ReturnList with all contracts. How can I add additional fields to that ReturnList and make it a dictionary? I need for instance to return only 5 recent contracts (filtered by timestamp). Also, I need to add total SIGNED contracts, and total PENDING contracts, counting all contracts data, so that my frontend would not need to do this. -
Django template pagination is not working with link
This is my template code for pagination : <div class="paginationWrapper mt-3"> {{match_list.paginator.num_pages}} {% if match_list.paginator.num_pages > 1 %} <ul class="pagination"> {% if match_list.has_previous %} <li> <a href="?p={{match_list.previous_page_number}}{%if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}" class="page-link"><i class="fas fa-angle-double-left"></i></a> </li> {% endif %} {% if match_list.number|add:'-4' > 1 %} <li><a href="?p={{match_list.number|add:'-5'}}">&hellip;</a></li> {% endif %} {% for i in match_list.paginator.page_range %} {% if match_list.number == i %} <li class="active"><a class="page-link" href="javascript:void(0);">{{ i }}</a></li> {% elif i > match_list.number|add:'-5' and i < match_list.number|add:'5' %} <li><a href="?p={{i}}{%if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}" class="page-link">{{ i }}</a></li> {% endif %} {% endfor %} {% if match_list.paginator.num_pages > match_list.number|add:'4' %} <li><a href="?p={{ match_list.number|add:'5' }}">&hellip;</a></li> {% endif %} {% if match_list.has_next %} <li><a href="?p={{match_list.next_page_number}}{% if request.GET.q%}&q={{request.GET.q}}{%endif%}{%if request.GET.sports%}&sports={{request.GET.sports}}{%endif%}{%if request.GET.match_status%}&match_status={{request.GET.match_status}}{%endif%}"><i class="fa fa-chevron-right" aria-hidden="true"></i></a></li> {% else %} <li class="disabled"><span><i class="fa fa-chevron-right" aria-hidden="true"></i></span></li> {% endif %} </ul> {% endif %} </div> And here it is my changelist_view for pagination: def changelist_view(self, request, extra_context=None): match_all = MatchSchedules.objects.filter().order_by('-id') sports = request.GET.get('sports') matchStatus = request.GET.get('match_status') searchs = request.GET.get('q') startDate = request.GET.get('match_datetime__range__gte') endDate = request.GET.get('match_datetime__range__lte') if sports: match_all = match_all.filter(tournament__sports__id=sports) if searchs: match_all = match_all.filter(Q(match_status__icontains=searchs) | Q(competitor_first_name__icontains=searchs) | Q( competitor_second_name__icontains=searchs) | Q(tournament__sports__sport_name__icontains=searchs)) if matchStatus: match_all = match_all.filter(match_status=matchStatus) if startDate or endDate: match_all = match_all.filter(Q(match_datetime__icontains=startDate) | Q(match_datetime__icontains=endDate)) paginator = Paginator(match_all, 10) print(match_all.count()) page = … -
How to add can i add comment form with queryset in Django?
Info: i have sales_item QuerySet in view. i want to approve, decline and add some comments on specific sales_items. Problem: The code below of views file is getting error Sale matching query does not exist. models.py class Authorize(models.Model): APPROVED = 'AP' DECLINED = 'DL' STATUS_CHOICES = [ (APPROVED, 'Approved'), (DECLINED, 'Declined'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sales_item = models.ForeignKey(Sale, on_delete=models.CASCADE, null=True, blank=True) comments = models.TextField(max_length=1000, blank=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=STATUS_CHOICES, default=APPROVED, max_length=2) views.py def SalesListView(request): queryset = Sale.objects.all() auth_form = AuthorizeForm(data=request.POST) if request.method == 'POST': pk = request.POST.get('pk') sales = Sale.objects.get(id=pk) if auth_form.is_valid(): approved = auth_form.save(commit=False) approved.sales_item = sales approved.save() context = { 'sales': queryset, 'form': auth_form } return render(request, 'pending_sale.html', context) -
Open EDX can't decode .weight file, Internal Server error (XBlock)
I'm developing an XBlock in Open EDX, and I'm stuck in the process of serving a static file with .weight extension. The environment is devstack (docker) for Juniper Release. The static file is stored in /edx/var/edxapp/staticfiles, which I want to use it in the js file of my XBlock. The file has the extension .weight, as it contains the weights of a Neural Network (face-api.js). When I try to GET this file, I get a 500 status error, and the message 'utf-8' codec can't decode byte 0xa6 in position 0: invalid start byte. Here some screenshots, GET request of the file (1) GET request of the file (2) I think that the problem is that Django and Python are not able to decode the content of those files, and can't return the proper file. Or maybe there's some trouble with Nginx. Thanks for your help! Joan -
BranchSemanticsTemplate has no field named 'semantics_tmplt'
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Traceback (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, sessions, staticassets, tmplts, toponyms Running migrations: Applying dashboard.0001_initial...Traceback (most recent call last): File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/models/options.py", line 575, in get_field return self.fields_map[field_name] KeyError: 'semantics_tmplt' During handling of the above exception, another exception occurred: 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 "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, … -
How do I fix "improperlyconfigured" error?
Just started learning Django but met with an error right off the bat I got the error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'app.urls' from 'C:\\django tutorial\\mysite\\app\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. these are the files that have my code in it: views.py: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse('Tech with Adil') app.urls.py: from django.urls import path from . import views urlpatters = [ path("", views.index, name='index') ] and mysite.urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app.urls')), path('admin/', admin.site.urls) ] -
Django Rest Framework - problem with filtering data
in my models i have Book and Author with M2M relationship. models.py from django.db import models from django.db import models class Book(models.Model): title = models.CharField(max_length=200) published_date = models.DateField(auto_now_add=False) categories = models.CharField(max_length=300, null=True, blank=True) average_rating = models.FloatField(null=True, blank=True) ratings_count = models.IntegerField(null=True, blank=True) thumbnail = models.URLField(null=True, blank=True) def authors(self): return self.author_set.all() def __str__(self): return f'title: {self.title} \n' \ f'date of publication: {self.published_date}' class Author(models.Model): name = models.CharField(max_length=200) books = models.ManyToManyField(Book) def __str__(self): return str(self.name) in my serializer i'm getting authors from def authors in models.py serializers.py class Meta: model = Author fields = ['name'] class BookSerializer(serializers.ModelSerializer): authors = AuthorSerializer(many=True) class Meta: model = Book fields = [ 'authors', 'title', 'published_date', 'categories', 'average_rating', 'ratings_count', 'thumbnail' ] so in views.py i want to filter books by authors views.py class BooksListAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer filter_backends = (filters.OrderingFilter, DjangoFilterBackend) filter_fields = ['published_date', 'authors'] ordering_fields = ['published_date'] but it gives me this error 'Meta.fields' must not contain non-model field names: authors any idea how can i filter data with authors so i can extract books of given authors. I would like to have a choice of selecting filters. Thanks in advance. -
Export Excel File Using Ceklry Task
I want to download an excel File Using CCelery Task Here is my celery task @celery_app.task(name="download_xls", base=PortalTask) def data_export_download_task(all, object_id ,user_id): user = User.objects.get(id=user_id) master_data = Mymodel.objects.get( object_id=object_id) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(master_data.name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('data.name') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True if all == 'yes': header = get_all_data_header(scenario) else: header = get_vendor_header(scenario) for col_num in range(len(header)): ws.write(row_num, col_num, header[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() if all == 'yes': rows = get_all_data_values(scenario) else: rows = get_vendor_values(scenario) data = [] for each in rows: t = {} for key, value in each.items(): if key in header: if key =="status_id": value = DropDown.objects.get(id = value) t.update({key: value}) t.update({key: value}) a = list(t.values()) data.append(a) for row in data: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) return response Everything is working fine but the return is not working It's failing the celery task It's saying that TypeError: Object of type method is not JSON serializable -
How to display another user's dashboard/profile (Django)
I'm a little lost how to implement a feature whereby the logged in user can view another user's dashboard on clicking View Dashboard. I am getting lost with how to properly set up the urls.py and views.py file so hoping I can get some support here. My JavaScript function (I'm doing most of my front-end rendering through JS): const viewDashboard = function(clickedUser){ console.log("Going to the Dashboard of:" + " " + clickedUser); userName = "/" + clickedUser; window.location.href = userName; }; My urls.py: [...] path('<username>', views.view_dashboard, name='view_dashboard'), [...] My views.py: def view_dashboard (request, username): # If no such user exists raise 404 try: user = User.objects.get(username=username) except: raise Http404 context = locals() template = 'dashboard.html' return render (request, template, context) The error traceback (when clicking on a user called Henry's view dashboard button): Traceback (most recent call last): File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/x/Desktop/Coding/anybody/anybody1/testingland/views.py", line 260, in view_dashboard return render (request, template, context) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) … -
In Django is it possible to delete a range of data from a table whose integer values sum up to a certain value?
Example I have this model models.py class Share(models.Model): member = models.ForeignKey( Member, on_delete=models.CASCADE, related_name='share') week = models.ForeignKey( WeekModel, on_delete=models.CASCADE, related_name='share') month = models.ForeignKey( MonthModel, on_delete=models.CASCADE, related_name='share', blank=True, null=True) year = models.ForeignKey( YearModel, on_delete=models.CASCADE, related_name='share', blank=True, null=True) shares = models.PositiveIntegerField(default=0) jamii = models.FloatField(blank=True, null=True, default=0) fine = models.FloatField(blank=True, null=True, default=0) created_at = models.DateTimeField(auto_now_add=True) date = models.DateTimeField(blank=True, null=True) #weeknumber = models.PositiveIntegerField(blank=True, null=True) monthname = models.CharField(max_length=100) years = models.PositiveIntegerField(blank=True, null=True) class Meta: db_table = 'share' unique_together = [("member", "week")] ordering = ['member__user__username'] natsorted(ordering) Is it possible to query by date the values that add up to a given integer from the share field and delete them? -
Using class based view UpdateView in case change or delete nested model
models.py class Project(models.Model): project_name = models.CharField(max_length=150) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=250) is_done = models.BooleanField(default=False) views.py from django.views.generic import ListView from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from .models import Project class ProjectListView(ListView): model = Project context_object_name = 'projects' class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('projects') project_list.html {% for project in projects %} <p>{{ project.project_name }} - <a href="{{ project.id }}/delete">Delete</a> </p> <ul> {% for task in project.task_set.all %} <li>{{ task.task_name }} - <a href="#">Done</a> - <a href="#">Delete</a></li> {% endfor %} </ul> {% endfor %} How I can use class based view UpdateView for the Project model in case change or delete nested model Task? -
user_logged_in is not working djnago rest framework
I have created registration api and login api using drf and i wanted to store all user login using signals user_loggged_in. it work fine when super user logged in but it doesn't work when user logged in.