Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django registeration verification of email not working
I followed blog https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef for email verification but it adding a user before verification of link. -
Why doesn't my toggle work correctly when I use staticflies?
I am studying Django and found the following problem when using staticsfiles, the toggler that appears when the screen is reduced does not extend my bootstrap navbar, I did not find the error. NOTE: the rest works, dropdown, navbar (css / js) NOTE1: when I use CDN everything works, including the toggler here are the excerpts that I call staticsfiles and the link to the complete project on github settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) scripts.html {% load static %} <script src="{% static 'jquery/dist/jquery.js' %}"></script> <script src="{% static 'popper.js/dist/umd/popper.js'%}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> Projeto no Github -
Which is better - django login or jQuery AJAX?
Django's indigenous login system is a lot confusing, I really don't know whether its even an AJAX call or simple form registration plus the security concerns with it is not really specified anywhere on the internet. I used jQuery AJAX for all form submissions till yesterday and now that this Django feature of login is an integrated Django feature I'm using it. Is this login methodology better over the AJAX calls? -
Django - How do I had a "points" field to my User model
I'm making an online quizz but when I add a "points" field to my User model, I have an error (I added the app in INSTALLED_APPS). So, I created a UserPoints model in my models.py : from django.db import models from django.contrib.auth.models import User class UserPoints(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) def AddPoints(self, amount): self.amount = amount self.points += amount self.save() Then I resgistered it in admin.py : from django.contrib import admin from .models import UserPoints admin.site.register(UserPoints) But when I type python manage.py makemigrations I have this error : You are trying to add a non-nullable field 'id' to pointsutilisateur without a default; we can't do that (the database needs something to populate existing rows) -
Python multiprocessing fails silently while generate cache with many keys
I want to populate cache (memcached) for a Django apps with Python Multiprocessing. The function create_cache(keys) create cache for memcached. About 5 Millions Keys. Factor from slowest to speadest create cache is about 10. I use BaseCommand of Django to launch following python script : #python imports import multiprocessing as mp # django imports from django.core.management.base import BaseCommand from .../apps import create_cache class Command(BaseCommand): def handle(self, *args, **options): keys =[....] core_number = mp.cpu_count() len_keys = len(keys) chunk_size = int(len_keys / core_number / 10) print ("total len",len_keys, "chunk_size",chunk_size) pool = mp.Pool(core_number) try: pool.imap_unordered(create_cache, keys, chunk_size) except Exception as e: print("a worker failed, aborting...",e) pool.close() pool.terminate() else: print("before close") pool.close() pool.join() print("after join") This code works for some thousands of keys, but after 10 000 keys, It fails after "before close", and process stay iddle, and not all the keys are created (I check with stats in memcached). In addition I can't CTR+C this process, I have to kill it in a terminal. I fix this issue with adding a sleep(0.0001) in create_cache before cache.set(key,result), but it slow down the script. I'am woundering why Multiprocessing lost memcached when too many keys ? Ubuntu 16.04, Python 2.7, Django 1.4 -
I cant able to add the product images , it is showing the attribute error,
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Product(models.Model): CONDITION_TYPE = ( ("New", "New"), ("Used", "Used"), ) name = models.CharField(max_length=50) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, null=True) brand = models.ForeignKey( 'Brand', on_delete=models.SET_NULL, blank=True, null=True) description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) condition = models.CharField(max_length=50, choices=CONDITION_TYPE) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Category(models.Model): category_name = models.CharField(max_length=50) image = models.ImageField(upload_to='product/', blank=True, null=True) def __str__(self): return self.category_name class Meta: verbose_name = 'category' verbose_name_plural = 'categories' class Brand(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Meta: verbose_name = 'brand' verbose_name_plural = 'brands' class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_image = models.ImageField( upload_to='categories/', null=True, blank=True) def __str__(self): return self.Product class Meta: verbose_name = 'product images' verbose_name_plural = 'product images' When I am adding the product images in the admin panel section, It is showing the attribute error.. AttributeError at /admin/product/productimages/add/ 'ProductImages' object has no attribute 'Product' Request Method: POST Request URL: http://127.0.0.1:8000/admin/product/productimages/add/ Django Version: 3.0.5 Exception Type: AttributeError Exception Value: 'ProductImages' object has no attribute 'Product' Exception Location: /home/durga/Desktop/django_projects/olx_clone/src/product/models.py in str, line 59 Python Executable: /home/durga/Desktop/django_projects/olx_clone/bin/python Python Version: 3.7.5 Python Path: ['/home/durga/Desktop/django_projects/olx_clone/src', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/durga/Desktop/django_projects/olx_clone/lib/python3.7/site-packages'] Server time: Wed, … -
Configurate MSSQL Server with Django
I have installed **appdirs==1.4.3 asgiref==3.2.7 distlib==0.3.0 Django==2.1.15 django-mssql==1.8 django-mssql-backend==2.8.1 django-pyodbc-azure==2.1.0.0 filelock==3.0.12 pyodbc==4.0.30 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 virtualenv==20.0.18 virtualenvwrapper-win==1.2.6** My settings.py file in the database section looks like this DATABASES = { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'localhost', 'HOST': 'localhost', 'USER': 'dbo', 'PASSWORD': '', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } I got the following error after run py manage.py migrate File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 167, in ensure_defaults conn = self.databases[alias] File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 37, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 154, in databases if self._databases[DEFAULT_DB_ALIAS] == {}: KeyError: 'default' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\z003vuxz\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen … -
Django reverse , reverse lazy and resolve
Hello i am new in django and the words resolve, reverse and reverse lazy are too much confusing i didn't get all these words in django please help me to understand these words Answer will be appreciated -
How do I get a files absolute path after being uploaded pdf files and converted it into csv in Django?
What I have done: 1.User uploads a pdf file 2.coverted into text and extract values and store in DB 3.pdf table extracted by Camelot and then convert it into CSV and store it in a different folder 4.return the path to a function so as to iterate the CSV file and store it into DB. But the problem I faced: the table data convert into CSV and store it into its folder but I cannot return the path with the file(.csv) extension. ''' def upload(request): if request.method == 'POST': pos = Model.objects.all() form = ModelForm(request.POST, request.FILES) if form.is_valid(): form.save() file_name = form.cleaned_data['pdf'].name file_name1 = form.cleaned_data['choose'] get_file = Model.objects.last() print(file_name1) print(form.cleaned_data['pdf'].name) text=convert_pdf_to_txt(file_name) #In there converts the pdf file and returns text file in #this finction. print(text) path = '/pos/pdfs/{}'.format(file_name) if file_name1 == "x": #here check for which pdf text and its own regex. #different pdf different regex. regex_Q ='len:\s?([0-9]+)' regex_no ='patch\s\s\s\s?([0-9]+)' Q_No=get_info_from_text(text,regex_Q ) s_No=get_info_from_text(text,regex_no ) elif file_name1 == "y": regex_Q = 'Un\s?([0-9\,]+)' regex_no = 'Nu\s?([0-9]+)' Q_No = get_info_from_text(text, regex_Q ) s_No = get_info_from_text(text, regex_no) data = tables_extract(path) #in here csv directory path will return and i want to iterate it #with csv reader #and put it into my Model or ORM … -
Django Url in JQuery
I am using jquery's autocomplete with ajax and django. The search feature exists on the navigation bar so it can be used from any url within the site. The issue I am running into is the link to be selected from the autocomplete dropdown. I have attempted passing in a django url like shown below in main.js but this leads to the url containing the characters '{% show_person %}' appended onto the end of the current url which obviously isn't the desire. main.js: the success parameter within the ajax call. ... success: function(a) { //console.log(a) $("#autocomplete").autocomplete({ source: a, select: function(event, ui) { event.preventDefault(); window.location.href = '{% url show_person %}'; }, minLength: 1, }) } Additionally, instead of the django url used above I have also tried window.location.href = "person/"+ui.item.value;. This ends up just appending person/<personid> onto whatever the current url is. What I would like to happen is for the url to be mapped directly to the corresponding person's page, but this only works now if I am on the index page because there the url is empty and the appendage works. -
How to get the server name in Python Django?
How to get the server name in Python Django? we hosted Django application in AWS - Apache machine which have more than 1 server and increased based on load. Now i need to find from which server the particular request is made and from which server we got the response. I am using Python 3.6, Django,Django restframework, Apache server on AWS machine. -
Authenticating using mysql in django
I am new to Django and noob in that concepts. According to my knowledge i am trying to connect the django page to the mysql database. The insertion to the database using form is done correctly, but when i am trying to login with credentials it throws an error. This was very important for my college graduation. It shows an error called 'NoneType' object is not subscriptable'. Tq for ur suggestions def login(request): email= request.POST['email'] password=request.POST['password'] con = mysql.connector.connect(user='root', password='', host='localhost', database='company') cur = con.cursor() cur.execute("SELECT email,password from buyerregister where 'email' = '"+email+"' and 'password' = '"+password+"' ") data=cur.fetchone() con.commit() cur.close() con.close() if data[2] == email and data[3] == password: return render(request, "purchase.html") else: return render(request, "order.html") -
Static File Issue with DJango and Heroku
This is a well-known issue and I have gone through a lot of such posts and applied different possibilities. But neither the problem is clear to me nor any solution worked. Let me give you the best possible problem description. I have a Django application. The folder structure is as follows, C:. ├───myproject │ └───__pycache__ └───main ├───migrations │ └───__pycache__ ├───static │ ├───css │ └───js ├───templates │ ├───main │ └───registration └───__pycache As you can see, the css and jss files are inside a folder named static In the HTMLs I access the static files as follows, {% load static %} <link href="{% static "/css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "/css/mystyle.css" %}" rel="stylesheet"> When I run the Django's built in server locally the files are accessed like, http://127.0.0.1:8000/static/css/mystyle.css in the browser and it works flawlessly. Now, comes to the Heroku deployment part. I have gone through the official page, https://devcenter.heroku.com/articles/django-assets I modified my settings.py file as, BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' MIDDLEWARE_CLASSES = ( 'whitenoise.middleware.WhiteNoiseMiddleware', ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) Now, after performing the builds I saw in the build log (Heroku cloud) the following line, python manage.py collectstatic --noinput So, it collects all the static files … -
Django import-export - Problem with ForeignKeyWidget
i am trying to insert bulk data into database i am using Django import_export option for importing data i need only import button. i added a foreign key widget for getting the corresponding data. but i got an issue please check the details model.py class Clip(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) dialogflow_intent_name = models.CharField(max_length=128) start_timestamp = models.CharField(max_length=32) end_timestamp = models.CharField(max_length=32) forms.py from django import forms from import_export.forms import ImportForm, ConfirmImportForm from .models import Subject class CustomImportForm(ImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) class CustomConfirmImportForm(ConfirmImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) resource.py from import_export import resources,fields from .models import Clip,Subject from import_export.widgets import ForeignKeyWidget class ClipResource(resources.ModelResource): subject = fields.Field( column_name='subject', attribute='subject', widget=ForeignKeyWidget(Subject)) class Meta: model = Clip fields = ('dialogflow_intent_name','start_timestamp','end_timestamp','subject') export_order = ('dialogflow_intent_name','start_timestamp','end_timestamp','subject') skip_unchanged = True report_skipped = True use_transactions = True admin.py class CustomClipAdmin(ImportMixin, ClipAdmin): resource_class = ClipResource formats = (base_formats.XLS, base_formats.CSV) def get_import_form(self): return CustomImportForm def get_confirm_import_form(self): return CustomConfirmImportForm def get_form_kwargs(self, form, *args, **kwargs): if isinstance(form, CustomImportForm): if form.is_valid(): subject = form.cleaned_data['subject'] kwargs.update({'subject': subject.id}) return kwargs Corresponing table contain 5 files - id(primary key),dialogflow_intent_name,start_timestamp,end_timestamp,subject_id(ForeignKey) Bt i found an error and i cant import the data : issue is attached, here id is my primary key and xls file contain 3 field dialogflow_intent_name,start_timestamp,end_timestamp,and … -
m learning..how to check in html file with jinja format ? it gives me error Could not parse the remainder: '>4000' from 'x.price>4000'
{%for x in dest%} <div class="destination item"> <div class="destination_image"> <img src="{{baseurl}}/{{x.image}}" alt=""> {% if x.price > 4000%} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {%endif%} </div> <div class="destination_content"> <div class="destination_title"><a href="{% static 'destinations.html'%}">{{x.name}}</a></div> <div class="destination_subtitle"><p>{{x.desc}}</p></div> <div class="destination_price">{{x.price}}</div> </div> </div> {% endfor %} What is the problem at if statement above?? i tried to access the line special offer but error says couldnot parse the remainder. -
access attribute via serializer django
I got following models: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) class Order(models.Model): reference = models.CharField(max_length=50) purchase_order = models.CharField(max_length=15, blank=True, null=True) I'm now writing a serializer for listing orders. In this OrderSerializer I need to access amount and ordered_amount in the OrderItem class. How do I do this? This is What I have now: class AdminOrderListSerializer(serializers.ModelSerializer): amount = serializers.IntegerField() ordered_amount = serializers.IntegerField() class Meta: model = Order fields = [ "purchase_order", "reference", "amount", "ordered_amount", ] # noinspection PyMethodMayBeStatic def validate_amount(self, order): if order.order_items.amount: return order.order_items.amount return # noinspection PyMethodMayBeStatic def validate_ordered_amount(self, order): if order.order_items.ordered_amount: return order.order_items.ordered_amount return This gives me following error: AttributeError: Got AttributeError when attempting to get a value for field amount on serializer AdminOrderItemListSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'amount'. -
Using DjangoCMS Wizards Without Temp Files Directory
I have tried creating a custom Wizard for the first time recently. It works well; however, there is a questions. Is there a way to prevent the Wizard from needing "wizard_tmp_files" directory and uploading files there? In our setup we use AWS S3. The files get uploaded there, but their copies also linger in "wizard_tmp_files", which is annoying, especially if the files are large. I wonder if there is a way to avoid using "wizard_tmp_files" altogether. Any help or advice is appreciated. Model: class Video(models.Model): title=models.CharField(max_length=500) description=models.TextField(default="") hash=models.CharField(max_length=10, default=_createHash, unique=True) creation_date=models.DateTimeField(default=timezone.now) videofile=models.FileField(upload_to='videos/', null=True, verbose_name="Video") poster=models.ImageField(upload_to='videos/thumbnails ', null=True, verbose_name="Poster") tags = TaggableManager() CMS Wizard: from django.utils.translation import override as force_language from .forms import VideoForm class VideoWizard(Wizard): def get_success_url(self, obj, **kwargs): """ This should return the URL of the created object, «obj». """ if 'language' in kwargs: with force_language(kwargs['language']): url = obj.get_absolute_url() else: url = obj.get_absolute_url() return url video_wizard = VideoWizard( title="New Video", weight=200, form=VideoForm, description="Create a new video", ) wizard_pool.register(video_wizard) -
I am using codepen animation with django templates but nothing happen
I used codepen loader, before loading the main page this effect must take place I think I get confused in extends tag. all files are connected to each other. The below code doesn't give me an error just a white blank page. Here is my base.html {% block content %} <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'css/my-loader'%}"> </head> <body> h1.intro cat loader .box .cat .cat__body .cat__body .cat__tail .cat__head </body> </html> {% endblock %} This is my-loader.css position: $type; @if $dir != 'bottom' {top: 0; } @if $dir != 'right' {left: 0; } @if $dir != 'left' {right: 0; } @if $dir != 'top' {bottom: 0; } } .cat { position: relative; width: 100%; max-width: 20em; overflow: hidden; background-color: #e6dcdc; &::before { content: ''; display: block; padding-bottom: 100%; } &:hover > * { animation-play-state: paused; } &:active > * { animation-play-state: running; } } %cat-img { @include fill-full; animation: rotating 2.79s cubic-bezier(.65, .54, .12, .93) infinite; &::before { content: ''; position: absolute; width: 50%; height: 50%; background-size: 200%; background-repeat: no-repeat; background-image: url('https://images.weserv.nl/?url=i.imgur.com/M1raXX3.png&il'); } } .cat__head { @extend %cat-img; &::before { top: 0; right: 0; background-position: 100% 0%; transform-origin: 0% 100%; transform: rotate(90deg); } … -
DRF SerializerMethodField how to pass parameters
Is there a way to pass paremeters to a Django Rest Framework's SerializerMethodField? Assume I have the models: class Owner(models.Model): name = models.CharField(max_length=10) class Item(models.Model): name = models.CharField(max_length=10) owner = models.ForeignKey('Owner', related_name='items') itemType = models.CharField(max_length=5) # either "type1" or "type2" What I need is to return an Owner JSON object with the fields: name, type1items, type2items. My current solution is this: class ItemSerializer(serializers.ModelSerializer): class Meta: model = models.Item fields = ('name', 'itemType') class OwnerSerializer(serializers.ModelSerializer): type1items = serializers.SerializerMethodField(method_name='getType1Items') type2items = serializers.SerializerMethodField(method_name='getType2Items') class Meta: model = models.Owner fields = ('name', 'type1items', 'type2items') def getType1Items(self, ownerObj): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type1") return ItemSerializer(queryset, many=True).data def getType2Items(self, ownerObj): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type2") return ItemSerializer(queryset, many=True).data This works. But it would be much cleaner if I could pass a parameter to the method instead of using two methods with almost the exact code. Ideally it would look like this: ... class OwnerSerializer(serializers.ModelSerializer): type1items = serializers.SerializerMethodField(method_name='getItems', "type1") type2items = serializers.SerializerMethodField(method_name='getItems', "type2") class Meta: model = models.Owner fields = ('name', 'type1items', 'type2items') def getItems(self, ownerObj, itemType): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType=itemType) return ItemSerializer(queryset, many=True).data In the docs SerializerMethodField accepts only one parameter which is method_name. Is there any way to achieve this behaviour using SerializerMethodField? (The example code here is overly simplified … -
Getting an additional HTML data using xhttp in Django
I'm working now with Django form based on ModelForm class which uses some JavaScript on my page to receive form data using POST. class MyForm(ModelForm): data_url = '/form-data/' dep_fields = '__all__' class Meta: model = Sign fields = '__all__' exclude = ['name', ] class Media: js = ('js/form.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) attrs_dict = {'onchange': 'addForm(this)', 'style': 'display:', 'data-url': f'{self.data_url}'} if self.data: '''form fields logic''' My Javascript does the following. It stores my form data like this: var data = new FormData(obj.form); and then sends in to my server every time I change any form field: xhttp.send(data); And form data looks like this: data1 = {'csrfmiddlewaretoken': ['cpWuNU1JfK'], 'country': ['2'], 'region': [''], 'area': [''], 'quality_mark': [''], 'sign': ['']} (I reduced the token for convenience) So all I need is to get ID of chosen field from my HTML page (country ID in this case). I added the following code to my JS: var field_id = parseInt(obj.id ); xhttp.send(field_id); And it seems to be working but I can’t understand where or how I can get this data (field_id) on my Django server. -
Django updateView always updating the first element in database
I have a simple model.py which has a ForeignKey relation. class Release(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) class Feature(models.Model): release = models.ForeignKey(Release, on_delete=models.SET_NULL, null=True, related_name='features') name = models.CharField(max_length=200, db_index=True, unique=True) In url.py path('release/<int:pk>/feature/<int:pk1>/update/', views.FeatureUpdate.as_view(), name='feature-update'), In views.py: class FeatureUpdate(UpdateView): model = Feature fields = ['name'] In feature_form.html {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input type="button" value="Cancel" onclick="history.back()"> </form> {% endblock %} Lets say I have 1 release(release-A) and 2 features(feature-A and feature-B) in database. When i try to edit feature-A it works. However when i try to edit feature-B: the form shows feature-A data and also edits feature-A. I am new to django and not able to go further. Please help.. -
Django REST Framework's IsAdminUser doesn't prevent non-admin users
I want to make one view admin-only. I'm using a simple function-based view with the @permission_classes decorator. I want this to be available only to admin users. from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser from django.http import JsonResponse @permission_classes([IsAdminUser]) def testing(request): return JsonResponse({"status": "ok", "user": request.user.username, "is_staff": request.user.is_staff}) However when I curl as an anonymous user the check clearly isn't applied: curl http://localhost:8000/testing/ {"status": "ok", "user": "", "is_staff": false} I would expect to be rejected if I wasn't logged in, or wasn't an admin user. It looks like I'm using them correctly according to the permissions and decorators docs. -
How to fix the error when configuring saml on Django?
Here are the items I use: python 3.6.8 django 2.1.5 django_saml2_auth all is installed correctly without an issue When I run the server, I get the error message as follows: saml2.sigver.SigverError: Cannot find ['xmlsec.exe', 'xmlsec1.exe'] How to fix this error? -
many to many array field in djano model
I'm building a work orders model in django. I'd like to have an array field for parts required with quantities and another array field of parts produced with quantities. The parts would be foreign keys from a model in an inventory app I have already created. From what I've read PostgreSQL won't allow for foreign keys in an array field. so I would need to have a many to many field in a new model. But I'm not sure how to construct that. what would be the best way to go about this? models.py from django.db import models from django.contrib.postgres.fields import ArrayField from inventory.parts.models import partslist # Create your models here. class jobs(models.Model): jobid = models.CharField(max_length=100) partsrequired = ArrayField( ArrayField( models.ForeignKey(partslist, on_delete=models.CASCADE) ) ) partsproduced = ArrayField( ArrayField( models.ForeignKey(partslist, on_delete=models.CASCADE) ) class instruction(models.Model): job = models.ForeignKey(jobs) pdf = models.FileField(upload_to='pdf') -
Celery worker best practices
I am using Celery to run background jobs for my Django app, hosted on Heroku, with Redis as broker. and I want to set up task prioritization. I am currently using the Celery default queue and all the workers feed from. I was thinking about implementing prioritization within the only queue but it is described everywhere as a bad practice. The consensus on the best approach to deal with the priority problem is to set different Celery queues for each level of priority. Let's say: Queue1 for highest priority tasks, assigned to x workers Queue2 the default queue, assigned to all the other workers The first problem I see with this method is that if there is no high priority task at some time, I loose the productivity of x workers. Also, let's say my infrastructure scales up and I have more workers available. Only the number of "default" workers will be expanded dynamically. Besides, this method prevents me from keeping identical dynos (containers on Heroku) which doesn't look optimized for scalability. Is there an efficient way to deal with task prioritization and keep replicable workers at the same time?