Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to structure Django project
I am currently doing an online shopping site in Django. And I have following modules, Admin Moderators Service Packing and shipment Users Shops if I create only one app and write all views in one file, it will be mess. so can I create multiple view files(adminviews.py,modeartorview.py ..) in a single app (be deleting original views.py) or do I need to create different apps for modules can anyone suggest me which one is better? -
Building web applications around TTN: how to best store the data (DynamoDB or PostgreSQL)?
I’m currently thinking about an architecture for a web application with following functionality: Generate sensor data charts (up to years) from an environment sensors that I’ve connected to TTN. I’m aware of Cayenne but I’d like to build my own application. Currently, I’ve already integrated a couple of RaspberryPis over MQTT witih following architecture: RPI → internet connection / MQTT → Amazon IoT & DynamoDB → Query Data from a Django server and show it to the User. I’d like to keep Django, which runs on pythonanywhere.eu, as my backend. I have checked and tried the Amazon AWS Api: https://www.thethingsnetwork.org/docs/applications/aws/index.html I also know the swagger and how to work with it: https://www.thethingsnetwork.org/docs/applications/storage/api.html Is there any restriction on how often a Request can be send? I didn’t find anything. I would just like to reach out for your help to check my options for storing and accessing sensor data. How would you do it? -
Django Queryset with custom property
I have a simple model like below class Parishioner(models.Model): def _age(self): return date.today().year - self.dob.year """Parishioner model""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() age = property(_age) GENDER_CHOICES = [("Male", "Male"), ("Female", "Female"), ("Other", "Other")] gender = models.CharField(max_length=10, choices=GENDER_CHOICES) address = models.CharField(max_length=1000) fathers_name = models.CharField(max_length=500) mothers_name = models.CharField(max_length=500) baptism_certificate = models.ImageField(null=True, upload_to=baptism_certificates_image_file_path) marriage_certificate = models.ImageField(null=True, upload_to=marriage_certificates_image_file_path) As you can see age is a calculated property. I have my viewset like below class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): first_name = self.request.query_params.get('first_name') last_name = self.request.query_params.get('last_name') gender = self.request.query_params.get('gender') address = self.request.query_params.get('address') fathers_name = self.request.query_params.get('fathers_name') mothers_name = self.request.query_params.get('mothers_name') age = int(self.request.query_params.get('age')) queryset = self.queryset if first_name: queryset = queryset.filter(first_name__contains=first_name) if last_name: queryset = queryset.filter(last_name__contains=last_name) if gender: queryset = queryset.filter(gender__contains=gender) if address: queryset = queryset.filter(address__contains=address) if fathers_name: queryset = queryset.filter(fathers_name__contains=fathers_name) if mothers_name: queryset = queryset.filter(mothers_name__contains=mothers_name) if age: queryset = queryset = queryset.filter(age__gte=age) return queryset.filter() All I want is to return obects who has age >= provides value. So if I send a request to this url http://localhost:8000/api/parishioners/?age=32 I'm getting this error --> Cannot resolve keyword 'age' into field So how can I use this url http://localhost:8000/api/parishioners/?age=32 and get objects who has age … -
Django User.date_joined.date using UTC time?
In my template, I want to show the join date of a user, so I am using {{ user.date_joined }} which shows the date and time (in local time zone - same as what is shown in the admin panel). To just show the date, I use {{ user.date_joined.date }}, but it seems to be converting the date and time to UTC before showing the date (I am in EST/EDT - I never remember which is which). For example: {{ user.date_joined }} ==> Feb. 18, 2021, 7 p.m. {{ user.date_joined.date }} ==> Feb. 19, 2021 Is there a way for me to change this so that it shows the same date as the full date and time? -
How to update a User and its Profile in nested serializer using generic ListCreateAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can update my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) otp = … -
type object 'Post' has no attribute 'published' Django (ERROR)
I am working on the application and I have entered all the code correctly. But when I enter the runserver command, browser gives me such an error My codes are as follows: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. and views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) What changes do I need to make now? -
How to run celery tasks on another Azure VM server?
I am working on a django application that uses Celery to run a video encoding task. But right now, every task is run on the same VM as the main application thereby using that server's memory. I was wondering if there was any way to run these tasks on a separate VM so that the main application is not affected by the encoding tasks memory usage. -
Why do I get typeerror while migrating mysql in django?
python 3.8, django 3.1.6 when i input like this: enter image description here the error is: enter image description here even if I googled, I couldn't find this case and in a library file 'django\db\backends\mysql\base.py' there is a method: enter image description here I think it's an error because cursor.fetchall() returns a byte. Can you figure out a solution to this problem? -
JS function only pick on first element in Django loop
My template code is as follows {% for content in contentlist %} <div class="card card-margin-top"> <div class="card-body"> <div class="card-head"> <p class="card-title">PRICE&nbsp;&#8208;&nbsp; <span id="price">{{content.price}}</span> </p> </div> </div </div> {% endfor %} and I want to convert my price value into a comma-separated value using the js function. JS function is as follows window.onload=function(){ var price = document.getElementById("reservedPrice").innerText x = updateTextInput(price) document.getElementById("reservedPrice").innerText = x } function updateTextInput(val) { x = val.toString(); var lastThree = x.substring(x.length-3); var otherNumbers = x.substring(0,x.length-3); if(otherNumbers != '') lastThree = ',' + lastThree; var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree; return res } but in result looks like this. JS executing only on first entry. I want all prices to be comma-separated. Please provide help ASAP. -
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..