Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate mailinblue in django-python
can someone please tell me how can I integrate sendinblue mail service inside my Django app. I have created a project for e-commerce in which if the user clicks on check out and as soon as he checks out, the mail should be sent to his registered email address and the mail should contain invoice in html format. I know how to do for malign but as its free for 3 month whereas sendinblue gives you lifetime n amount of bulk emails to use. so I want to integrate/configure sendinblue, please help. I Appreciate your time and efforts. -
django.db.utils.DatabaseError when updating upvotes of a post
I've created a reddit-like clone web that accept users upvotes and downvotes for both post and comments, however, I keep getting a databaseError. I am using djongo to connect to my mongodb atlas. Everything is working with djongo until I add the upvote/downvote features. I think that my votes up/down calculation updates are correct, I've updated urls.py. The issue is at self.save(). This is the code for the votable models: class Votable(BaseModel): upvote_count = models.PositiveIntegerField(default=0) downvote_count = models.PositiveIntegerField(default=0) class Meta: abstract = True def get_score(self): return self.upvote_count - self.downvote_count @staticmethod def get_object(eid): post = Post.get_or_none(eid=eid) if post: return post comment = Comment.get_or_none(eid=eid) if comment: return comment def toggle_vote(self, voter, vote_type): uv = UserVote.get_or_none(voter=voter, object_id=self.eid) if uv: # Case 1.1: Cancel existing upvote/downvote (i.e. toggle) if uv.vote_type == vote_type: uv.delete() # Case 1.2: You're either switching from upvote to downvote, or from downvote to upvote else: uv.vote_type = vote_type uv.save() # Case 2: User has not voted on this object before, so create the object. else: UserVote.objects.create(voter=voter, content_object=self, vote_type=vote_type) def get_user_vote(self, user): if not user or not user.is_authenticated: return None uv = UserVote.get_or_none(voter=user, object_id=self.eid) if not uv: return None if uv.vote_type == UserVote.UP_VOTE: return 1 else: return -1 def _change_vote_count(self, vote_type, … -
Generate pdf with bootstrap in django
I'm trying to generate a PDF by providing an HTML page in my Django project. I have previously used the pisa library of xhtml2pdf but failed to load bootstrap. It will be very helpful, if the PDF is not only just a screenshot/image containing page, rather a searchable one. Which alternative can I use now? -
Is modifying Django urlconf via set_urlconf and request.urlconf in a middleware safe?
I am changing the default urlconf in a middleware based on the requested hostname and it's working as expected during development, however I am concerned about racing/threads as I am modifying a Django setting at runtime! My concern is that Django would confuse the urlconfs with many concurrent requests. Is that a valid concern? -
Django transferred from windows to M1 Mac not working
I've recently transferred a small Django Project from my windows machine to my new M1 Mac and when try to run the same project which was working with no issues on windows is showing error like this: (venv) sravan_ss@Sravans-MacBook-Air btre_project % python manage.py runserver File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax Manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'btre.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3%@q4cyi9v!3#z#w@cp**1vf&22r_+mlrc!%m8ra-pe#$!uoeu' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # ! Warning # ? Should I # TODO: Make this happen # // line of code # * … -
How to make custom primary key in Django models
I'm building an app that show tables of data. The primary key that my client want is like this Year-4digitinteger-3digitinteger Instance: 20200001001 When the last 3 digit number reach 200 it add 1 to 4digit in the middle and back count from 1 again Below is the example: Before: 20200001200 After add one more data: 20200002001 How can i achieve that? -
Python Stomp.py library is returning 403 error while accessing through outside network
I am working on a product which is working on inside company network. Now requirement is use application outside company network. In application we are using python stomp.py plugin for messaging queue. When we accessing application within company network then everything is working fine. But when we trying to access application outside the company network then stomp.py library throwing 403 error. -
Set a reverse foreignkey relationship in django without saving
if you have an instance of a django object, you can set a field and if you don't save it, it goes away. if you have a foreignkey relationship and you use set, clear, etc. the change you made is immediately written to the db. this makes sense, but is there a way not to do this. As in to temporarily modify the relationship objects, similar to what you can do for a charfield, etc. https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ class Foo(model): name = charfield() class Bar(model): name = charfield() foo = Foreignkey(Foo, related_name="bars", null=True) bar1 = Bar.objects.create(name="bar1") bar2 = Bar.objects.create(name="bar2") foo = Foo.objects.create(id=1, name="dog") foo.bars.add(bar1) foo.bars.add(bar2) foo.name >> "dog" foo.name = "cat" foo.name >> "cat" len(foo.bars.all()) >> 2 foo.bars.clear() len(foo.bars.all()) >> 0 foo1 = Foo.objects.get(id=1) foo1.name >> "dog" len(foo1.bars.all()) >> 0. ---->>>> i want this to remain 2 -
modify the @login_required Decorator in Django to do authentication Role wise - Django, Python
I am working on a project in Django 3.1.2, here I have several models and views, and I have three entities admin, designer and customer. I have created customer and admin site separately, but the designer has some functionalities to modify some files, and entries in database from admin side. I can use @login_required validator to restrict unauthenticated user to access the pages, but I also want to make stop the designer to use all the functionalities of the page which admin can do, so I have taken a field role in user table so that I can easily identify the type of user, but don't know how to use is to create it in decorator so that I don't have to check in every view for the user role. My user models is like given below: models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') can you please help me to create a role based login required decorator. -
How do I sort a Django queryset by frequency of occurance from a list and ensure the remaining objects follow?
I have a Django application running Django 3+ and Python 3.8+. I am trying to fill the front page of my site with relevant accounts to the user currently logged in. I have a list of common tags (belonging to the logged in user), let's call this: common_tags=['tag1','tag2','tag3'] This list can vary in length. My goal: I need to be able to query all my users and filter it in such a way that I get an ordered queryset where the users who have the most common_tags as their tags come up on top. That set of people need to be sorted by who has more tags in common (not based on how many of each tag they have, just the common occurrences with logged in user). This same query set should also contain the remaining users who do not have any of the common tags. Lastly, this queryset should not have any repeats. So far I have: relevant_accounts= User.objects.all()\ .annotate(count_resources=Count('resources')).order_by('-count_resources')\ .order_by(Case(When(resources__tags__name__in=common_tags, then=0),default=1, output_field=FloatField())) This appears to work, but I get repeated values. Running .distinct() does not resolve the issue. Edit: Sample Input/Output User A: Tags = ['A','A','B','C'] User B: Tags = ['A','B','B','C'] User C: Tags = ['A','B','B','B'] Sample User … -
AWS Elastic Beanstalk an error occured: no such file or directory for a Django/Python3 app
I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I was able to stand up my Django project on my local MacBook pro, but when deploying to AWS EB, it failed, logs below: 2021/02/03 23:50:45.548154 [INFO] Executing instruction: StageApplication 2021/02/03 23:50:45.807282 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ 2021/02/03 23:50:45.807307 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/ 2021/02/03 23:50:46.552599 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully 2021/02/03 23:50:46.553257 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/bin/python: no such file or directory 2021/02/03 23:50:46.553265 [INFO] Executing cleanup logic 2021/02/03 23:50:46.553350 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1612396246,"severity":"ERROR"}]}]} My research led me to this post: AWS Elastic Beanstalk chown PythonPath error, but when I tried the suggested command: git rm -r --cached venv in my project directory, it returned: fatal: pathspec 'venv' did not match any files. Any insight would be greatly appreciated! -
Is it good to build SSO app with Django with multiple auth backend?
I'm wondering how good is to build SSO service written in Django with multiple backends (mobile phone + OTP, email + password) using JWT. Is there any best practices and some advices? How Django + Postgres will work together if there will be more than 10 000 users per day. I know all of these are scalable. But, I will be grateful for any architectural advices and recommendations at the beginning. -
'ManyToManyDescriptor' object has no attribute 'all' when accessing related_name
I have 3 models: class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") duration = models.IntegerField( ) def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" class Passenger(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") def __str__(self): return f"{self.first} {self.last}" and I am trying to access all passengers of a certain Flight when I visit /<int:flight_id> like this: def flight(request, flight_id): flight = Flight.objects.get(id=flight_id) # return HttpResponse(flight) return render(request, "flights/flight.html", { "flight": flight, "passengers": Flight.passengers # AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' }) Your response is appreciated Thank you In advanced -
How to add a condition in template to detect super user is the same as post author
I am trying to something new in Django Project, I have different blogs made by users but I want to change the name of superusers or staff to become admin instead of their names. I have made a trial but it didn't work accurately I think the correct way would be similar. Here is the template: {% if post.author == user.is_superuser %} <a class="mr-2 proj-title" href="">Admin</a> {% else %} <a class="mr-2 proj-title" href="{% url 'blog:user-posts' post.author.username %}">{{ post.author }}</a> {% endif %} Currently, all users' name appears either superuser or normal users. Question how can I check is the post.author is a superuser or staff and if staff the name should be admin -
Django - Cannot pass id of Django form to javascript variable
So I read the django documentation and a django form field id should have the format id_(form field name), but when I try to reference this id when assigning the form field to a javascript variable it returns null. To test this, I used auto_id to make sure the id I used in javascript matches the field id I am trying to reference and it does. Additionally, I passed another html element ("testid") to my javascript to make sure it works with the rest of the elements in the template and it does. Why would I be able to assign the id of all of my html elements to a javascript variable but not the django form? forms.py (list of choices not included to save space) class FilterForm(forms.Form): dataset = forms.CharField(label='', widget=forms.Select(choices=DATASET_CHOICES)) graph_type = forms.CharField(label='', widget=forms.Select(choices=GRAPH_CHOICES)) html {% extends 'base.html' %} {% load materializecss %} {% block content %} <form action = "", method = "POST"> {{form|materializecss}} </form> {{form.graph_type.auto_id}} <div id = "testid"></div> {% endblock %} main.js const carInput = document.getElementById("id_graph_type") const testInput = document.getElementById("testid") carInput.addEventListener('change', e=>{ console.log('Changed') }) testInput.addEventListener('change', e=>{ console.log('Changed') }) -
How to prompt category specified form in vue js
In first step form we have one field category field. if user enters "Real estate" based on that we need to prompt Real estate form in second step with some input fields like "total rooms", "square ft". if user enters "IT Training" based on that category we need to prompt IT Training form in second step with some input fields like "Location", "Salary". I have tried a lot this by capturing category from first form by using onchange event. I have written one condition but how to call that particular step 2 form after user enters based on that need too prompt user specified form. onChange(event) { var category = event.target.value if (category == "Real Estaste"){ // Here I need to propt real estate form with some fields // example fields are total rooms, square_ft. }, This is an example code of multi step form please help me to achieve this, Thank you. <html> <head> <script src="https://unpkg.com/vue@next"></script> </head> <body> <html lang="en"> <head> <title>Multistep Form In VueJs</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h3 class="text-success" align="center">Multistep Form In VueJs</h3> <br> <div class="container" id="app"> <div class="panel-group"> <div class="panel panel-primary"> <div class="panel-heading">Multistep Form In VueJs</div> <form class="form-horizontal" action="/action_page.php"> <fieldset v-if="step == 1"> … -
Django Heroku not displaying all images when DEBUG=False
I have deployed my app on Heroku and all works fine when DEBUG=True however when I set this to False some of my images do not show up. They appear on the base.html and the home.html but none of the other pages which I find odd as they use the same path. Here is my static files in settings.py - STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I have tried using whitenoise but Heroku has an error when deploying with it. Any advice? -
Django/Javascript Uncaught TypeError: Cannot read property 'addEventListener' of null [duplicate]
Well I'm trying to start using event listeners in my project but I can't get the get element by id function to work properly. I see no reason why what I have pasted below shouldn't work but I always get the TypeError. Any thoughts? test.html {% extends 'base.html' %} {% block content %} <button id = "id">click me</button> {% endblock %} main.js const carInput = document.getElementById('id') carInput.addEventListener('click', e=>{ console.log('changed!') }) base.html <!doctype html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <!--Custom css--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/css/materialize.min.css" integrity="sha256-qj3p6P1fJIV+Ndv7RW1ovZI2UhOuboj9GcODzcNFIN8=" crossorigin="anonymous" /> <link rel='stylesheet' type='text/css' href="{% static 'style.css' %}"> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/js/materialize.min.js" integrity="sha256-SrBfGi+Zp2LhAvy9M1bWOCXztRU9Ztztxmu5BcYPcPE=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ // Initialize materialize data picker $('.datepicker').datepicker({'format': 'yyyy-mm-dd'}); $('select').formSelect(); }); </script> {% include 'navbar.html' %} <script type='text/javascript' src={% static 'main.js' %}></script> <script type='text/javascript' src={% static 'materialcss.js' %}></script> <title>Data Science Express {% block title %}{% endblock title %}</title> {% block css %} {% endblock css %} </head> <body> <div class='container'> {% block content %} {% endblock content %} </div> {% block scripts %} {% endblock scripts %} </body> </html> -
server is down due to redirection loop
I am using wagtail hook to redirect the homepage to another page in my case it is the LibraryPage here is the code: @hooks.register("before_serve_page") def redirect_to_library_page( page, request, serve_args, serve_kwargs ): if request.path == "/": site = Site.find_for_request(request) library = site.root_page.get_children().type(LibraryPage).first() return redirect(library.get_full_url()) the server is up for few minutes and I can browse different pages and links then after few minutes it is down and I got ingress error here are a sample of logs 10.140.0.51 - - [04/Feb/2021:09:47:33 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.49 - - [04/Feb/2021:09:47:33 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.51 - - [04/Feb/2021:09:47:34 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.51 - - [04/Feb/2021:09:47:35 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.4.5.1 - - [04/Feb/2021:09:47:38 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.50 - - [04/Feb/2021:09:47:38 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.4.5.1 - - [04/Feb/2021:09:48:20 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.49 - - [04/Feb/2021:09:48:26 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.50 - - [04/Feb/2021:09:48:31 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.4.5.1 - - [04/Feb/2021:09:48:31 +0900] "GET / HTTP/1.1" 302 0 "-" "GoogleHC/1.0" 10.140.0.49 - - [04/Feb/2021:09:48:33 … -
ModuleNotFoundError after installing Pillow
The HTTP is giving me the ModuleNotFoundError whichever link I go. The ModuleNotFoundError is giving me the following information: ModuleNotFoundError at /web/ No module named 'django.core.context_processors' Request Method: GET Request URL: http://127.0.0.1:8000/web/ Django Version: 3.1.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'django.core.context_processors' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /Users/william/Documents/coding/WDTP/wfw_fixed/env/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/wfw_fixed/wfw', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Documents/coding/WDTP/wfw_fixed/env/lib/python3.9/site-packages'] Server time: Sat, 23 Jan 2021 00:07:14 +0000 It is happening since I installed Pillow. In my settings.py: """ Django settings for wfw project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Test for settings templates path SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wfw_editor.apps.WfwEditorConfig', 'feedback.apps.FeedbackConfig', ] MIDDLEWARE … -
Django unittest handle PermissionDenied
As docs says https://docs.djangoproject.com/en/2.2/topics/testing/tools/#exceptions; The only exceptions that are not visible to the test client are Http404, PermissionDenied, SystemExit, and SuspiciousOperation. Django catches these exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check response.status_code in your test. I handle a custom a login mixin for raising an error to user logged in but has no access to that page. class LoginQuizMarkerMixin(LoginRequiredMixin): def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: if not self.request.user.has_perm('quizzes.view_sittings'): raise PermissionDenied("You don't have any access to this page.") return super().dispatch(*args, **kwargs) I my unitest, it working fine. class TestQuestionMarking(TestCase): def setUp(self): self.c1 = Category.objects.create_category(name='elderberries') self.student = User.objects.create_user(username='student', email='student@rebels.com', password='top_secret') self.teacher = User.objects.create_user(username='teacher', email='teacher@jedis.com', password='use_d@_force') self.teacher.user_permissions.add(Permission.objects.get(codename='view_sittings')) .... def test_paper_marking_list_view(self): # should be 302 (redirection) marking_url = reverse('quizzes:quiz_marking') response = self.client.get(marking_url) print('response1', response) # should be 403 (permission denied) self.client.login(username='student', password='top_secret') response = self.client.get(marking_url) print('response2', response) # should be 200 (allowed) self.client.login(username='teacher', password='use_d@_force') response = self.client.get(marking_url) print('response3', response) But for somehow, it the error of PermissionDenied it showed an error like this: response1 <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/?next=/quizzes/marking/"> WARNING 2021-02-04 00:28:44,270 log 1 139681767683904 [log.py:222] Forbidden (Permission denied): /quizzes/marking/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) … -
My images doesn´t appear in my ecommerce using Django
When i run my code with the local server my images are not visualized, there are images icons but not the image itself. settings.py: MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') my template tienda.py: {% extends 'tienda/index.html'%} {%load static%} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{{product.imageURL}}" alt="" class="thumbnail" > <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Agregar al carrito</button> <a class="btn btn-outline-success" href="">Ver</a> <h4 style="display: inline-block; float: right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {%endfor%} </div> {% endblock %} my model Product: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank = False) images = models.ImageField(null=True, blank=True) -
Django with jQuery/datatable
I have seen the following Python code which uses jQuery and datatable req = request.GET sort_col = req['columns[%s][data]' % req['order[0][column]']] glob_search_val = req['search[value]'] if req['order[0][dir]'] != 'asc': Where can I find more information on the structure of columns, order, search (and other) parameters passed to the server from jQury/datatable? -
Django override delete method
How can I override delete method ? I want to prevent delete not your posts by users. Using JWT auth serializers.py class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = '__all__' ... ... def delete(self, instance): user = self.context['request'].user if user.pk != instance.author.id: raise serializers.ValidationError( {"authorize": "You dont have permission to delete this post."}) instance.delete() views.py class PostDelete(generics.DestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated] -
How to add a CORS Domain Wildcard rule with Static Port
I'm trying to set up a CORS rule in my Django python web app to allow any domain/subdomain from port 8092 to access my API. I have added this line http://*:8092 to my CORS array, but no luck. I'm getting the following error Origin http://mbps-mbp.lan:8092 is not allowed by Access-Control-Allow-Origin. My goal is to allow Cross-Origin communication for port 8092 to my API. Is it possible to add a rule like that?