Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model filter with default value
I wanna do something similar as here, but I want a filter with default value if it's not passed as parameter. E.G: class MyUserManager(models.Manager): def get_queryset(self, is_active=True): return super().get_queryset().filter(is_active=is_active) class User(AbstractUser): # ... manager = MyUserManager() So I don't have to remember to filter with is_active=True every time since I will want only active users all the time, except when I intentionally pass is_active=False. I don't think get_queryset() override works for this case. -
Django - Set what model for data type geometry(MultiPolygon) in database?
In my database, I have a column like this: (Around 2000 letters) Geo 0106000000010000000103000000010000004B0000001F00004022A45A40F9FFFF5FEA463540E8FFFF5F2BA45A400D000040C3463540020000E081A45A40F5FFFF3F8E463540E8FFFF5F7BA45A4009000080174635401200000083A45A40F7FFFF7FD0453540F1FFFFDFAAA45A40FFFFFFDF9E453540F3FFFFBFB0A45A4004000060D3453540020000E0CDA45A4000000000A0453540070000A0DDA45A400C0000205A453540E1FFFFBFE5A45A4004000000DB443540E3FFFF9FFFA45A40FAFFFF1FC3443540160000C052A55A4002000080C1423540E3FFFF9F3FA55A40000000A0CF413540EEFFFFFF40A55A40FBFFFFDF63413540E8FFFF5F63A55A40FDFFFF5F3D4135401D00006068A55A40FDFFFF5FDD403540FEFFFF1F76A55A400B000060F9403540F5FFFF9F72A55A40FDFFFF5FBD403540E3FFFF9F7FA55A40FFFFFFDFA6403540020000E06DA55A400B00000049403540E6FFFF7F6DA55A40000000A0873F354009000080A3A55A40F9FFFF5FC23E3540E8FFFF5FBFA55A4000000000E03D3540070000A001A65A40FBFFFFDF433E3540FCFFFF3F40A65A40F5FFFF9F663E35400000000064A65A40FAFFFFBF0A3D3540160000C00EA65A40FDFFFFBFAD3C35401F000040AAA55A400B000000C93B3540EAFFFF3F95A55A400A0000A0E83B3540F7FFFF7F7CA55A40010000C0583C3540140000E060A55A400C0000207A3C3540020000E0F5A45A40FCFFFF9F843B354000000000B0A45A40F5FFFFFF263B3540040000C04FA45A400E0000A0433B3540E3FFFF9F13A45A400D000040EB3A3540140000E0F4A35A40070000603E3A3540120000000BA45A400A0000A038393540070000A0E5A35A4007000060FE373540F7FFFF7F18A45A40FEFFFF7FAE353540FCFFFF3F10A45A40060000E064353540160000C0DEA35A4009000080C7343540DFFFFFDFEBA35A40F5FFFFFF863235401A000080B2A35A40F5FFFF9FBE313540E8FFFF5F97A35A40F9FFFFFFC9313540FEFFFF1F46A35A40F8FFFFDF78313540F5FFFF9F22A35A40F5FFFFFF46313540EAFFFF3F05A35A40F3FFFFBFE4303540140000E0F4A25A40F3FFFFBFE4303540040000C0B7A25A40030000A042313540160000C0AEA25A40F5FFFFFF763135401D000060A4A25A400200008059323540E8FFFF5F83A25A400B00000019333540FEFFFF1F76A25A40FCFFFFFFCC333540120000004FA25A4000000000A8343540E6FFFF7F1DA25A40F9FFFF5F2A373540E8FFFF5FF3A15A40F5FFFF9FC6373540E6FFFF7FEDA15A40080000C0CE383540DFFFFFDFD3A15A40060000E014393540E6FFFF7F7DA25A40070000A09D393540FCFFFF3FECA25A40000000A0BF3B3540F5FFFF9F16A35A40060000E0E43B3540160000C02EA35A40F8FFFF3FC13C35401F0000402AA35A400C000020523D3540160000C046A35A40F2FFFF5F143E3540E1FFFFBF6DA35A400C000080723E35400F000020D1A35A400D0000E04A403540140000E0B4A35A40020000E099403540F9FFFF5F9AA35A40060000E084413540E8FFFF5FB3A35A40090000E017423540F7FFFF7FA8A35A40F5FFFF3FAE423540FCFFFF3FC4A35A400A00004038433540EEFFFFFFA4A35A40030000A0E2433540F1FFFFDFFEA35A40060000E024443540ECFFFF1FDBA35A4000000000B04635401F00004022A45A40F9FFFF5FEA463540 Data type of this column is geometry(MultiPolygon) I dont know what to assign for this column in model of Django Right now I set models.TextField() -
How can i filter products of shop and display them using a for loop in django
Am developing an online mall. The mall consists of different shops. Each shop has got different owners (shop managers) hence they can add different products The homepage of my project returns all shops in the mall I would like the mall to function this way The owner of the shop adds products to his/her shop A visitor is able to see different shops (all) at homepage When a visitor clicks a link on a particular shop, he/she should be able to see products of that shop On this page (products page of a clicked shop), the customer can proceed and add the product to the cart, and submit order I would have liked to use the multitenancy but am yet to understand as used here https://books.agiliq.com/projects/django-multi-tenant/en/latest/ I have reedited the codes to fit the question, any mistype is yet to receive a correction down below in the comment Below are some of my files used, if in need of more files for clarity am ready to share index.html This should show all shops in the mall {% for shop in shops %} <div> <div> <a href="{% url 'ckmall_shop_detail' shop.pk %}"> <img src="/uploads/{{ shop.shop_logo }}" alt="{{ shop.shop_name }}"> </a> </div> <div> … -
Username and password fields in Django model
I am new to Django and I need help creating models for my User class. Do I need to add username and password field to this class to save in my database? If so, how do I define the fields and to ensure it is protected. If I have : id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) username = ?? password = ?? I appreciate all the help! -
is there a way to load django website on mobile device during development?
I want to see what the website would look like on mobile web browsers during development like I could at localhost in the desktop web browser. Is there any way I could do that? Thanks! -
Why can I only populate 1 row in webpage with Django framework?
This is now driving me crazy. I used to get only the last row, whatever it was, but now I only get a specific row {{ item.Basil_qty_futurecol, which happens to be the last, and nothing else. I cannot see what is different from the rest of the tables that makes it and only it work. I've gone over it with a fine toothed comb and found nothing wrong. I just know it will be totally obvious once it's pointed out to me. The UI with only Next Order Basil Qty rendered The code Settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.4. """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent print(BASE_DIR) # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#####################################################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' # Application definition INSTALLED_APPS = [ 'myapi.apps.MyapiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
How to set up ManyToOneRel in Django Models
I have 2 tables Voucher (with all information of a voucher) and VoucherCustomer (listing number of vouchers that a user has used) Here is my model: class Voucher(models.Model): code = models.ForeignKey('VoucherCustomer', related_name= 'voucher_code', on_delete = models.CASCADE) (1) start_at = models.DateTimeField() (2) end_at = models.DateTimeField() (3) usage_limit_per_customer = models.BigIntegerField() (4) times_used = models.BigIntegerField() (5) usage_limit_daily = models.BigIntegerField() (6) times_used_daily = models.BigIntegerField() (7) is_global = models.BooleanField(blank=True, null=True) (8) is_active = models.BooleanField() (9) class VoucherCustomer(models.Model): voucher_code = models.ManyToOneRel(field = "voucher_code", field_name = "voucher_code", to = "code")(1) customer_id = models.IntegerField() (2) times_used = models.BigIntegerField(blank=True, null=True) (3) created_at = models.DateTimeField(blank=True, null=True) (4) updated_at = models.DateTimeField(blank=True, null=True) (5) Here is the sample data: +++++++ Voucher ++++++++ (1) (2) (3) (4) (5) (6) (7) (8) (9) TEST01 | 2020-11-30 17:00:00 | 2021-03-01 16:59:59 | 100 | 1124 | 5000 | 6 | true | true +++++++ VoucherCustomer ++++++++ (1) (2) (3) (4) (5) TEST01 10878 9 2020-12-03 02:17:32.012722 2020-12-08 10:32:03.877349 TEST01 12577 1 2020-12-02 07:17:34.005964 2020-12-02 07:17:34.005964 TEST01 8324 18 2020-12-02 07:49:37.385682 2021-02-01 14:35:38.096381 TEST01 7638 2 2020-12-02 08:17:46.532566 2020-12-02 08:17:46.532566 TEST01 3589 1 2020-12-02 14:57:01.356616 2020-12-02 14:57:01.356616 I am not quite sure about how and what to put in parameters of models.ManyToOneRel of Django. when I … -
wrap multiple values in single JSON and store in model - Django
I want to store multiple inputs in single JSON field. this is the order table , there is a "attribute_field" I want to store the attributes in this field as JSON. models.py class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.ImageField('Product Quantity', max_length=10, default=500) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00) views.py def order(request, id): if request.method == 'POST': customer_id = request.user.user_id product_id = id try: size = request.POST['size'] except MultiValueDictKeyError: pass try: Colour = request.POST['Color'] except MultiValueDictKeyError: pass try: Paper_Choice = request.POST['PaperChoice'] except MultiValueDictKeyError: pass return render(request, 'user/order.html') here I have not done form save method, but let me explain what I want to do. I want to wrap SIZE, COLOR, PAPER CHOICE is single JSON and store it in attribut_values field in model but don't know how to do, can you please explain it to me. -
How to send Ajax request to different url of same server
I am sending an ajax request to my server like this : var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: function (data) { var obj = JSON.parse(data)[0].fields; console.log(obj); } }); The url becomes http://127.0.0.1:8000/home/post/api/getnews/home/post/title , if I am at http://127.0.0.1:8000/home/post But , I want it to be : http://127.0.0.1:8000/api/getnews/home/post/title Any Suggestion.. -
How to implement django session authentication in thrid party website?
Help me implement Django session based authentication in thrid party website. I'm building the javascript library that served from django server but client can place it in any website and think of this like google oauth popup where you click the login with google button and the popup will appear once you logged in popup will disappear and whenever you make the call server identifie as the authenticated request. Whatever I tried after the popup closed I can't able to make the authenticated request even though user is logged in when I browse it in the new tab. For your information I'm making this call using fetch credentials: include So far I've this in my settings.py file. I'm using django-cors-headers and I've these settings. CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True WHITENOISE_ALLOW_ALL_ORIGINS = True I need to know what settings should I adjust so that I can make the authenticated requests from another domain to django server. -
TypeError when redirecting to Django URL
Very simple one but cannot seem to find the issue : TypeError at /userlookup/foo userlookup() got an unexpected keyword argument 'username' views.py def userlookup (request, username): if request.method == "GET": UserId = User.objects.get(user=username).id UserPosts = Post.objects.filter(user=UserId) UserPosts = list(UserPosts.order_by("-timestamp").all()) p_all = Paginator(UserPosts, 10) page_number = request.GET.get('page') page_obj_all = p_all.get_page(page_number) return render(request, "network/userlookup.html",{ "page_obj_all": page_obj_all, "allposts": UserPosts, }) url.py path("user/<str:username>", views.userlookup, name="userlookup"), html (Properly looping, but shortening for visibility) (Some Stuff) <div class="card-body"> <h5 class="card-title" id="Username">{{ allpost.user }}</h5> <a href="{% url 'userlookup' allpost.user%}">{{ allpost.user }} 's profile</a> <p>User ID = {{ allpost.user.id }}</p> </div> (Some Stuff) Question : Why the error? I understand that allpost.user = foo. I pass "foo" to the URL called userlookup. The URL do accept a STR called username. My function then grab the username, fetch the data based on the username and (should) return "username/foo" with the relevant data. Hope you can help! -
Django: How to dynamically store user data in sessions?
I am trying to create different django-allauth signup forms for different types of users. So different forms for different user types. Once a user selects a user type (example: "I want to sign up as a vendor"), they should be redirected to a different form where they will fill up other signup and profile details before email confirmation and login. I have one signup form working, but not multiple. Currently I have a general purpose form assigned to users/accounts/signup/ but I also want a vendor specific signup form assigned to users/accounts/signup_vendor/. The best possible solution I've found is provided by the django-allauth author, stating: "There are multiple ways to approach this. You could store the desired user type into the session, and dynamically construct your form fields depending on that. Or, you could allow for the user to make up his mind at any time by simply adding a "profile type" to the sign up form. Basically, the fields in the signup form would have to be the union of all possible fields, and perhaps you would want to add some Javascript to dynamically show/hide some fields depending on the type chosen. I would recommend an approach where the user … -
Why Django Validates Multiple Forms
I have a settings template which includes different forms. When I submit a form and it is not valid, other forms are asigned as invalid and shows validation errors. What I want is showing error just for the form which is submitted. Is there a solution for this problem? Here is my code. I can share html and form codes if needed. user = request.user if request.method == "POST": edit_profile_info_form=EditProfileInfo(request.POST or None) edit_account_form=EditAccountForm(request.POST or None) context = { "profile_info_form" : edit_profile_info_form, "account_form" : edit_account_form, } if "profile_info_submit" in request.POST: if edit_profile_info_form.is_valid(): first_name=edit_profile_info_form.cleaned_data.get("first_name") last_name=edit_profile_info_form.cleaned_data.get("last_name") user.first_name=first_name user.last_name=last_name user.save() messages.success(request,"Changes saved") return redirect("user:settings") return render(request,"settings.html",context=context) if "account_submit" in request.POST: if edit_account_form.is_valid(): username = edit_account_form.cleaned_data.get("username") user.username = username user.save() messages.success(request,"Changes saved") return redirect("user:settings") return render(request,"settings.html",context=context) else: edit_profile_info_form=EditProfileInfo(initial{"first_name":user.first_name, "last_name":user.last_name}) edit_account_form=EditAccountForm(initial={"username":user}) context = { "profile_info_form" : edit_profile_info_form, "account_form" : edit_account_form, "password_form" : edit_password_form, "delete_form" : delete_account_form, } return render(request,"settings.html",context=context) -
django ArrayField PositiveSmallInteger admin multiple choice widget
I'm using PostgreSQL and I have the following model: STUDY_LANGUAGES = ( (1, "1st"), (2, "2nd"), (3, "3rd") ) class Test(models.Model): test_field = ArrayField(models.PositiveSmallIntegerField(), choices=STUDY_LANGUAGES, size=3, null=False) Because I used choices kwarg in the field's definition, I have a single select widget displayed on my admin site. I'd like to have a multi-selection widget. In order to do this, I tried all of the mentioned solutions in here and here but none of them works. I receive the following error. How could I achieve my goal? I'm using python 3.7 and django 3.1.5 Traceback (most recent call last): File "python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 1656, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "python3.7/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, … -
Google map not showing in Django index html page
I am using django 3.0 and i have the index.html below. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- GOOGLE MAPS --> <script src="https://maps.googleapis.com/maps/api/js?key=KEY_HIDDEN&callback=initMap" async defer></script> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <script> // Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.036 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } </script> <title>Hello, world!</title> </head> <body> <h3>Map</h3> <div id="map"></div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script> --> </body> </html> This is just a test but google map is not rendering on the page. Is there something that i am doing wrong? i checked console.log, no Error message. Any help would be much appreciated. -
How i can to implement django like a admin site?
I have a implement project about collect data from anywhere in company. The description of project following these below. some user can be create "Collect Data Forms" for every employee in company to fill out infomation. UI for every employee look like admin page such as table and "Add Button" and pagination every employee have seen data of themself only,but owner (The user who created the form)will see all data from every employees. The index page must show all forms. and I would like the form to be show only user who have permission. def get_app_user_list(request): app_list = admin.site.get_app_list(request) for app in app_list: for model in app['models']: model['model_name'] = model['admin_url'].split("/")[-2] return app_list class IndexList(View): def get(self, request): context = { "app_list" : get_app_user_list(request) } return render(self.request,'collectdata/index_list.html',context) I stuck in views.py when pass parameter to view. a parameter is a string of model. i don't know how to match between string and model. class TableList(View): def get(self, request,model_name): context = { "model_name" : model_name, "table" : XXXXXXX.objects.all() } return render(self.request,'collectdata/table_list.html',context) It seems to be a problem in this below path("",IndexList.as_view(),name="index") path("<model_name>/list/",TableList.as_view(),name="list") path("<model_name>/add/",View.as_view(),name="add") path("<model_name>/view/<di>",View.as_view(),name="view") path("<model_name>/edit/<id>",View.as_view(),name="edit") path("<model_name>/delete/<id>",View.as_view(),name="delete") This project will does not use django admin site for some reson. If you have the … -
django_countries not discovered by django in installed apps
Seems I'm following the instructions, but somehow Django doesn't see django_countries as an app. Error: System check identified no issues (0 silenced). February 18, 2021 - 23:56:01 Django version 3.1.4, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/run/media/fv/hdd-1/PROJECTS/django-receipes/django_template/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: (WSGI stuff...) settings.py: INSTALLED_APPS = [ 'django_countries', 'registration.apps.RegistrationConfig', ..... Project tree: . ├── db.sqlite3 ├── django_project │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── myapp │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── readme.rst ├── registration │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── requirements.txt ├── static │ … -
Django REST Framework PDF Generation
I am currently developing the back-end for a mobile application using Django REST Framework. The app has a feature where the user can request a pdf report. I am not sure whether to use ReportLab to generate the report or to create an html template and then convert that to a pdf. -
Django Channels - Duplicates with consumers on multiple servers with load balancer with separate redis server
Issue concerns duplicate messages received thanks to having multiple Django servers, with django channels consumers, accessing a separate redis server. I am running 2 identical instances of my Django server with a load balancer. The channels consumers in these servers access a separate redis server. The issue is that currently I am receiving duplicate messages as I think each consumer is separately fetching from redis and sending to the destination. (If I turn one of the servers off my duplicate messages go away). Wondered what the common / best solution to this was? One thought was trying to target different databases redisurl/0, redisurl/1 for each server ... however this raises issues as I don't know to which one my load balancer will direct traffic for other parts of the application. Thoughts appreciated hahah! Using: Django 2.2 Channels 2.4.0 Channels-Redis 3.1.0 Redis 6 -
Django pagination by date (week)
I am making a website that displays this week's soccer games from the day you open the website to six days later (current week), and i want to paginate by date. example <previous> <19 feb - 25 feb> <next> then when i press next <previous> <26 feb - 4 march> <next> in views.py. matches is a list of dictionaries, each dictionary is a single game that contains the date of the game and other info and its sorted by date def home(request): start = datetime.now().date() end = today + timedelta(6) matches = request_games(today, after_week) return render(request, "sporty/home.html",{ "matches": matches, "start" : start, "end": end }) in home.html {% for match in matches %} //match info {% endfor %} -
Django Logging: Output all Logger messages to a file
I'm trying to do some debugging and cannot figure out how I can get all the usual server output that I would normally get on a development server. Here's my logging file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'catch_all_logger': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'somelogfile.log'), }, }, 'loggers': { 'django': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.server': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.security.DisallowedHost': { 'handlers': ['catch_all_logger'], 'propagate': True, }, 'django.security.csrf': { 'handlers': ['catch_all_logger'], 'propagate': True, }, }, } When I do cat somelogfile.log, I get almost useless information: Bad request: /url/where/bad/request However, the documentation says that django.server for instance will show status code and a message with it as extra context on the INFO level with HTTP 5XX as ERROR and 4XX as WARNING. Do I have the logging level setup incorrectly? Would love some guidance as I'm puzzled. -
Multiple Values into initial form data
I am attempting to render a form which will have certain fields prefilled based on the Primary Key. Im currently only able to successfully prefill one field (Project). Do I have to define all the other fields in my view? This is my Model class Document(models.Model): DOC_TYPE = ( ('Proposal', 'Proposal'), ('Invoice', 'Invoice'), ('Receipt', 'Receipt'), ('Other', 'Other') ) docName = models.CharField("Document Name", max_length=1000, null=True) docType = models.CharField("Document Type", max_length=10, null = True, choices=DOC_TYPE) company = models.ForeignKey('project.Company', on_delete=models.PROTECT, blank = True, null = True) customer = customer = models.ForeignKey('customer.Customer', on_delete=models.PROTECT, null = True) project = models.ForeignKey('project.Project', on_delete=models.PROTECT, blank = True, null = True) docFile = models.FileField("Document", upload_to='newdocuments/') note = models.TextField("Note About Document", blank = True, null = True) dateUpload = models.DateTimeField(auto_now_add=True) This is my View def ProjectAddDocument(request, pk): project = Project.objects.get(id=pk) form = ProjectAddDocumentForm(initial={'project':pk}) if request.method == 'POST': form = ProjectAddDocumentForm(request.POST) if form.is_valid(): form.save() return redirect('file_list') context = {'form':form} return render(request, 'project/adddocument.html', context) This is my URL path('adddocument/<int:pk>/', views.ProjectAddDocument, name='proj_document'), This is my Form class ProjectAddDocumentForm(ModelForm): class Meta: model = Document fields = ['docName', 'docType', 'company', 'customer', 'project', 'note', 'docFile'] -
How to validate and redirect on fail in CreateView get
I am trying to do some sanity checks in a CreateView get request and want to redirect user to a different URL in case the sanity checks fail. How can I achieve this? For example: class JobCreateView(LoginRequiredMixin, CreateView): model = Job form_class = JobFormClass # This does not let me redirect on return since a dictionary return is expected and redirect is not acceptable def get_context_data(self, **kwargs): if not self.request.user.is_superuser: messages.add_message( self.request, messages.ERROR, _("You are not authorized! Bugger off!") ) return redirect("home") # The user is good to proceed return super().get_context_data(**kwargs) This gives me back the following error: context must be a dict rather than HttpResponseRedirect. I am using get_context_data because I don't know what to use to be honest. Feel free to suggest something better. My use case in not really a super user check, that just felt like a better example -
Best practice for saving new model instance in Django Rest Framework
I'm new to DRF and I can't wrap my head around where to save new model instances when I POST to my endpoints. I need to overwrite my def create() method because I'm managing nested objects in my queries. I've noticed that I can save new instances from the model Serializer ( def create(self, validated_data)) but also from the associated class view ( def create(self, request)) What's the best practice here? I'm pretty sure I'm confusing major concepts, please indulge me! -
I try to build Follow system, I have error when i try to get the pk of the vested account
I try to build follow system in Django, My code Filed when I try to get the pk of the current vested account which I try follow them The Error message NoReverseMatch at /account/3/ Reverse for 'add-follower' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/follower/(?P[0-9]+)/add$'] my models class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="follow") My views class AddFollwers(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): account = Account.objects.get(pk=pk) account.following.add(request.user) return redirect('account', pk=account.pk) The urls urlpatterns = [ path('<int:user_id>/', account_view, name="view"), path('follower/<int:pk>/add', AddFollwers.as_view(), name='add-follower'),] The Template <form action="{% url 'account:add-follower' pk=pk%}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-success">Follow</button> </form>