Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to limit CheckboxSelectMultiple choices for paid membership in Django
I'm struggling with my code in Django. My app is Garden, when you create a new garden and you are a member of 'plus' membership, you can select unlimited plants. But if you are a member of free membership you can select only 3 plants. How can I do that? models.py class Garden(models.Model): name = models.CharField(max_length=256) description = models.TextField(blank=True, default='') address = models.CharField(max_length=512) plant = models.ManyToManyField(Plant, related_name="gardens", through="GardenPlant") user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) class Membership(models.Model): PLUS = 'PL' FREE = 'FR' MEMBERSHIP_CHOICES = ( (PLUS, 'plus'), (FREE, 'free') ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default=FREE, max_length=30) price = models.DecimalField(default=0, max_digits=999, decimal_places=2) class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) class Subscription(models.Model): user_membership = models.ForeignKey(UserMembership, related_name='subscription', on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.user_membership.user.username forms.py class GardenForm(forms.ModelForm): class Meta: model = Garden fields = ['name', 'description', 'address', 'plant'] def clean_plant(self): value = self.cleaned_data['plant'] if len(value) > 3: raise forms.ValidationError("You can't select more than 3 items.") return value plant = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Plant.objects.all()) def save(self, user): garden = super().save(commit=False) garden.user = user garden.save() garden.plant.add(*self.cleaned_data.get('plant')) views.py def create_garden(request): form = GardenForm(request.POST or None) if form.is_valid(): form.save(request.user) return redirect('/garden') context = {"form": form, "has_subscription": subscription_check(request.user)} return render(request, "create_garden.html", … -
Heroku push is failing with error: node:internal/modules/cjs/loader:936 throw err;
I'm trying to build a small web application with django and react. I already added the buildpacks for both. Now I wanted to run git push heroku master, but I keep getting this output: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: remote: -----> Installing binaries remote: engines.node (package.json): 16.13.0 remote: engines.npm (package.json): 8.1.0 remote: remote: Resolving node version 16.13.0... remote: Downloading and installing node 16.13.0... remote: npm 8.1.0 already installed with node remote: remote: -----> Installing dependencies remote: Prebuild detected (node_modules already exists) remote: Rebuilding any native modules remote: rebuilt dependencies successfully remote: Installing any new modules (package.json) remote: remote: changed 3 packages, and audited 567 packages in 1s remote: remote: 55 packages are looking for funding remote: run `npm fund` for details remote: remote: found 0 vulnerabilities remote: remote: -----> Build remote: Running build remote: remote: > frontend@1.0.0 build remote: > webpack --mode production remote: remote: node:internal/modules/cjs/loader:936 remote: throw err; remote: ^ remote: remote: Error: Cannot find module '../lib/bootstrap' … -
django extra select to qs
How can i add addition select in queryset? queryset = ActivityCollection.objects.filter(date_at__gte=from_date, date_at__lte=to_date).order_by('date_at') it looks { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00" }, i need to get: { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00", "cpc": "25" } cpc = cost / clicks -
Django static css is not loading on page
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html. I have the following structure djangoAjax settings.py ... djangoAjaxApp static ok.css templates css_practice.html My settings.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '############################################' # 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', "crispy_forms", 'djangoAjaxApp', ] 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 = 'djangoAjax.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 = 'djangoAjax.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL … -
how to save two dynamic relates forms together - django
I'm trying to save three forms together : this the scenario ; form 1 Invoice number, form 2 item names can have several items in one invoice , form 3 Serial number, serial number if in the form2 item one quantity = 10 then we have 10 unique serial numbers , and second item quantity = 4 we have to add 4 unique serial number , in one submit button . i've used maodelformset_factory to make the forms dynamic here is the models class ItemName(models.Model): item_name = models.CharField(max_length=60,unique=True) class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) company = models.ForeignKey(ClientCompany,on_delete=models.PROTECT) invoice_no = models.IntegerField(blank=True,null=True) items = models.ManyToManyField(ItemName,through='Item') class Item(models.Model): invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT,related_name='invoice') item = models.ForeignKey(ItemName,on_delete=models.PROTECT,related_name='item_name') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Serial(models.Model): item = models.ForeignKey(Item,on_delete=models.PROTECT) serial_no = models.CharField(max_length=15,unique=True) status = models.BooleanField(default=True) and i've used modelform i think it doesnt require to post the forms , the Serial and Item are modelformset_factory , and here is the view @login_required def create_invoice_view(request): form = InvoiceForm() item_formset = itemformset(queryset=Item.objects.none()) serial_formset = serialformset(queryset=Serial.objects.none()) if request.POST: form = InvoiceForm(request.POST) item_formset = itemformset(request.POST) serial_formset = serialformset(request.POST) if form.is_valid() and item_formset.is_valid() and request.user.is_superuser: invoice_obj = form.save(commit=False) invoice_obj.admin = request.user invoice_obj.save() data = { 'id':invoice_obj.id } for item in item_formset: item_obj = … -
infinite loop while overriding save method in Django
I want to override the save method in order to update quantity if the cart_item already exists insert new entry if the cart_item does not already exists but every time after the save method it gets stuck in infinite loop class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self) -> str: return self.product.name def save(self, *args, **kwargs): try: cart_item = CartItem.objects.get(cart_id=self.cart.id, product_id=self.product.id) cart_item.quantity += self.quantity pprint(cart_item) cart_item.save() #after this line goes into infinite loop except CartItem.DoesNotExist: super().save(*args, **kwargs) #after this line goes into infinite loop pprint("-------------------------here") `` -
Django Celery with Redis Issues on Digital Ocean App Platform
After quite a bit of trial and error and a step by step attempt to find solutions I thought I share the problems here and answer them myself according to what I've found. There is not too much documentation on this anywhere except small bits and pieces and this will hopefully help others in the future. Please not that this is specific to Django, Celery, Redis and the Digital Ocean App Platform. This is mostly about the below errors and further resulting implications: OSError: [Errno 38] Function not implemented and Cannot connect to redis://...... The first error happens when you try run the celery command celery -A your_app worker --beat -l info or similar on the App Platform. It appears that this is currently not supported on digital ocean. The second error occurs when you make a number of potential mistakes. -
How to calculate sums and multiplications in a django formset without using javascript?
I am a newbie in django and more in javasript, the question is that I am trying to do calculations in my formset with javascript but it does not come out, is there any way to do addition and multiplication in django formsets in an easier way? -
local variable 'verify_payment' referenced before assignment
i;m having the local variable renfrenced before assign and i have tried a lot of ways that i can use to fix this. any help would be greatly appreciated let me show some code views.py (the error after the top of the second if statement) def call_back_url(request): reference = request.GET.get('reference') # We need to fetch the reference from PAYMENT check_pay = PayHistory.objects.filter(paystack_charge_id=reference).exists() if check_pay == False: # This means payment was not made error should be thrown here... print("Error") else: payment = PayHistory.objects.get(paystack_charge_id=reference) # We need to fetch this to verify if the payment was successful. def verify_payment(request): url = 'https://api.paystack.co/transaction/verify/'+reference headers = { 'Authorization': 'Bearer '+settings.PAYSTACK_SECRET_KEY, 'Content-Type' : 'application/json', 'Accept': 'application/json', } datum = { "reference": payment.paystack_charge_id } x = requests.get(url, data=json.dumps(datum), headers=headers) if x.status_code != 200: return str(x.status_code) results = x.json() return results initialized = verify_payment(request) if initialized['data']['status'] == 'success': PayHistory.objects.filter(paystack_charge_id=initialized['data']['reference']).update(paid=True) new_payment = PayHistory.objects.get(paystack_charge_id=initialized['data']['reference']) instance = Membership.objects.get(id=new_payment.payment_for.id) sub = UserMembership.objects.filter(reference_code=initialized['data']['reference']).update(membership=instance) user_membership = UserMembership.objects.get(reference_code=initialized['data']['reference']) Subscription.objects.create(user_membership=user_membership, expires_in=dt.now().date() + timedelta(days=user_membership.membership.duration)) return redirect('subscribed') return render(request, 'payment.html') def subscribed(request): return render(request, 'subscribed.html') traceback System check identified 1 issue (0 silenced). November 26, 2021 - 18:50:42 Django version 3.2.9, using settings 'dexxapikprj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Error Internal … -
Google App Engine Django Project Infinite Loading and error 500 does not raise any error in logs
Im am trying to deploy a Django project on Google Cloud App Engine. I deployed my app using the command gcloud app deploy. As I try to load the page in my browser, there is an infinite loading until the page finally returns a "Server 500 Error". I decited then to see if there is something weird in the logs by executing gcloud app logs tail but it does not raise any type of error, this is what i get. 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Starting gunicorn 20.1.0 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Listening at: http://0.0.0.0:5432 (11) 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [11] [INFO] Using worker: sync 2021-11-26 17:38:31 default[version_code] [2021-11-26 17:38:31 +0000] [16] [INFO] Booting worker with pid: 16 This is my Python Django settings.py: if os.getenv('GAE_APPLICATION', None): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'cloudsql/<my-google-cloudsql-connection-string>', 'NAME': 'database_name', 'USER': 'username', 'PASSWORD': 'password', 'PORT': '5432', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } This is my app.yaml file: runtime: python39 env: standard app_engine_apis: true handlers: - url: /static static_dir: static/ - url: /.* script: auto entrypoint: gunicorn -b :5432 NG.wsgi I also get this … -
Django MANAGERS and ADMINS settings, do we need it configured?
I know ADMINS can be used to receive error notifications on email Something that can be better handled by datadog or sentry For manager seems to be something even more specific, since you need t use BrokenLinkEmailsMiddleware as well # MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = [ ("Admin", "admin@mail.com"), ] # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS Does it have any other purpose? Any reason to keep it on the Django settings? -
insert data through django automatically
I have made crawler and I want to link it with my django app so i can see this data in admin panel , but my problem is I do not know how do I insert crawled data automatically to django database. -
python Django middleware to check license. How to avoid code cracking
I wanted to have a license key to use the django application I am creating a signed file using pub and private keys This singed file will contain the details of the license, like username, date of expiry, version number etc. One after purchasing the software they will download the signed file. They have to place the file at a location mentioned Basically i will have a middleware in the Django which will read the signed file and it also has the pubkey. Using that it will verify the signed document, and if it passes, then checked the expiry date and allow to continue class CheckDate: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. current_date = datetime.datetime.now() pub_key = "key is passed here" allowed_date = get from signed document the expiry date if current_date < allowed_date: return response else: #return render(request, 'licence_expired.html') return HttpResponse(json.dumps({"message":f"License Expired on {allowed_date}"}),content_type='application/json',status="401") return response Now using nuitka i am trying to obfuscate the code of … -
Django: how store multiple data types to the same model field
I want to create a database model somewhat similar to the example below: The idea is that User (or any model) can have multiple different features (or whatever) with different values. Feature can be anything, for example integer (salary), date (birthdate), or multiple selection (competences like C, Python, etc.). To keep the database design simple, I've tried an approach where I have only one Feature table which has optional choices via Choice table, instead of having separate database table for each feature type. User selection for feature value is stored to a User_has_Feature table "value" field, which is a CharField which can store multiple different data types, like integer, date, choice, multiple choice etc. My question is, how can I validate all data so that it validates against the field data type, and also shows everything correctly in admin or UI (having different UI widgets for different types)? I've tried an approach where I store the field type for each feature to Field table, which can be CharField, IntegerField, DateField, etc. Then in User_has_Feature model clean() I can dynamically validate against the field type, for example: FIELDS = { 'DateField': DateField, 'IntegerField': IntegerField, etc. } def clean(self): class_ = FIELDS.get(self.feature.field) … -
Django: Group and then Calculate the Sum of the column values through query
I have a model: bill_status_choice = ( ('Paid','Paid'), ('Pending','Pending'), ('Partially Paid','Partially Paid'), ) class Bill(models.Model): company_name = models.ForeignKey(Contact, on_delete=models.CASCADE) grand_tot = models.DecimalField(max_digits=9, decimal_places=2) status = models.CharField(max_length=100, choices=bill_status_choice) ... which has a fk to: class Contact(models.Model): associated_company = models.CharField(max_length=100) ... In my Views.py ... from bills.models import Bill from django.db.models import Sum def home(request): total = Bill.objects.filter(status='Paid').aggregate(Sum('grand_tot'))['grand_tot__sum'] context = { 'total':total, } return render(request, 'home.html',context) The problem: I am using charts.js in my front end template and I am trying to display a chart in which as a user creates new company names the chart should display the total amount grouped by company names how would I achieve that? eg: I create two invoices for "xyz" company with amounts: $100 & $200 || & create one invoice for "abc" company with amount $100 I want the chart to group the "xyz" invoice amounts and display $300 (ie:100+200) || & "abc" = $100 FYI I'm aware I'm using something completely wrong in the view function but its just something that I tried. Thanks -
How do I implement a login system in Django with GRPC?
I read GRPC documentations but it was not clear for me: How do I implement a registration form and then login with username and password? In JWT requests (REST) we always send the token with each request, but what is authentication in GRPC? -
Any way to figure out the reverse chain of Django relationship string?
Imagine you have a valid model relation string b__c__d__e for some model modelA, so that,say, the expression ModelA.objects.filter(b__c__d__e__in=[...]) is valid. My goal is to come up with a sort of "reverse" string which defines the "path" of relation from ModelE to ModelA. Is there any built-in way to do that? I am going to write such a function myself. But before dwelving into that, I wonder if there's any built-in way to do that. -
TypeError: Cannot read properties of undefined (reading 'params') when using match.params.id to fetch json data React Django rest API
I am trying to access specific data from my django backend based on using the unique id in the url for my react app on the frontend. I expect to see the body of the journal Instead i get this error: TypeError: Cannot read properties of undefined (reading 'params') I tried to use, 'useParams' instead but it lead to more errors. I also found similar questions on SO but they mentioned using 'props', is this the method i should be attempting instead? my App.js import { BrowserRouter, Routes, Route, Router, } from "react-router-dom"; import './App.css'; import Header from './components/Header' import JournalDashboard from './pages/JournalDashboard' import JournalPage from './pages/JournalPage' function App() { return ( <div className="App"> <BrowserRouter> <Header /> <Routes> <Route path="/" exact element={<JournalDashboard/>}></Route> <Route path="/journals/:id" element={<JournalPage/>} ></Route> </Routes> </BrowserRouter> </div> ); } export default App; my JournalPage.js import React, { useState, useEffect } from 'react' const JournalPage = ({ match }) => { let journalId = match.params.id let [journal, setJournal] = useState(null) useEffect(() => { getJournal() }, [journalId]) let getJournal = async () => { let response = await fetch(`/api/journals/${journalId}/`) let data = await response.json() setJournal(data) } return ( <div> <p>{journal?.body}</p> </div> ) } export default JournalPage Thanks in advance -
Django - show and verify email domains in registration form
I am using crispy forms to display the registration form and I have an issue with label_suffix in my form because it is not showing in the register.html file. When I change {{form|crispy}} to {{form}} then I can see it. Could you please tell me what am I doing wrong? Moreover, I'd like to limit the email domains that my registration system will accept and I want to check if the email is @companyname.com, @companyname2.com, @companyname3.com and it will accept only these emails in the registration process. Could you please tell me how can I do it? register.html <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-secondary">Register</button> </form> views.py class SignUpView(View): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('user/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': form}) forms.py TRUSTED_EMAILS = ['@companyname.com','@companyname2.com', … -
Django - TypeError: object of type 'method' has no len()
I was trying add paginator to my website using some online code but I'm getting this error return len(self.object_list) TypeError: object of type 'method' has no len() Views.py def sample(request): WAllPAPER_PER_PAGE = 2 wallpapers = Wallpaper.objects.all page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {"wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator} return render(request, "Wallpaper/sample.html", context ) Models.py class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name -
How to reuse a serializer in Django (Python)
I have a service in a Django app I am building where I want to hanlde get and post requests. I though I should reuse a serializer I ve build but in the examples I find whenever someone want to use a serializer they create a new object. This is an implementation where the serializer class is called multiple tiems to create multiple instanses one each time a request arrives: from django.http.response import JsonResponse from django.http.request import RAISE_ERROR, HttpRequest from rest_framework.parsers import JSONParser from rest_framework import status from models import Instrument from serializers import InstrumentsSerializer class InstrumentsService(): def __init__(self): self.serializer: InstrumentsSerializer = None def get_instruments_by_type(self, instrument_type: str): if instrument_type is not None: instruments = Instrument.objects.all() instruments.filter(instrument_type__icontains=instrument_type) instruments_serializer = InstrumentsSerializer(instruments, many=True) else: raise ValueError("Value type None is not acceptable for 'instrument_type'") return instruments_serializer.data def add_instrument(self, instrument_data: Instrument): instrument_serializer = InstrumentsSerializer(data=instrument_data) if instrument_serializer.is_valid(): instrument_serializer.save() How can I use the same serializer and pass different data to it each time? Because in the example I presented the data are being passed in during initialization. -
How to dump and restore correctly a postgresql db from docker
I stuck with this error when trying to backup and restory my database from a docker django app environnement : [error :(][1] [1]: https://i.stack.imgur.com/G8P4V.jpg I first did this command to backup my whole DB docker exec -t project_final-db-1 pg_dumpall -c -U fred2020 > ./db/dump.sql And then trying to restory with this command cat dump.sql | docker exec -i --user fred2020 catsitting-db-1 psql -U fred2020 -d postgres I have two containers, one for my django app named catsitting-web-1 and one for my postgresql named catsitting-db-1 I don't understand why it gaves me that error, my db user is the same that I specified on the dockerfile... Any clue ? -
Django: NoneType' object has no attribute 'user' error
I've this two models: MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) name_user_B = models.CharField(max_length=250) code_user_B = models.PositiveIntegerField(null=True) total_user_B = models.PositiveIntegerField(null=True) sd_user_B = models.PositiveIntegerField(null=True) With File model it should be uploaded a csv file and then the information in the file should be saved in the Dataset model. After that I'd like to show some chart to my user so I need my File and Dataset models linked. This is my view: VIEWS def file_upload(request): data = None if request.method == 'POST': form = FileForm(request.POST, request.FILES) raw_file= request.FILES if form.is_valid(): form.instance.user = request.user.profile form.instance.filename = raw_file['file_upload'].name form.save() data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': data, 'form': form, } return render(request, 'upload_file.html', context) When I try to access the Dataset database in the admin area I get this error: 'NoneType' object has no attribute 'user'. I cannot also access … -
Update an item using a django model instance
Is it a good idea to update an item by saving a model instance with the same id? Lets say there is an Person item in the database: id: 4 name: Foo surename: Bar tel: 0000000000 Is it a good idea to update that item like: p = Person( name='Foo' surename='Bar' tel='0000000111' ) old_p = Person.objects.get(name='Foo', surname='Bar') p.id = old_p.id p.save() -
Which setup is the best for remote authentication using Django REST Framework?
I currently have two different Django projects. One that handles the API; one that handles the front-end. Which way is best for authenticating users using the API from my front-end? For example, the users will log in on my front-end app and all the subsequent requests, that are made to the API from the front-end, should be done using the authenticated user. None of the authentication methods provided by DRF seems to suit my use case. Is there a way to do this or is my entire setup wrong?