Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My widget doesn't work. How can I fix it?
I try to make a radioselect form field, but it doesn't work. I tried to do it in several ways. I can't understand the problem. Models.py: class Check_Result(models.Model): Text = models.ForeignKey(Text, blank=True, on_delete=models.CASCADE, null=True) essay = models.ForeignKey(Essay, blank=True, on_delete=models.CASCADE, null=True) score = models.IntegerField(null=True, blank=True) checker = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) essay_rating = models.IntegerField(default=0) Forms.py: class get_check(forms.ModelForm): class Meta: model = Check_Result exclude = ('Text', 'essay', 'score', 'checker') #widgets = {'essay_rating': forms.RadioSelect(attrs={'name': 'rating'}, choices=('1', '2', '3', '4', '5'))} def __init__(self, *args, **kwargs): super(get_check, self).__init__(*args, **kwargs) self.fields["essay_rating"] = forms.ChoiceField( widget=forms.RadioSelect(), choices=('1', '2', '3', '4', '5') ) html: <div> <!--{{ form.essay_rating }} --> {% for radio in form.essay_rating %} {{ radio }} {% endfor %} </div> Also, what is the right way to write in html: with cycle or without it? Thank you for any help! -
Django model object query misbehaving
I am trying to display the contents of a profile which is a model that is linked to the inbuilt User model. Everything works fine, strangely except the last object entry of the model. For example if user8 is the last model object logging in with user1 to user 7 is working with all the contents inside verified belonging to the current user. but when I login using the last object ie. user8 in this case I get a Page 404 not found : No (Model name) matches the given query error. to be bit more clear, now if I create another user called user9 , Now I am able to login with user8 but not with the lastly created user9. **views.py : ** # Create your views here. def home(request): if request.user.is_authenticated: contextvar = Post.objects.all() user_content = get_object_or_404(user_profile, pk = request.user.pk) # user_content = user_profile.objects.get(pk=request.user.pk) # user_content = user_profile.objects.get(pk='8') print("the current users id is " , request.user.pk) return render(request,'homepage.htm', {'context':contextvar , 'user_content' : user_content , "up" : request.user.pk }) else: contextvar = Post.objects.all() return render(request,'homepage.htm', {'context':contextvar}) models.py : from django.db import models from django.contrib.auth.models import User # Create your models here. class user_profile(models.Model): #using default User model by linking … -
Passing user id to an inline_formset factory
I am trying to implement an inlineformset_factory and I can't seem the figure out how to pass the user id as created_by to the form. I get this error AttributeError: 'ItemForm' object has no attribute 'created_by' I can't figure out how I can pass the request.user to the Item. Any kind of help would be appreciated. Thank you! items/models.py: class Item(models.Model): invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name='items', null=True, ) name = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='items') invoices/models.py: class Invoice(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invoices') invoices/views.py: class InvoiceCreateView(LoginRequiredMixin, CreateView): model = Invoice form_class = InvoiceForm template_name = 'invoices/invoice-create.html' login_url = 'account_login' # Pass the request to the form to allow filtering by user id def get_form_kwargs(self): kwargs = super(InvoiceCreateView, self).get_form_kwargs() kwargs.update({'request': self.request}) return kwargs # Added this because form was not saving user id def get_initial(self): self.initial.update({'created_by': self.request.user}) return self.initial def get_success_url(self): return reverse_lazy('invoices:invoice_detail', kwargs={'pk': self.object.id}) # Inline formsets from medium post https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d def get_context_data(self, **kwargs): data = super(InvoiceCreateView, self).get_context_data(**kwargs) if self.request.POST: data['items'] = ItemFormset(self.request.POST) else: data['items'] = ItemFormset() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save() if items.is_valid(): items.instance = self.object items.save() return super(InvoiceCreateView, self).form_valid(form) # End medium post stuff invoices/forms.py: … -
How to use Async views and urls in Django?
I build an application using django that can get data from an api. At first, I used the python requests to connect to the api and it's working. But the problem is I find it a little bit slow when it comes to the web page loading speed. So i decided to use async function in my codes, but i keep getting an error . Here's my codes: views.py async def e_sign_page(request): start_time = time.time() template_name = "e_sign/e_sign_table.html" url = f"API_URL_HERE" async with aiohttp.ClientSession() as session: esign = [] doc = asyncio.ensure_future(fetch(session, url)) esign.append(doc) docs = await asyncio.gather(*esign) end_time = time.time() total = end_time - start_time print("Code Execution Time : ", total) context = { 'docs' : docs } return render(request, template_name, context) urls.py from django.urls import path from e_sign.resources.e_sign import ( e_sign_page, ) urlpatterns = [ path("e-sign-page/", e_sign_page, name = "e_sign_page"), ] utils.py async def fetch(session, url): async with session.get(url) as resp: assert resp.status == 200 return await resp.json() Here's my errors that I'm receiving 'coroutine' object has no attribute 'get' How to fix this? -
Get the value of the token from authentication in Django
I have made a customized token Authentication for my app. It is based on a specific model that stores the tokens that I will be generating. class ApiKeyAuthentication(TokenAuthentication): keyword = "api-key" def get_token_from_auth_header(self, auth): auth = auth.split() #validations here def authenticate(self, request): auth = get_authorization_header(request) token = self.get_token_from_auth_header(auth) if token: return self.authenticate_credentials(token) def authenticate_credentials(self, key): try: token = TokenModel.objects.get(key=key) except TokenModel.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid Api key.") user = User.objects.first() return (user, token) Is there a possibility to get the values of the token that was returned upon authenticate_credentials? I have to access a field from that model ( TokenModel ) on the views.py. -
Cannot group by an aliased field in Django
I have two django models (db tables): class Assignment(models.Model): title = models.CharField(max_length=255) # Some fields ... class Task(models.Model): assignment = models.ForeignKey(to=Assignment, on_delete=models.CASCADE, related_name='tasks') deadline = models.DateField() There can be many tasks related to a single assignment. The deadline of an assignment is the latest deadline from its children tasks. Let's assume I want to group assignments by deadlines statuses and , e.g. If the deadline of the assignment is in 5 days, then status is 'DUE_SOON', If the deadline has passed, then status is 'EXPIRED' Otherwise, status is 'OK' Here is what I came up with: I am annotating new field called date_diff which is difference between the maximum of the children's deadline today's date (e.g. if deadline is 2021-02-25 and today is 2021-02-19, then date_diff is 6) Then I am annotating a field deadline_status, which is calculated based on date_diff (e.g. if date_diff < 0, then 'EXPIRED', etc.) And finally, I group the queryset by the deadline_status Assignment.objects.annotate( date_diff=ExpressionWrapper( Max(F('tasks__deadline')) - date.today(), output_field=IntegerField() ), deadline_status=Case( When(date_diff__lt=0, then=Value('EXPIRED')), When(date_diff__lte=5, then=Value('DUE_SOON')), default=Value('OK'), output_field=CharField() ) ).order_by().values('deadline_status').annotate( count=Count('deadline_status') ) But, when I run the code above it raises an error: Cannot compute Count('deadline_status'): 'deadline_status' is an aggregate What is the problem? -
Django - How to make multiple self join tables?
I have a table like this: Its model: class RLocation(models.Model): id = models.CharField(primary_key=True) Parent_ID = models.CharField(unique=True, max_length=255, blank=True, null=True) Name = models.CharField(max_length=255, blank=True, null=True) Geo = models.TextField(blank=True, null=True) Sample data: ID Parent_ID Name Geo 1 Null City A ABC1 City A 12 1 District 1 ABC002 District 1 in City A 123 12 Ward 1 ABC002003 Ward 1 in District 1 in City A 25 1 District 5 XYZ004 District 5 in City A 251 25 Ward 4 XYZ002006 Ward 4 in District 5 in City A Normally, I got the ID of the ward (third in the hierarchical). I need to to do query to get the GEO of the city (first in the herarchical). In query (PostgreSQL), I would do something like this : SELECT l1.Geo FROM routing.r_location l1 LEFT JOIN routing.r_location l2 ON l1.ID= l2.Parent_ID LEFT JOIN routing.r_location l3 ON l2.ID= l3.Parent_ID WHERE l3.ID= '123' Here is my so far code, but I dont really like it: Parent_ID_lv3 = RLocation.objects.filter(ID = 123).values('Parent_ID') Parent_ID_lv2 = RLocation.objects.filter(ID = Parent_ID_lv3).values('Parent_ID') Geo_lv1 = RLocation.objects.filter(ID = Parent_ID_lv2).values('Geo') -
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) -
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. -
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, … -
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.