Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AES encryption and decryption of file path with django
I am trying to encrypt the file path when users upload images to the database and decrypt the images when displaying it on the web page. Both encryption/decryption require the usage of AES algorithm. Do I need to install some sort of library to do this in Django and how do I go around doing it in my code? I'm assuming I have to add the encryption parameter in obj = ImagefieldModel.objects.create() and decryption parameter in allimages = ImagefieldModel.objects.all(). models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" views.py def imgupload(request): context = {} if request.method == "POST": form = ImagefieldForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data.get("name") img = form.cleaned_data.get("image_field") obj = ImagefieldModel.objects.create( title = name, img = img ) obj.save() print(obj) messages.info(request, f"image uploaded successfully!") return redirect("main:basehome") else: form = ImagefieldForm() context['form'] = form return render( request, "main/image_upload.html", context) def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/view_and_download.html',{'images': allimages}) image_upload.html {% extends "main/header.html" %} {% block content %} <head> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </body> {% endblock %} view_and_download.html {% extends "main/header.html" %} {% load static %} {% block content %} … -
Comparison of objects in django
Models class Weapon_Class(models.Model): title = models.CharField(max_length = 50) description = models.TextField() def __str__(self): return self.title class Gun(models.Model): weapon_type = models.ForeignKey(Weapon_Class, on_delete = models.CASCADE) name = models.CharField(max_length = 50) magazine_size = models.IntegerField(default = 0) damage = models.IntegerField(default = 0) fire_rate = models.IntegerField(default = 0) description = models.TextField() def __str__(self): return self.name Views class Weapon_class_view(ListView): model = Weapon_Class template_name = 'weapon_class.html' # print(Weapon_Class.objects.all()[1].headline) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['items'] = Weapon_Class.objects.all().count() context['weapons'] = list(Weapon_Class.objects.all()) context['arm'] = (Gun.objects.all()) return context Template {% for weapon in weapons %} <div class = "wepbox" > <a href="#"><div class = "boxy">{{ weapon.title }}</div></a> </div> {% for g in arm %} {% if g.weapon_type == weapon.title %} <h1 style="color: yellowgreen;">{{g.name}}</h1> {% endif %} {% endfor %} {% endfor %} It displays nothing on the browser but it should display the name of different guns like type 25 which is the assault rifle or MW11 which is the pistol -
Populate dropdown in template from model choices using Django Rest Framework
I have the model, serializer, viewset and html as follows: GENDER = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHERS', 'Others'), ) class Client(BaseModel): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256, default="", blank=True, null=True) designation = models.CharField(max_length=256, default="", blank=True, null=True) gender = models.CharField(max_length=20, choices=GENDER, null=True, blank=True) class ClientSerializer(QueryFieldsMixin, DynamicFieldsModelSerializer): name = serializers.SerializerMethodField() def get_name(self, obj): return getattr(obj, "first_name", "") + " " + getattr(obj, "last_name", "") class Meta: model = Client fields = '__all__' @method_decorator(login_required, name='dispatch') class ClientViewSet(viewsets.ModelViewSet): model = Client queryset = model.objects.all() serializer_class = ClientSerializer @action(detail=True, methods=['post','get'], renderer_classes=[renderers.TemplateHTMLRenderer]) def update_client(self, request, *args, **kwargs): object = self.get_object() context = {"operation": "Update", "object_id": object.id, "events": Event.GetEventsForObject(object)} template_name = 'contact-client.html' response = Response(context, template_name=template_name) <div class="row"> <div class="columns medium-5 medium-text-left"> <div class="select2-full select-2-full--sm input-rounded"> <label for = "gender" style="text-align: left;" >Gender</label> <select id="gender" class="js-select2 input-height-sm element-contact" name="gender" validated="false"></select> <option></option> </div> <div id="gender_error" style="display:none"> <p class="help-text"> <span class="form-action-icon error-icon"></span>Please select gender.</p> </div> </div> <div class="columns medium-5 medium-text-left"> </div> </div> When I instantiate the ClientSerializer in shell like this ClientSerializer() then that gender field is shown along with its choices. But I am not able to show it in the template. All the other fields are being passed correctly. How can I populate the dropdown with … -
TypeError when using AWS S3 Bucket with Django
I'm brand new to Django and AWS S3 and seem to have hit a wall. This is all on localhost at the moment. I'm trying to add a new product through my own admin app for a Art Gallery website i'm working on, all worked fine originally when adding a product, but since using AWS S3 i receive the following TypeError: The error states that it's expecting "...a string or bytes-like object." and refers to the following lines of code in both my mixins.py and my staff views.py mixins.py: from django.shortcuts import redirect class StaffUserMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: return redirect("home") return super(StaffUserMixin, self).dispatch(request, *args, **kwargs) views.py: class ProductCreateView(LoginRequiredMixin, StaffUserMixin, generic.CreateView): template_name = 'staff/product_create.html' form_class = ProductForm def get_success_url(self): return reverse("staff:product-list") def form_valid(self, form): form.save() return super(ProductCreateView, self).form_valid(form) As I stated at the start i'm very new to both Django and AWS S3, so if this is just a schoolboy error, please forgive me but any help would be fantastic. And if any additional info is needed i'll be happy to provide. Thanks! -
Difference between TruncDay and Cast, extracting date from datetime
What are the differences between these two methods(extracting date from datetime): #1 User.objects.annotate(date=TruncDay('date_joined')).values('username','date') #2 User.objects.annotate(date=Cast('date_joined', output_field=DateField())).values('username','date') Resulted Query: #1 SELECT "users_user"."username", DATE_TRUNC('day', "users_user"."date_joined" AT TIME ZONE 'UTC') AS "date" FROM "users_user" #2 SELECT "users_user"."username", ("users_user"."date_joined")::date AS "date" FROM "users_user" I noticed that TruncDay also takes consider the timezone information while Cast not. Are there any difference between the use of these two methods for extracting date out of datetime both in sql level and django level, which one is prefered usually? -
Connecting Django docker to remote database
I have a Django application running on docker connected to a database in another container on the same host. This seams to work fine, but when I try to change the connection to a database on another server, it fails to connect. Not only that, but when I try to connect to the Django application in the browser(like admin or api) I get no response, and see no activity in the output log. The application runs fine with the remote database if I run it outside the container, and the database is set to accept all IPs for the user I am trying to connect with. Any Ideas as to why I am not getting a connection? Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN apk add mariadb-dev python3-dev postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app_django COPY ./app_django /app_django WORKDIR /app_django COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] docker-compose.yml version: '3.7' services: db: build: mysql/ environment: MYSQL_ROOT_PASSWORD: … -
Django Rest Framework: Unable to set custom header
I have two custom header keys, api-key and api-secret. On passing it still gives me the error for not having required headers. Below is the code: from rest_framework.test import APITestCase from .models import App, Wallet from .stellar import * # Create your tests here. class WalletTestCase(APITestCase): app_id = 0 app = None def test_create_wallet(self): response = self.client.post( '/wallets/', data={'app_id': self.app_id, 'customer_id': 'A-001'}, # headers={'HTTP_API_KEY': 'test-api', 'HTTP_api-secret': 'test-api-password'} ) self.client.credentials(HTTP_X_API_KEY='test-api', HTTP_X_API_SECRET='test-api-password') data = json.loads(response.content) print(data) self.assertEqual(data['status'], 'OK') -
Is it possible that define pdf attach file in django framework?
We use Title = models.CharField(max_length = 60) For char fields. Is it possible simply use PdfField or FileField in model.py for uploading pdf files? For example: Title = models.CharField(max_length = 60) Document = models.FileField(upload_to='documents/') I do not want to use form and... Extra codes -
django OperationalError when trying to migrate with docker
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known That is the error I get when running docker-compose exec web python manage.py migrate my docker-compose.yml contains: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 This Is what I put for DATABASE in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } I have tried running docker-compose up -d --build and then docker-compose exec web python manage.py migrate But that doesn't work. -
Do some task before Django project stops
How can I do some tasks like clear Redis cache objects before my Django project stops? Is there any way to find this moment inside a Django project so that there is no need for extra config and commands in the server such as Nginx server? -
A condition for checking if a field is 'None' is not working as expected
So I'm running a basic loop that's iterating through a list of items containing a dictionary and I'm filtering the list on the basis of if the selected key !=" " or None. However, the !=" " part seems to be working but the None check is not working. Here's what I'm trying to say in code form data = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}, {'Field': 'somevalue', 'Anotherfield': ''}, {'Field': 'somevalue', 'Anotherfield': None}} datanew = [] for items in data: if items['Anotherfield']!= '' or items['Anotherfield'] is None: datanew.append(items) What I should be getting is datanew = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}] vs what I'm getting datanew = [{'Field': 'somevalue', 'Anotherfield': 'somevalue'}, {'Field': 'somevalue', 'Anotherfield': None}] I think it's just a simple mistake in the if condition somehow, but I've gone over it a lot of times now and haven't been able to figure it out yet. What am I doing wrong here? Thank you. -
Why CSS is not working and image is not displaying in my django app
I started with a django app and tried to run index.html. But CSS is not working and also image is not showing. However, If I run index.html besides this app, it is working fine. my settings.py: """ Django settings for mac project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zzam)ocs^4jpa618b+dp^da6!#r9!*ka6$=u+0@0wc=fxo9*_l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'shop', ] 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', ] ROOT_URLCONF = 'mac.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mac.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
How to apply a transformation on a field when serializing?
In Django, how does one apply a custom transformation while serializing a field? For instance, I have a model which has a geometry field, which is stored in a specific coordinate system. Now, for this one serializer, I'd like to perform a conversion that converts the coordinates to another coordinate system. How is that done? The serializer currently looks like this: class LinkWithGeometrySerializer(serializers.ModelSerializer): class Meta: model = Link fields = ['link_type', 'geometry', ] The geometry is the field that should have a transformation applied to it. -
New to Django, Saving ForeignKeys, is this the right way?
So I am confused as to how I should save foreign keys relation in Django so far this is my first attempt and I am doing it like this with save(commit=False) when the form data is sent back to the server from POST request in my views.py as follows: def create_listing(request): if request.method == 'POST': form = get_product_category_fields(category=eval('Broomstick'), data=request.POST) imageform = ImageForm(request.POST, request.FILES) print(form.errors.as_data()) print(imageform.errors.as_data()) if form.is_valid() and imageform.is_valid(): fkey_image_album = imageform.save(commit=False) fkey_product_album = form.save(commit=False) album = ImageAlbum() album.save() fkey_product_album.album = album fkey_image_album.album = album fkey_product_album.save() fkey_image_album.save() return render(request, "auctions/index.html") forms.py from django.forms import ModelForm from .models import * def get_product_category_fields(category, data): class Category_Form(ModelForm): class Meta: model = category exclude = ['date_added', 'user', 'product_comment', 'album'] form = Category_Form(data=data) return form class ImageForm(ModelForm): class Meta: model = Image exclude = ['album'] models.py class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lte=100, length__lte=100) class Image(models.Model): image = models.ImageField(upload_to='uploads/') default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) def __str__(self): return self.image class auction_product(models.Model): product_name = models.CharField(max_length=64) date_added = models.DateField(default=timezone.now) user = models.ManyToManyField(User, through='product_ownership', related_name='product_user') product_bid = models.ManyToManyField(User, through='bid', related_name='product_bid') product_comment = models.ManyToManyField(User, through='comment') album = models.OneToOneField(ImageAlbum, related_name='product_model', on_delete=models.CASCADE) def __str__(self): return self.product_name -
facing problem in cyberpanel with hosting django website
i have tried to site from https://blog.cyberpanel.net/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/ but it is not helping . i think problem is related to openlitespeed. if anyone got idea help me thanks in advance . i was following same procedure as blog and same context context / { type appserver location /home/django.cyberpanel.net/public_html/cyberpanel binPath /usr/local/lsws/fcgi-bin/lswsgi appType wsgi startupFile cyberpanel/wsgi.py envType 1 env LS_PYTHONBIN=/home/django.cyberpanel.net/public_html/bin/pyhton env PYTHONHOME=/home/django.cyberpanel.net/public_html/ } -
I want to get the total of sales for each item
I am working on a small django project. In my models.py I have a Product class like: class Product(models.Model): ... ... ... And I have a Sales class like: class Sales(models.Model): item = models.ForeignKey(Product) quantity = models.IntegerField() I want to display a list of all my products with the total of sales for each product... I hope my question is clear enough. Thanks -
Django returns "CSRF Verification Failed" only when uploading large files [Nginx + Gunicorn]
I'm working on a project which involves uploading large files (a whole folder containing a lot of files actually). All post requests, including uploading small files and folders work well. However, when I try to upload a large folder with POST request, I get 403 "CSRF Verification Failed" error. I did include the csrf token which is why all my post requests work. This only happens with large files/folder. I've included these lines in nginx.conf: client_max_body_size 4G; proxy_send_timeout 7300s; proxy_read_timeout 7300s; I set my client_max_body_size to 4GB but when I upload a folder of 100MB I still get the CSRF failed error. I've tried uploading a folder of about 8MB and it works fine. I'm so confused now. Can someone help me please? Thanks in advance! -
Django redirect, reverse
How can i do it so the user after editing the post doesn't get redirected to homepage but to the detail view of the post they just edited My views.py from . models import Post from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import DeleteView, UpdateView, CreateView from django.urls import reverse_lazy def home(request): posts = Post.objects.all() return render(request, 'pages/index.html', {'posts':posts}) def detail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'pages/detail.html', {'post':post}) class edit(LoginRequiredMixin, UpdateView): model = Post template_name = 'pages/edit.html' fields = ['title','image','body'] success_url = reverse_lazy('pages:homepage') def dispatch(self, request, *args, **kwargs): handler = super().dispatch(request, *args, **kwargs) user = request.user post = self.get_object() if post.author != user: raise PermissionDenied return handler my models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import pre_save from A_Tech_Blog.utils import unique_slug_generator class Post(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(blank=True, null=True, max_length=300) image = models.ImageField(upload_to='post_images', default='default.jpg') time_created = models.DateTimeField(auto_now_add=True) views = models.IntegerField(default=0) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.title} -- Author={str(self.author)}' class Meta: ordering = ['-time_created'] verbose_name_plural = 'Posts' def get_absolute_url(self): return reverse('pages:detail', args=(self.slug)) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Post) I want to be able to edit the … -
Django: Returning data from a linked table
I am doing a project that revolves around storing scores against players. Each player can shoot several rounds, some several times. I am trying to make a page that shows a list of the rounds shot and the number of times that round has been shot. This will ultimately be a link to a table of those rounds. I have been able to bring back the round id but cannot get the round name back from the linked table. This seems such a basic thing but I cannot figure it out. My models are: class Score(models.Model): BOW_TYPE = ( ('R', 'Recurve',), ('C', 'Compound',), ('L', 'Longbow',), ) archer = models.ForeignKey('User', related_name='scores', on_delete=models.CASCADE) rndname = models.ForeignKey('Round', related_name='rounds', verbose_name=("Round Name"), on_delete=models.CASCADE) age = models.ForeignKey('Age', related_name='scores', on_delete=models.CASCADE) bowtype = models.CharField(max_length=1, verbose_name=("Bow Type"), choices=BOW_TYPE) score = models.IntegerField(default=0) dateshot = models.DateField(verbose_name="Date Round Shot", default=timezone.now) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.archer) + ' | ' + str(self.score) + ' | ' + str(self.rndname) + ' | ' + str(self.created_date) class Round(models.Model): roundname = models.CharField(max_length=200) maxscore = models.IntegerField(default=0) def __str__(self): return str(self.roundname) I can return the number id of the distinct rounds using this line in views.py: posts = Score.objects.values('rndname').distinct().order_by('rndname') and this returns the round id as … -
How to paginate 3 different objects in the same page efficiently?
I have 3 different models ModelA,ModelB,ModelC, all related to the user. So, I want to show them in a list ordered by date (infinite scroll down). But it's starting to take too much to load them at once. My ajax view: ... list1 = user.modela_list.all() list2 = user.modelb_list.all() list3 = user.modelc_list.all() result = list1 + list2 + list3 return render(request,'template.html',context={'result':result}) The template (I use the regroup templatetag to group them by the DateTimeField they all have): <div class="tab-pane fade show active" id="tab1" role="tabpanel"> {% regroup result by date.date as result_list %} {% for group_by_date in result_list %} <div class="section-title">{{ group_by_date.grouper }}</div> <div > {% for object in group_by_date.list %} .... {% endfor %} </div> </div> {% endfor %} </div> This creates something like this: So now, instead of just loading all the objects I wan't some kind of pagination but I can't figuire it out. How do I get the correct amount of ModelA, ModelB and ModelC objects by date?: #I can't do just this list1 = user.modela_list.all()[0:5] list2 = user.modelb_list.all()[0:5] list3 = user.modelc_list.all()[0:5] If I want 15 elements per load, how many of modelA, B and C do I have to show. I hope I explained myself. Thanks! -
TemplateDoesNotExist at / index.html Django
I'm learning django when create templates so got an error this is the error i got urls.py urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^first_app/',include('first_app.urls')), url(r'^admin/', admin.site.urls), ] settings.py BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") -
Why doesn't this script add the structure correctly to the Django database?
I encountered a pretty weird problem with a ManyToManyField in Django today. When automatically reading input data from a dict the ManyToMany field gets populated falsely. My model is for this example pretty simple the UnitType has a name and 4 ManyToMany fields, one of them beeing possible_children = models.ManyToManyField('self', related_name='UnitTypeChildren', blank=True). When I run my management command which I set up for this minimal example I run (subtypes is truncutaded because there are a lot of values and everything with this works): building_subtypes = { 'garage/ parking': {'subtypes': [...]}, 'room': {'subtypes': [...], 'child': ['room']}, 'apartment': {'subtypes': [...]}, 'floor': {'subtypes': [...], 'child': ['room', 'apartment', 'garage/ parking']}, 'building': {'subtypes': [...], 'child': ['room', 'floor', 'apartment', 'garage/ parking']}, 'address': {'subtypes': [...], 'child': ['building', 'apartment', 'garage/ parking']}, 'business': {'subtypes': [...]}, 'other': {'subtypes': [...]} } for typ in building_subtypes: ut, new = UnitType.objects.get_or_create(name=typ) for subtype in building_subtypes[typ]['subtypes']: UnitSubType.objects.get_or_create(name=subtype, unit_type=ut) if 'child' in building_subtypes[typ]: for child in building_subtypes[typ]['child']: child_ut, new = UnitType.objects.get_or_create(name=child) print(subtype.name + ' ' + child_ut.name) # Prints correctly ut.possible_children.add(child_ut) # Check if it worked for ut in UnitType.objects.all(): childstring = "" for child in ut.possible_children.all(): childstring += str(child) + ', ' print(ut.name + ': ' + childstring) # Prints alternate structure When accessing … -
How to configure MySQL to automatically decrypt data/images request?
I am building a Django app that allows user to upload images to MySQL and the app also displays the uploaded images to users from MySQL. I plan to encrypt the filepath that stores those images. Is there a way to configure MySQL to automatically decrypt data/images when my Django app queries the database for those encrypted image/file path? -
How do I add 'list' attribute to an input field using jQuery?
I'm struggling to figure out the following; I have a django form field hidden in {{ field.field }}. It renders out as <input type="text" name="field-id" value="100" id="id_set-0-product" class="vForeignKeyRawIdAdminField"> I can tagret it using jQuery by its id but I need to add a list = "choicelist" which corresponds with <datalist id="choicelist" style="text-align: center"> </datalist> which I populate using ajax requests. How do I add the list = "choicelist" to it? Any help would be much appreciated! -
How To Attach One User To Another User For Payment And Upline AutoMatically In Django When New User Register
Am building a django project and i want Newly Auntheticated User to be Attached to Old Authenticated User as Upline for payment purposes(i sure know how to handle the payment case). This Attachment or Assign of this New User to Old User should be based on the Request of the Old User and the willingness of the New Users. There is a payment category for Users of the App in a range of $50, $100, $150, $200. Lets take for example- the old User Request For a payment of $50 and the new user select a category of payment of $50. Then the new user which is assigned to the old user will be automatically Assigned to pay the new User the amount Category Requested by the old User and agreed upon by the New Users. After the Request from the old User and Request from the New User then i will want my app to automatically assign the old user to the new user. Note. I will determine the other conditions that will enable the old user Elligible to make such requests. Lets take a look at my Code. Payment Category Class PayCategory(models.Model): Amount = models.Charfield(max_length=6) My Manager which …