Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Permissions in file upload
I'm trying to build a file sharing application using Django REST Framework in the backend. In order to upload files, I have the following field in my models: user_file = models.FileField() However, when a user uploads a file, that file is stored in the directory of the DRF project, and if I put the path of that file in a browser, every user can then access it as well. How can I prevent this? I've thought of having an Apache HHTPd server where there would be a folder for each user and when a user tries to access a file that was not uploaded my them, the backend would do that verification and would not allow it, but I don't know if that would solves the problem? How can I do this? Thanks -
Django - Show all ForeignKeys belonging to the given ID as a select multiple field
I have this model: class OrderProduct(models.Model): order = models.ForeignKey(to=Order, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) price_paid = models.DecimalField(max_digits=5, decimal_places=2) @property def total_value(self): return self.price_paid * self.quantity def __str__(self): return f"{self.order.id} / {self.order.user} // {self.product.name} / {self.quantity} ks" def save(self, *args, **kwargs): self.price_paid = self.product.price super(OrderProduct, self).save(*args, **kwargs) This is my form: class ChangeOrderProductForm(ModelForm): class Meta: model = OrderProduct fields = ('product',) This is my view: def change_orderproduct(request, order_id: int): set_session_cookie_restraunt_status(request) if not check_if_user_has_permission(request, 'kitchen.change_orderproduct'): messages.warning(request, 'Unauthorized to perform this action.') return redirect("index") ordered_products = OrderProduct.objects.filter(order__pk=order_id).first() order = Order.objects.filter(pk=order_id).first() if not order: messages.info(request, "Given order does not exist.") return redirect(request.META.get('HTTP_REFERER', index)) if request.method == "GET": form = ChangeOrderProductForm() context = { "form": form, "order": order } return render(request, "kitchen/change_orderproduct.html", context=context) if request.method == "POST": form = ChangeOrderProductForm(data=request.POST, instance=ordered_products) if form.is_valid(): form.save() messages.success(request, f"Products in order {order.pk} were successfully changed.") return redirect(request.META.get('HTTP_REFERER', all_orders_view)) The code above works, but it only allows you to choose 1 Product in the ChangeOrderProductForm view: However, there are multiple products for almost all Order instances. How do I make it to: Show all the possible Product instances to choose from in the form? Make the already existing ForeignKeys assigned to OrderProduct as the pre-selected ones? … -
find top performing list of category which have highest number of orders in django
models.py class Line_items(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey('Products' , on_delete=models.DO_NOTHING ) class Products(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=400 , blank=True) category = models.ManyToManyField('Categories', through='Product_Categories', related_name='products') class Categories(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100 , blank=True) slug = models.CharField(max_length=200 , blank=True) class Product_Categories(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(Products, on_delete=models.DO_NOTHING) category_id = models.ForeignKey(Categories, on_delete=models.DO_NOTHING) here are my models. where line_items contains number of orders done till now. in line_items we have connect product id with product table. but we don't have any connetion from product table to category table. ( category table contains every category and their id ). to connect product table with category table we have created new table 'product_categories' which connects each category with their respective product. here what we want is top performing category. category which have highest number of orders. thanks -
TypeError: hasattr(): attribute name must be string (Django)
Hi how to solve this issue, when i am excluding this code i am getting this type error. my admin.py is this, list_display = [ "id", exclude==("mode_of_action",)] -
AWS Lambda, An error occurred (InvalidToken) when calling the PutObject operation: The provided token is malformed or otherwise invalid
I made a Django application and tried to deploy it using Zappa and AWS Lambda. My deployment was successfully deployed but, the image was not uploaded to AWS S3 to invoke the API. This is my cloudwatch error log [ERROR] 2022-04-22T08:35:19.84Z cbf18c70-f478-4363-8f5a-0777c76564e9 Internal Server Error: /production/v1/ReviewCamping/ Traceback (most recent call last): File "/var/task/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/task/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/task/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/task/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/var/task/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/var/task/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/var/task/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/var/task/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/task/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/var/task/service/views/v1/camping.py", line 80, in perform_create serializer.save(owner=self.request.user) File "/var/task/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/var/task/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/var/task/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/task/django/db/models/query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "/var/task/django/db/models/base.py", line 806, in save self.save_base( File "/var/task/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/var/task/django/db/models/base.py", line 1000, in _save_table results = self._do_insert( … -
Is it possible to link multiple models to one fiel in django?
Let's say I have these models: class Material(models.Model): name = models.CharField([...]) class Consumable(models.Model): name = models.CharField([...]) restores = models.IntegerField([...]) class Weapon(models.Model): name = models.CharField([...]) damage = models.IntegerField([...]) # And then I have an 'inventory', like this one: class Inventory(models.Model): user = models.ForeignKey([...]) # to which user you want to link the item item = models.ForeignKey([...]]) # which item quantity = models.IntegerField([...]) # how many of it I want to be able to have all Material, Consumable, and Weapon models listed in the 'item' field, so when you want to add an item as an inline, you would see all 3 models' objects. Something like # instead of this item = models.ForeignKey(Consumable) # which item # want something like this item = models.ForeignKey(Consumable and Material and Weapon) # which item # this wouldn't work ofc... Is there a way to collect all 3 of them and pass them to the 'item' field, without the need of restarting the server? (when making a "choices" list that queries from a model you must restart the server to see the newly added objects, I don't want that.) I also want to stick to the built-in admin of Django since it provided everything I need … -
How to add similar key value in python?
Sorry if you find the question misleading This is the array of data: [{'user': 1, 'coins': 2}, {'user': 18, 'coins': 8}, {'user': 1, 'coins': 1}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}, {'user': 18, 'coins': 0}] Expected Outcome: [{'user': 1, 'coins': 3}, {'user': 18, 'coins': 8}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}] So, there will be an array of those data, and we have to add the coins to similar user which can be identified by user key value. If user key have similar value that is 1 (in above case) then coins of both or multiple user must be added making it a total sum of that user coins. -
Password validation with CustomUser Django
I am trying to validate a password against CustomUser fields: email and full_name. All test validations are working except for UserAttributeSimilarityValidator, which is the only test that I have included with the code below. forms.py class RegistrationForm(forms.ModelForm): email = forms.EmailField(label=_('Email address'), widget=forms.EmailInput(attrs={'class': 'form-control mb-4', 'class': 'form-control mb-4', })) full_name = forms.CharField(label=_('Full name'), widget=forms.TextInput(attrs={'class': 'form-control mb-4', })) password = forms.CharField(label=_('Password'), widget=forms.PasswordInput(attrs={'class': 'form-control mb-4', 'autocomplete': 'new-password', 'id': 'psw', })) class Meta: model = get_user_model() fields = ('full_name', 'email', 'password') def clean_password(self): password = self.cleaned_data.get("password") if password: try: password_validation.validate_password(password, self.instance) except ValidationError as error: self.add_error("password", error) return password def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError( mark_safe(_(f'A user with that email already exists, click this <br><a href="{reverse("account:pwdreset")}">Password Reset</a> link' ' to recover your account.')) ) return email tests.py @override_settings( AUTH_PASSWORD_VALIDATORS=[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS': { 'user_attributes': ( 'email', 'full_name', )}, }, ] ) def test_validates_password(self): data = { "email": "jsmith@example.com", "full_name": "John Smith", "password": "jsmith", } form = RegistrationForm(data) self.assertFalse(form.is_valid() self.assertEqual(len(form["password"].errors), 1) self.assertIn( "The password is too similar to the email.", form["password"].errors, ) Which results in this test result: FAIL: test_validates_password (account.tests.test_forms.RegistrationFormTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/tester/Documents/dev/test/venv/lib/python3.8/site-packages/django/test/utils.py", line 437, in inner return func(*args, **kwargs) File "/Users/tester/Documents/dev/test/account/tests/test_forms.py", line 112, in … -
How to make files available not in "/static/", but in "/app/static/"?
I have Django 1.11 project structure like this: project static img1.png app static img2.png File "settings.py" contains: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Images are available at: my-site.com/static/img1.png my-site.com/static/img2.png But I want the images to be available in a different way: my-site.com/app/static/img1.png my-site.com/app/static/img2.png I can write to a file "project/app/urls.py": urlpatterns += static('static/', document_root=os.path.join(BASE_DIR, 'app' + STATIC_URL)) And then "img2.png" will be available, but not "img1.png". How can I make "img1.png" available? -
how to create row in model based on data fetched from JSON request from third-party crawling with "best practice"
describe the problem: I want to crawl data from dataforseo , and save them directly in model database through model.create() method with having multi model with multi relation with models so for instance in model A have ManyToMany relation with model B ManyToMany relation with model C ManyToMany relation with model D and model B have relation with model C so my question is how to save JSON response to all model mentioned above smoothly through model A create Method Code: view.py file @api_view(['POST']) @parser_classes((JSONParser,)) def crawl_data(request): """ A view that can accept POST requests with JSON content. """ Product.create( title=request.data[title] url=request.data[url] describtion=request.data[describtion] ... ) return Response({'received data': request.data}) models.py class Highlighted(models.Model): name_highlighted = models.CharField(max_length=100) def __str__(self): return str(self.name_highlighted) class Rating(models.Model): rating_type = models.CharField(max_length=500, null=True, blank=True) # make unique value = models.CharField(max_length=500, null=True, blank=True) votes_count = models.CharField(max_length=500, null=True, blank=True) rating_max = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.value) class Price(models.Model): current = models.CharField(max_length=500, null=True, blank=True, default="none") regular = models.CharField(max_length=500, null=True, blank=True) max_value = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.current) class Product(models.Model): title = models.CharField(max_length=500, null=True, blank=True) url = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) pre_snippet = models.CharField(max_length=500, null=True, blank=True) extended_snippet = models.CharField(max_length=500, null=True, blank=True) images = models.CharField(max_length=500, … -
Django Admin dependent DropDown HTML field
I have a Region and SubRegion ForeignKey in the Country Model. My SubRegion model also has a Region ForeignKey for the Region Model. I am having a hard time displaying the SubRegion dropdown in the Country Model on the basis of the Region selected. What would be the best way to achieve it? It would be great if dropdowns were based on the value of their parent. models.py class Region(models.Model): name = models.CharField(max_length=20) is_active = models.BooleanField(verbose_name='is active?', default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class SubRegion(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(max_length=50) is_active = models.BooleanField(verbose_name='is active?', default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Sub Regions' class Country(models.Model): name = models.CharField(max_length=100) region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Region') subregion = models.ForeignKey(SubRegion, on_delete=models.CASCADE, verbose_name='Sub Region') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) admin.py class CountryAdmin(admin.ModelAdmin): list_display = ('name', 'is_active', 'is_default', 'created_at', 'updated_at', ) list_filter = ('region', 'subregion', 'is_active', 'is_default', 'created_at', 'updated_at', ) search_fields = ('name', 'official_name', ) fieldsets = ( ('Region Information', {'fields': ('region', 'subregion', )}), ('Basic Information', {'fields': ('name', 'official_name', )}), ('Codes Information', {'fields': ('cca2', 'ccn3', 'cca3', 'cioc','idd', 'status', )}), ('Coordinates', {'fields': ('latitude', 'longitude', )}), ('Membership & Statuses', {'fields': (('is_independent', 'is_un_member', … -
Django - if i add multiple row in views, its not showing up before i refresh PostgreSQL services
for E in PositionList.objects.all(): # It fetching above 100 records AE = Attendance() AE.EmployeeName = Candidates.objects.get(pk=E.EmployeeName_id) AE.Company = Preclient.objects.get(pk=E.Company_id) AE.AttendanceDate = date.today() AE.Attendance = True AE.Remarks = "Initial Entry" AE.save() It actually created above 100 records, but it wont showing up. if refresh or restart all services like PostgreSQL, it will showing up sudo systemctl restart gunicorn sudo systemctl daemon-reload sudo systemctl restart gunicorn.socket gunicorn.service sudo nginx -t && sudo systemctl restart nginx **if i do following commands in my console, it will be showing up What is the solution for it??? i am using gunicorn django nginx ubuntu** -
Django complex multiform views
I am not that good in coding, so take me easy. I would like to create/update view with multiple models in a single form , but need to dynamically add second and third model (need formsets) form into the view. That could be achieved by javascript , by copy empty forms. here is model structure, need it to be scalable, but lets stack with 3 models. What I need 1)present parent and second 2)hit resolve button , which will send ajax and all form data then I proces validate and get additional data and that generate third forms 3)save everything back to database , with appropriate ForeigKeys between models models.py from django.db import models class Parrent(models.Model): data = models.CharField(max_length=30) class Second(models.Model): parent = models.ForeignKey(Parrent, on_delete=models.CASCADE) data = models.CharField(max_length=30) class Third(models.Model): second = models.ForeignKey(Second, on_delete=models.CASCADE) data = models.CharField(max_length=30) forms.py from django.forms import ModelForm from myapp.models import Parrent, Second, Third class ParrentForm(ModelForm): class Meta: model = Parrent fields = ['data'] class SecondForm(ModelForm): class Meta: model = Second fields = ['data'] class ThirdForm(ModelForm): class Meta: model = Third fields = ['data'] SecondFormSet = formset_factory(SecondForm, extra=1) ThirdFormSet = formset_factory(ThirdForm, extra=1) template.html <!-- [ Template form second] start --> <div id='template-second-form' class="card-body table-border-style hidden"> {{ … -
Filter queryset by checking two columns if they are equal
models.py class Entry(models.Model): paid = models.FloatField(blank=True, null=True) price = models.FloatField(blank=True, null=True) I want to get all entries that have paid and price columns the same value. How can I achieve this? -
INSERT failed: NOT NULL constraint failed: error in django and sqlite3
when i run this command in sqlite3: sqlite> .import af.csv tmpr_product it gives me this error: af.csv:1: expected 2 columns but found 1 - filling the rest with NULL af.csv:1: INSERT failed: datatype mismatch af.csv:2: expected 2 columns but found 1 - filling the rest with NULL af.csv:2: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:3: expected 2 columns but found 1 - filling the rest with NULL af.csv:3: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:4: expected 2 columns but found 1 - filling the rest with NULL af.csv:4: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:5: expected 2 columns but found 1 - filling the rest with NULL af.csv:5: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:6: expected 2 columns but found 1 - filling the rest with NULL af.csv:6: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:7: expected 2 columns but found 1 - filling the rest with NULL af.csv:7: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:8: expected 2 columns but found 1 - filling the rest with NULL af.csv:8: INSERT failed: NOT NULL constraint failed: tmpr_product.number af.csv:9: expected 2 columns but found 1 - filling the rest with NULL af.csv:9: INSERT failed: NOT NULL constraint … -
Run django management command for admin file
I want to run this management command but its not working for me , from django.core.management.base import BaseCommand from product.admin import ProductinfoAdmin class Command(BaseCommand): def handle(self, *args, **options): moa = ProductinfoAdmin.admin_site.filter(list_display("info")).update(list_display=False) print(f"The total number of activated Products {moa}") -
Django-Deploy AWS ElasticBeanstalk - Health Red
Hello trying to deploy my django app in EB Note: my app has literally nothing, i just created a new one to check my eb status keeps helth = red Note: in my local env when i type python --version it shows 3.9.12 but when i created the eb init i did eb init -p python-3.8 store-django i don't know if there's much problem Full log of eb create store-django: eb create store-django Creating application version archive "app-220422_041439243455". Uploading: [-------------------------------------Uploading: [#######------------------------------Uploading: [##############-----------------------Uploading: [#####################----------------Uploading: [#############################--------Uploading: [####################################-Uploading: [#####################################Uploading: [##################################################] 100% Done... Environment details for: store-django Application name: store-django Region: us-west-2 Deployed Version: app-220422_041439243455 Environment ID: e-kpknmry6cd Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.12 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2022-04-22 07:16:53.279000+00:00 Printing Status: 2022-04-22 07:16:52 INFO createEnvironment is starting. 2022-04-22 07:16:53 INFO Using elasticbeanstalk-us-west-2-106867183434 as Amazon S3 storage bucket for environment data. 2022-04-22 07:17:14 INFO Created security group named: sg-01633b0706407c8aa 2022-04-22 07:17:29 INFO Created load balancer named: awseb-e-k-AWSEBLoa-1CUR121EIGENQ 2022-04-22 07:17:29 INFO Created security group named: awseb-e-kpknmry6cd-stack-AWSEBSecurityGroup-15U6VRTD05NMK 2022-04-22 07:17:29 INFO Created Auto Scaling launch configuration named: awseb-e-kpknmry6cd-stack-AWSEBAutoScalingLaunchConfiguration-G27zecBdyLEc 2022-04-22 07:18:33 INFO Created Auto Scaling group named: awseb-e-kpknmry6cd-stack-AWSEBAutoScalingGroup-L2RKI6CKUCOF 2022-04-22 07:18:33 INFO Waiting for EC2 instances to launch. This may take a few minutes. 2022-04-22 … -
Django CreateView object.id in get_succes_url pk(id) is NONE and then after redirecting to another URL it prints out created entry ID
I have a problem that I just can't figure out. After creating a work order I want to redirect to the detail page of that work order. Here is my models.py class Radni_nalozi(models.Model): Klijent = models.ForeignKey(Klijenti, on_delete=models.CASCADE) Pacijent = models.CharField(max_length=100) Rok_isporuke = models.DateField() Cijena = models.FloatField(default=0) Napomene = models.CharField(max_length=400,blank=True) Zaduzenja = models.CharField(max_length=400,blank=True) Status = models.CharField(max_length=50, choices=STATUS_CHOICES, default = "OTVOREN") Aktivan = models.BooleanField(default=True) def __str__(self): return f"{self.id} - {self.Klijent}, {self.Pacijent}" And here is my model form: class RadniModelForm(BSModalModelForm): class Meta: model = Radni_nalozi fields = ["Klijent","Pacijent","Rok_isporuke","Napomene","Zaduzenja"] labels = {"Klijent":"Klijent: ", "Pacijent":"Pacijent: ", "Rok_isporuke":"Rok isporuke: ", "Napomene":"Napomene: ","Zaduzenja":"Zaduženja: "} widgets = {'Rok_isporuke': DatePickerInput(options={ "locale":"en-gb", })} I want to create a new work order and I'm using django BSModalCreateView. Here is my views.py: class RadniCreateView(LoginRequiredMixin,BSModalCreateView): template_name = 'app/radni_nalozi/dodaj_rn.html' form_class = RadniModelForm def get_form(self): form = super(RadniCreateView,self).get_form() #instantiate using parent form.fields['Klijent'].queryset = Klijenti.objects.filter(Aktivan=1) return form def get_context_data(self, **kwargs): context = super(BSModalCreateView, self).get_context_data(**kwargs) context['title'] = 'NOVI RADNI NALOG' context['gumb'] = 'KREIRAJ' return context def get_success_url(self): print(self.object.pk) return reverse_lazy('detalji_rn', kwargs={'pk': self.object.pk}) The command print(self.object.pk) returns NONE although the object is created. If I put some other hardcoded value in reverse_lazy function (for example number 13) then my view executes, it redirects to the hardcoded value and … -
Django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0001_initial
I was trying to build logins with Google. I added django.contrib.sites in INSTALLED_APPS image. When I run python manage.py migrate on my Django project, I get the following error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0001_initial is applied before its dependency sites.0001_initial on database 'default'. How can I solve this problem? -
Django error - ModuleNotFoundError: No module named 'polls.ulrs'
I just write the code the create app in django , its named "polls", configure like below: my project\urls.py from django.contrib import admin from django.urls import include, re_path urlpatterns = [ re_path('admin/', admin.site.urls), re_path(r'^$', include("polls.ulrs")), # path("", include("polls.ulrs")), ] my project\settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls' ] polls\ulrs.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^$', views.index, name='index'), ] polls\views from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): response = render() response.write("<h1>Welcome</h1>") response.write("This is the polls app") return response The issue i got as below, could you please help look this? File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.ulrs' -
Why isn't django recognizing my token after i'm redirecting from browser?
In my frontend i'm logging into an app's api from the browser, I'm then redirected back to a View in my backend which gets a code from the app's api, sends it back in a post request then receives an access token and stores it in a model associated with the current user. I'm using token auth. View: class APICallback(APIView): authentication_class = [authentication.TokenAuthentication] permission_class = [permissions.IsAuthenticated] def api_callback(request, format=None): code = request.GET.get('code') if not code: return Response({'Error': 'Code not found in request'}, status=status.HTTP_400_BAD_REQUEST) response = post('https://accounts.api.com/api/token', data={ 'code': code, }).json() print(response) user = request.user access_token = response.get('access_token') token = APIToken(user=user, access_token=access_token) token.save() return redirect('frontend') I have other Views that make requests and it has been able to get the token to know who the user is, but when this View is called I get a 401 Unauthorized error. How do I let Django know the token I'm receiving from the other app's api belongs to the current user? also... when I take off permissions and authentication class from the View it returns the user as Anonymous User -
ModuleNotFoundError: No module named 'model' in Torch.load in Django project
I have trained my model and working well with just script. It load my model with torch as expected. However, when i connect it to the request, i got following error: File "/Users/feqanrasulov/Desktop/sdp/ner/testing/test.py", line 23, in main model = torch.load("/Users/feqanrasulov/Desktop/sdp/ner/testing/model.pth", map_location=lambda storage, loc: storage) File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 712, in load return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args) File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 1046, in _load result = unpickler.load() File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 1039, in find_class return super().find_class(mod_name, name) ModuleNotFoundError: No module named 'model' [22/Apr/2022 07:08:20] "POST /ner HTTP/1.1" 500 123282 -
How to use custom authentication class inside ListAPIView
I am using react components and to test my code I wrote a quick custom authentication class and defined in the settings for the rest_framework as follow: DEFAULT_AUTHENTICATION_CLASSES += ['restaurant.rest_api.dev.DevAuthentication'] This works great and uses the user I tell it to class DevAuthentication(authentication.BaseAuthentication): def authenticate(self, request): user = User.objects.get(id=6) return (user,None) However, I am now trying to use ListAPIView from generics and the user that prints out is an anonymous user which means that it is not using my authentication class. I found that classes can be explicitly defined inside the function and so I did class SearchUsersAPIView(generics.ListAPIView): search_fields = ['email', 'first_name', 'last_name', 'phone_number'] filter_backends = (filters.SearchFilter,) queryset = CustomUser.objects.all() authentication_classes = [restaurant.rest_api.dev.DevAuthentication] serializer_class = userSerializer @permission_classes([IsAuthenticated]) def dispatch(self,request, *args, **kwargs): self.request = request print(self.request.user) if request.user.is_anonymous or request.user.is_user_superuser()==False: response = Response({"message":"Action Denied"}, status = status.HTTP_400_BAD_REQUEST) response.accepted_renderer = JSONRenderer() response.accepted_media_type = "application/json" response.renderer_context = {} return response return super().dispatch(request,*args, **kwargs) I must add that if I write a simple function view with the api_view decorator the user authenticated is the one that I have specified. I wonder why this is not working only for this class and uses its defaults which are basic and session authentication. Is there a way … -
Vercel error deploying Django project, python version error
1 When running the vercel command in Ubuntu terminal: Error! Command failed: python3.6 /tmp/2de7da56/get-pip.py --user ERROR: This script does not work on Python 3.6 The minimum supported Python version is 3.7. Please > use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead. python --version returns 3.8.10. pip --version returns 22.0.4. vercel --version returns 24.0.1 requirements.txt just has Django == 4.0.3 What I tried: Ran the script linked in the error message and added its installation directory to PATH. Updated pip in default directory to 22.0.4. Even aliased python3.6 to python at one point. Tried on both Windows and Ubuntu. -
Failed to get value from html page in Django
I have a problem with trying to get a response from my HTML page using Django (admin). I have a pretty simple div = contenteditable and need to pass data from this div back after the submit button was clicked. Everything, including choosing selection and opening the intermediate page works fine. But when I tapped submit button, the condition if "apply" in request.POST failed to work. Please, tell me, what I'm doing wrong? This is my Django admin: class QuestionAdmin(AnnotatesDisplayAdminMixin, admin.ModelAdmin): def matched_skills(self, question): return ', '.join(s.name for s in question.skills.all()) def update_skills(self, request, queryset): if 'apply' in request.POST: print("something") skills = [] for question in queryset: skills.append(self.matched_skills(question)) return render(request, 'admin/order_intermediate.html', context={'skills': skills}) update_skills.short_description = "Update skills" This is my order_intermediate.html page: {% extends "admin/base_site.html" %} {% block content %} <form method="post"> {% csrf_token %} <h1>Adjust skills. </h1> {% for skill in skills %} <div> <div id="title" style="margin-left: 5px" contenteditable="true" > {{ skill }} </div> </div> {% endfor %} <input type="hidden" name="action" value="update_status" /> <input type="submit" name="apply" value="Update skills"/> </form> {% endblock %}