Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : changes on views.py not applying on templates
i've working on a django project and i needed to pass two objects ex: post and images to template but after long struggling i found that changes that i made on views.py not applying on templates (which really pissed me off) here is an example : views.py def listings(self, request): listings = Listing.objects.all() context = { 'listingd': listings } return render(request, 'listings/listings.html', context) index.html {%if listings %} {%for listing in listings %} //some code here {%endfor%} {%endif%} what i did by purpose is changing the name of the variable in the views.py to listingd so the listings in the index.html should become empty when i reload but guess what nothing has changed listings is still happily keeping it's value of two days ago !! -
How to Give Permission in Django?
I am working on Django and I create my Custom Admin Panel, But I want the same functionality of permission like as Django Default admin Panel. I create functionality for the Blog model in my Dashboard, if I log in as a super-admin and I give Normal User to blog view only permission then Normal user should not access add and edit access on my dashboard, Currently normal user also can access add and edit access on the admin panel which I developed. I added the functionality for Admin and Normal User, if a user is admin then he can access my dashboard otherwise he/she will re redirect on the homepage. But my problem is, how I can create permission-based functionality on my dashboard, I will give permission from Django default admin panel. Please let me guide, Does I need to create the same URL's like Django default admin panel or there is another way to solve this issue. it's a very big problem for me please give me the correct solution. please send if you have any documentation or solution for this. -
how to set default image in views.py django
I have this login inside my views.py, my question is How do i set a default value of an image if the system detect that the picture is None? image = request.FILES['image1'] or None fs = FileSystemStorage() filename = fs.save(image.name, image) uploaded_file_url = fs.url(filename) image2 = request.FILES['image2'] or None fs = FileSystemStorage() filename = fs.save(image2.name, image2) uploaded_file_url = fs.url(filename) image3 = request.FILES['image3'] or None fs = FileSystemStorage() filename = fs.save(image3.name, image3) uploaded_file_url = fs.url(filename) insert_data = Product( image = image, image2 = image2, image3=image3, .... ) insert_data.save() in models.py class Product(models.Model): image = models.ImageField(upload_to='images', null=True, blank=True, default='default1.jpg') image2 = models.ImageField(upload_to='images', null=True, blank=True, default='default1.jpg') image3 = models.ImageField(upload_to='images', null=True, blank=True, default='default1.jpg') ..... this is my traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in InsertProduct 133. image2 = request.FILES['image2'] or None File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py" in __getitem__ 80. raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /InsertProduct/ Exception Value: 'image2' -
Guys help me: Iam have to use Django APS through i want insert data daybases with Consumer_order from to Daily_Cart
*Guy i have check day and publish newspaper if equal then we have to insert data Daily_Cart datatable. so guy any django expert help me * from.models import Consumer_order,Daily_Cart,Newspaper from datetime import date, datetime def transfer_daily_data(): if date.today().weekday() == 4: set = Consumer_order.objects.all() for e in set: self.create(ac_no=e.Consumer_order, newspaper=e.newspaper) print(e) ------- Traceback (most recent call last): ------- System check identified no issues (0 silenced). September 11, 2020 - 08:22:17 Django version 3.0.8, using settings 'Newspaper_tracing.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Job "transfer_daily_data (trigger: interval[0:01:00], next run at: 2020-09-11 08:24:12 IST)" raised an exception Traceback (most recent call last): File "C:\Users\user\Documents\Django\Project--Django\Pro_Venv\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\Users\user\Documents\Django\Project--Django\Pro_Venv\NewspaperAPI\insert_data_script.py", line 10, in transfer_daily_data self.create(ac_no=e.Consumer_order, newspaper=e.newspaper) NameError: name 'self' is not defined Job "transfer_daily_data (trigger: interval[0:01:00], next run at: 2020-09-11 08:24:15 IST)" raised an exception -
How to show articles from a user (django)?
I have an 'Article' model is inside an app, 'Article' have User as a Foreign Key: (/dashboard/models.py) class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Here is how I call create detailview for each user: (/blog/views.py) def auth(request): def get_user(): if hasattr(request, 'user'): return request.user else: from django.contrib.auth.models import AnonymousUser return AnonymousUser() return { 'user': SimpleLazyObject(get_user), 'messages': messages.get_messages(request), 'perms': lazy(lambda: PermWrapper(get_user()), PermWrapper)(), } (/blog/urls.py): urlpatterns = [ path(r'^<pk>/?$', DetailView.as_view( model=User, template_name='blog_detail.html', context_object_name='user_object' ), name='blog_detail'),] In template 'blog_detail.HTML', I call name, profile of each User just fine, but I cannot call articles written by that User. (/blog/templates/blog_detail.html) {% if article_list in user_object.Article.set_all %} {% for article in article_list %} Where did I go wrong, pls help me:( -
Cannot add data into django ManyToManyfield
I have this two models: class Posts(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts") creation_date = models.DateTimeField(auto_now_add=True, blank=True) content = models.TextField(null=True) class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') likes = models.ManyToManyField(Posts, related_name='liked_by') pass And I want to add a post to someone`s likes field, so i do: def change_like(request, post_id): post = Posts.objects.get(id=post_id) current_user = User.objects.filter(username=request.user.username).first() current_user.likes.add(post) print(post.liked_by) print(current_user.likes) But it prints this: network.User.None network.Posts.None Why is this happening? Am I adding the data correctly? -
how to implement attribute base access control in python based web application?
i have a web application written in python(django REST framework) , now i want to implement attribute based access control(ABAC) on my web application for authorization , how can i implement ABAC policies on this application (can i use XACML policies(how to implement xacml on python web app ) or is there any other way to write ABAC policies on python and how to implement on my web application ) can i use py-ABAC and how to use it ? import vakt from vakt.rules import Eq, Any, StartsWith, And, Greater, Less policy = vakt.Policy( 123456, actions=[Eq('fork'), Eq('clone')], resources=[StartsWith('repos/Google', ci=True)], subjects=[{'name': Any(), 'stars': And(Greater(50), Less(999))}], effect=vakt.ALLOW_ACCESS, context={'referer': Eq('https://github.com')}, description=""" Allow to fork or clone any Google repository for users that have > 50 and < 999 stars and came from Github """ ) storage = vakt.MemoryStorage() storage.add(policy) guard = vakt.Guard(storage, vakt.RulesChecker()) inq = vakt.Inquiry(action='fork', resource='repos/google/tensorflow', subject={'name': 'larry', 'stars': 80}, context={'referer': 'https://github.com'}) assert guard.is_allowed(inq) Or if you prefer Amazon IAM Policies style: import vakt from vakt.rules import CIDR policy = vakt.Policy( 123457, effect=vakt.ALLOW_ACCESS, subjects=[r'<[a-zA-Z]+ M[a-z]+>'], resources=['library:books:<.+>', 'office:magazines:<.+>'], actions=['<read|get>'], context={ 'ip': CIDR('192.168.0.0/24'), }, description=""" Allow all readers of the book library whose surnames start with M get and read any book or magazine, … -
django-filters returns two the same models when an instance of a model has the same value
Here is my code; models.py class Home(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.user) class GeneralHomeFeatures(models.Model): home = models.ForeignKey( Home, on_delete=models.CASCADE, related_name="general_home_features" ) home_feature = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return str(self.home) serializer.py class GeneralHomeFeaturesSerializer(serializers.ModelSerializer): class Meta: model = GeneralHomeFeatures exclude = ["home"] filterset.py class HomeFilter(filters.FilterSet): home_feature = filters.CharFilter(field_name="general_home_features__home_feature") class Meta: model = Home fields = [ "home_feature", ] once I give GeneralHomeFeatures class the same value twice, once filtered, it returns the same instance twice. Example; [ { "id": 1, "user": "cliffaust", "general_home_features": [ { "id": 1, "home_feature": "Pool" }, { "id": 2, "home_feature": "Children Play Ground" }, { "id": 7, "home_feature": "Pool" } ], }, { { "id": 1, "user": "cliffaust", "general_home_features": [ { "id": 1, "home_feature": "Pool" }, { "id": 2, "home_feature": "Children Play Ground" }, { "id": 7, "home_feature": "Pool" } ], }, { "id": 3, "user": "cliffaust", "general_home_features": [ { "id": 4, "home_feature": "Pool" }, { "id": 6, "home_feature": "Children Play Ground" } ], } ] because home_feature of GeneralHomeFeatures has two the same value(pool), it seems like django-filter is returning the same instance twice(based on the serializer id). I don't know if this is a fault in my code, or its just how … -
Django xhtml2pdf generate multiple invoices using For Loop
I am trying to generate multiple invoices/reports in a single .pdf file. Can anybody help me? How can I use for loop for that and generate multiple reports in a single response? -
django automate model creation
hi everyone hope you're all well I'm building an app where the user is gonna be able to add objects to a database through a graphical interface, I can't know in advance the type of data they wanna add, basically I need a way to automate creating tables and adding parameters according to a JSON file, I can implement the logic and parsing of the JSON (which would be like a nested list of data types chosen from a list), but I don't know how to go about actually creating the objects from a script I hope that makes sense please try to help me out, and let me know in the comments if this post lacks clarity thanks in advance -
How to save a class instance using custom APIView in Django REST API without model?
how to create a method to post and get an instance of this class and save it in the viewset? Serialize.py class Videos(object): def __init__(self, duration, timestamp): self.duration = duration self.timestamp = timestamp def retorno(self): return [self.duration] class VideoSerializer(serializers.Serializer): duration = serializers.FloatField() timestamp = serializers.FloatField() def create(self, validated_data): return Videos(**validated_data) ViewSet.py class VideoViewSet(APIView): def Get(self, request, format=None): def post(self, request, format=None): -
How do I access a method from my Model in Django in React
In the following model... class Question(models.Model): question_text = models.CharField(max_length=200) likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) pub_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.question_text}" def validity(self): total_likes = self.likes + self.dislikes percentage = (self.likes / total_likes) * 100 return percentage I want to be able to access Question.objects.get(pk=1).validity() assuming that pk=1 exists in this case. In python shell I can do this easily. But how do I do this using React. I am able to get all my questions and the fields in React without a problem but I don't think I have a way to access the validity method I created. -
ways to pivoting data and render the result to HTML in Django
I am building a simple school-registration app in Django and struggling to figure out how to create a report. The data looks like: ws=[{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 4>}, {'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 5>}, {'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 6>}, {'a': datetime.date(2020, 8, 31), 'b': <BB: 02>, 'c': <CC: 9>}, {'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 4>}, {'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 5>}, {'a': datetime.date(2020, 9, 1), 'b': <BB: 02>, 'c': <CC: 3>}] And i wish to make it look like next, then render it to HTML. \ a b\ |2020-08-31| 2020-09-01| ---|----------|-----------|----- 01 |c= 4,5,6 |c= 4,5 | 02 |c= 9 |c= 3 | Even though spending days of effort, i still do not have any idea. If someone can kindly give me some guidance, i will very very appreciate. -
Complex Query using django-filters
I've been reading all day the documentation of django-filters [Djando-Filters Docs][1], but I cannot figure out how to do a specific complex query. The docs have examples based on only one Model (and even those are a little bit difficult to understand...), but what I need is based on 3 models. class Company(models.Model): id = models.PositiveIntegerField(null=False, blank=False, primary_key=True) name = models.CharField(max_length=255, null=True, blank=True, default="") ... #much more data class Auditable(models.Model): company = models.ForeignKey( Company, null=False, blank=False, on_delete=models.CASCADE, related_name='configurations', ) enabled = models.BooleanField(default=False) class Audited(models.Model): company = models.ForeignKey( Company, null=False, blank=False, on_delete=models.CASCADE, related_name="logs" ) city = models.CharField(null=False, blank=False, max_length=255) self_audited = models.BooleanField(default=False) What I need to do is to select a Company that has not been audited in a specific city (represented as a row on Audited. The city is a parameter (on the Rest call)). Also, the company cannot be a self audited company (self_audited on Audited model), and has to be being Enabled to audition (enabled field on Auditable. Currently, I have a query who works correctly, and it is this: def get_company_audited(self, parameters): # This part retrieve the companies enabled for audition query = Company.objects.filter(configurations__enabled=True) # This part exclude the ones already have been audited on this city … -
mod_wsgi permission denied for apache django running in root folder
Is it a problem to have python code and virtual env in the /root directory itself? Below is the directory structure: /root/cqsite #django project files /root/myenv #python3 virtualenv Below is my apache2.conf (I have installed mod_wsgi as a python3 module, version 4.7.1 inside myenv, and not through apt-get): LoadModule wsgi_module /root/myenv/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so WSGIPythonHome /root/myenv WSGIScriptAlias / /root/cqsite/cqsite/wsgi.py WSGIDaemonProcess cqsite python-path=/root/cqsite:/root/myenv/lib/python3.8/site-packages #python-home=/root/myenv WSGIProcessGroup cqsite <Directory /root/cqsite/cqsite> #AuthUserFile /etc/apache2/.htpasswd # AuthType Basic # AuthName "Restricted Content. The Site is under Development" # AuthUserFile /etc/apache2/.htpasswd # Require valid-user <Files wsgi.py> Require all granted #AllowOverride All #Require valid-user </Files> WSGIApplicationGroup %{GLOBAL} </Directory> Alias /static /root/cqsite/static <Directory /root/cqsite/static> Require all granted </Directory> This is from /var/log/apache/error.log Current thread 0x00007f39108ddc40 (most recent call first): <no Python frame> [Thu Sep 10 21:55:40.274990 2020] [wsgi:warn] [pid 68680:tid 139883067595840] (13)Permission denied: mod_wsgi (pid=68680): Unable to stat Python home /root/myenv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/root/myenv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/root/myenv' sys.base_exec_prefix = '/root/myenv' sys.executable = … -
Error importing cv2: 'libSM.so.6: cannot open shared object file: No such file or directory'
I'm deploying a Django app on AWS elastic beanstalk, and I run into the following error: ImportError: libSM.so.6: cannot open shared object file: No such file or directory. I've attached logs below, the one that describes the error is 'var/log/web.stdout.log'. The initial fix I looked into was to add these lines to my django.config file: 03_install_cv: command: "sudo apt-get update" command: "sudo apt-get install -y libsm6 libxext6 libxrender-dev" But, I still get the same error. Any idea what another fix could be? I've included my logs below. Let me know if there is anything else I can provide that would provide information. Thank you!! /var/log/web.stdout.log Sep 10 19:43:25 ip-172-31-16-39 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/utils/deprecation.py", line 113, in __call__ Sep 10 19:43:25 ip-172-31-16-39 web: response = self.process_request(request) Sep 10 19:43:25 ip-172-31-16-39 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/middleware/common.py", line 53, in process_request Sep 10 19:43:25 ip-172-31-16-39 web: if self.should_redirect_with_slash(request): Sep 10 19:43:25 ip-172-31-16-39 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/middleware/common.py", line 71, in should_redirect_with_slash Sep 10 19:43:25 ip-172-31-16-39 web: not is_valid_path(request.path_info, urlconf) and Sep 10 19:43:25 ip-172-31-16-39 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/urls/base.py", line 154, in is_valid_path Sep 10 19:43:25 ip-172-31-16-39 web: resolve(path, urlconf) Sep 10 19:43:25 ip-172-31-16-39 web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/urls/base.py", line 25, in resolve Sep 10 19:43:25 ip-172-31-16-39 web: return get_resolver(urlconf).resolve(path) Sep 10 … -
Multiple Password DJANGO
I am creating an app that authenticates with users for AD, but then it also needs separate passwords to authenticate for two other services. Is there a way to use 3 passwords to verify login? I can set up log in verification individually for each service, but I was wondering if I could store all three passwords in the same session. Reason being is because users will need to authenticate with multiple services to use all functions of this app. here is roughly what I am doing in my view.py request.session['pass_kinit2030'] = password request.session['reg_pass'] = reg_pass request.session['oraclepass'] = oraclepass -
Issue with migration from Wagtail 2.7.1 to 2.7.4
I had to upgrade Wagtail along with Django for some security updates. When a blow away my local database and rerun the migrations, I get the following errors. My backend is Postgres. Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, cpe, cve4, cvss2, cvss3, enrichment, sessions, taggit, vulnerability, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747... OK Applying cpe.0001_initial... OK Applying cpe.0002_auto_20200129_1941... OK Applying cpe.0003_auto_20200330_2229... OK Applying cve4.0001_initial... OK Applying cvss3.0001_initial... OK Applying cvss3.0002_auto_20200130_0403... OK Applying cvss2.0001_initial... OK Applying cvss2.0002_auto_20200130_0403... OK Applying cve4.0002_auto_20200102_2244... OK Applying cve4.0003_auto_20200106_1747... OK Applying cve4.0004_auto_20200130_0403... OK Applying cve4.0005_auto_20200330_2255... OK Applying cve4.0006_foxscore... OK Applying enrichment.0001_initial... OK Applying enrichment.0002_auto_20200205_1925... OK Applying enrichment.0003_githubrepository_link... OK Applying enrichment.0004_auto_20200205_2220... OK Applying enrichment.0005_auto_20200205_2339... OK Applying enrichment.0006_enrichmentmetrics... OK Applying sessions.0001_initial... OK Applying taggit.0001_initial... OK Applying taggit.0002_auto_20150616_2121... OK Applying taggit.0003_taggeditem_add_unique_index... OK Applying wagtailcore.0001_squashed_0016_change_page_url_path_to_text_field... OK Applying wagtailcore.0017_change_edit_page_permission_description... OK Applying wagtailcore.0018_pagerevision_submitted_for_moderation_index... OK Applying wagtailcore.0019_verbose_names_cleanup... OK Applying … -
Queryset working in regular django but getting KeyError when applying the queryset to a DRF Serializer?
I got the following queryset: queryset = Expense.objects .annotate(month=TruncMonth('expense_date')) .values('month') .annotate(total_cost=Sum('cost')) .values('month', 'total_cost') .order_by("month") Which essentially sums all expense costs and groups them by month. If I just print out the queryset it works fine: <QuerySet [{'month': datetime.date(2020, 9, 1), 'total_cost': Decimal('1029772.00')}]> However, if I try to serializer it: serializer = ExpenseSerializer(queryset, many=True) I get Got KeyError when attempting to get a value for field `cost` on serializer `ExpenseSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'cost'." serializer.py: class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense exclude = ("receipt", ) Whats the fuss? -
Django-rest-framework - how to create or increasing performance of API?
I wanted to create an API as shown below the models. But firstly I am having 2 models profile and stories. S I wanted to create an API wherein profile I'll be having a key name "stories" with a value containing a list of lists order according to -date_created__date in which there will be stories id ordered according to time they were created. And I achieving it using the above code. The question is this code work faster will huge amount of data like 1000000? if not, then how can I optimize it as its performance will increase swiftly? #models.py class Profile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), related_name='profile_user',on_delete=models.CASCADE) followers = models.ManyToManyField('followsys.Follow', verbose_name=_("Follow"),related_name='followers_detail') following = models.ManyToManyField('followsys.Follow', verbose_name=_("Follow"),related_name='following_detail') class Stories(models.Model): user = models.ForeignKey(User, related_name='story_user', unique=False,on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) shoutout = models.ManyToManyField(User,verbose_name=_("Shout Out"), related_name='shoutout', blank=True) song = models.ForeignKey("music.Song", null=True, blank=True, verbose_name=_("Song"), on_delete=models.CASCADE) image = models.ImageField(upload_to=None, null=True, blank=True, height_field=None, width_field=None, max_length=100) viewer = models.ManyToManyField(User, verbose_name=_("Viewer"), related_name='story_viewer',unique=False,blank=True) active = models.BooleanField(_("Active Story"),default=True) #API { "something":"something...", "stories": [ [ 1511 ], [ 619 ], [ 110, 109, 108, 72, 11 ], [ 10 ], [ 8 ], [ 6 ], [ 4, 3 ], [ 1 ] ] } #serializer.py class ProfileSerializer(ModelSerializer): stories = SerializerMethodField() class Meta: model … -
Installing Geos with remote server and Mysql
It a really simple question. I don't understand how I can install GEOS for GeoDjango. I've already installed GeoIP (pip, then apps_installed, download library, create a new folder and create a path in settings) but I don't understand how it works with Geos. Could I install it from the pip? I got an online website. I'm using Cpannel with Mysql (so I only get GEOS, GDAL) thanks a lot for your help, -
Django CORS allowing requests from non-allowed origin
I have Django CORS running with an allowed origin list that looks like this: CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8000', 'http://127.0.0.1:3000', ] Yet if I request this using Python's requests library in my terminal it still allows the request. I've even tried only allowing requests from https://google.com, but it still allows me to use my API. Why is this? (I'm still new to Django, so sorry if this is a bad question) Here are some other settings Installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # internal 'my_app1', 'my_app2', 'my_app3', # third party 'rest_framework', 'corsheaders', 'debug_toolbar', ] Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django_user_agents.middleware.UserAgentMiddleware', ] -
modal form without redirection in django
Is there a method to avoid redirection after submitting a modal form. The modal form opens, a user submits data and the modal form closes. No changes in the page that the modal is triggered from. Examples welcome. Regards Starylass -
How to send HTTP requests asynchronously without waiting for the result with asyncio in a Django 3.1 view?
I'm writing an app in Django that has a linked-list-esque model called Task: # models.py from django.db.models import Model, CharField, ForeignKey, SET_NULL import asyncio import requests import httpx class Task(Model): name = CharField(max_length=255) execute_task_endpoint = CharField(max_length=255) next_task = ForeignKey('self', on_delete=SET_NULL, null=True) def get_trigger_endpoint(self): # the internal django endpoint that calls the .trigger() method endpoint = reverse('trigger_task', kwargs=dict(task_id=self.pk)) return endpoint async def trigger_next_task(self, next_task_trigger_endpoint): async with httpx.AsyncClient() as client: await client.get(next_task_trigger_endpoint, timeout=60 * 3) def trigger(self): # send the request to the outside system to run the task code # this method should wait for this request to finish. r = requests.post(self.execute_task_endpoint) # If the request fails, end the task execution chain if r.status_code != 200: return -1 # If it succeeds, execute the next task in the chain if there is one. if self.next_task: # send the request internally to the execution endpoint in the django system # this method should *not* wait for the response and it should not block the function next_task_trigger_endpoint = self.next_task.get_trigger_endpoint() asyncio.run(self.trigger_next_task(next_task_trigger_endpoint)) return 1 # views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404 from . import models def execute_task(request, task_id): task = get_object_or_404(models.Task, pk=task_id) status = task.trigger() response_msg = f"Task {task_id} {'failed' if status … -
How to create an hierachical user mode in django using django-mptt?
I am buiding an affiliate marketing plateform and i need to store user hierarchie somewhere in the database . Does any one can help me?