Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add login in django by rest API in a template
how are you? I am totally new in Django and I am working on a project that is for task managing. every owner of a task can edit or update but no one else can. I wrote a login function that works correctly but now I want to rewrite it with the rest. I wrote a navbar in which by pressing the login button (in that)you will see the login.html. How can I write login in rest and connect it with my login.html ? Also, I have a question that how can I protect the update and delete method that only the admin and the owner can do them? Thanks in advance My login.html {%extends 'base.html' %} {% block content %} <body> <div id="container"> <div></div> <div class="container"> <h1>Login</h1> <p>Please fill in this form to login.</p> <hr> <form method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <label for="username"><b>Userame</b></label> <input type="text" placeholder="Enter Username" name="username" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <div class="row justify-content-center "> <button type="submit" class="signupbtn btn btn-primary" name="btn">Login</button> </div> </form> {% for message in messages %} <div class="alert alert-danger d-flex align-items-center" role="alert"> <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg> <div> {{ message }} … -
Django: Using multiple select with dynamic Data from SQL
I am in the process of creating a graphical interface for filtering SQL data. There the corresponding table should be selected first. Then it should be possible to select with the drop-down list, which columns of the respective table should be displayed. Does anyone have an approach for me there? Thanks a lot :) Returns the names of the columns of the passed table -
How to count all objects in a queryset related to a specific fields value?
I have a Model Poller that has a field category. I have a filtered queryset of Poller. Now I would like to count the objects for each category like so: Poller 1: Category - Sport Poller 2: Category - Sport Poller 3: Category - Tech Poller 4: Category - Tech Poller 5: Category - Fashion should return a dictionary somewhat to counts = {'Sport' : '2', 'Tech' : '2', 'Fashion' : '1'} # Model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # View / query qs = Poller.objects.filter( created_by__username=username).order_by( '-poller_category') Not sure but the ordering itself might be obsolet probably. -
How to get backend data in invoice pdf in django
In invoice.html file where i am rendering data from backend but i don't know how to get data in pdf how to pass the context this is my view can anyone tell me about that? -
How to set query to Autofill Data using Django
My Models: '''class Client(models.Model): name = models.CharField(max_length=40) contact = models.CharField(max_length=11) address = models.CharField(max_length=50) def __str__(self): return self.name class Area(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Route(models.Model): area = models.ForeignKey(Area, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return "%s %s %s" % (self.area, ",", self.name) class Driver(models.Model): name = models.CharField(max_length=30) phone = models.CharField(max_length=11) salary = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) active = models.BooleanField(default=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) def __str__(self): return "%s" % (self.name) class Attendance(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) name = models.ForeignKey(Driver, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) date = models.DateField() week_one = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_one_loan = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_one_extra = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two_loan = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two_extra = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00)''' I have 5 class 1- client and its just name 2- area also only name 3- route its part from area to make it easy to filter and all name 4- driver name , salary , route from class , client from class 5- attendance here i add it every month (date/ client/driver) all definitely so i have to filter I want when I add data in Attendance class once I select Driver … -
is this correct using of foreign key ? i get error by migrate
class CustomerDetail(models.Model): name = models.CharField(max_length=100,default='') phone_no = models.CharField(max_length=10,unique=True,default='') dob = models.DateField(default='') def __str__(self): return self.name class orderview(models.Model): reference = models.CharField(max_length=100,default='') customer = models.CharField(max_length=100,default='') overalltotal = models.ForeignKey(CustomerDetail, on_delete=models.SET_NULL,null=True,blank=True) def __str__(self): return self.reference class orderdetails(models.Model): product = models.CharField(max_length=100,default='') quantity = models.IntegerField() unit_price = models.IntegerField() total= models.CharField(max_length=30) orderid = models.ForeignKey(orderview,on_delete=models.SET_NULL) def get_total(self): result = self.quantity * self.unit_price return result def save(self, *args, **kwargs): self.total = self.get_total() super(orderdetails, self).save(*args, **kwargs) -
Django "manage.py startapp" functionality through a view
I am trying to create a django app dynamically with respect to user inputs and would want to do it in a view (after a POST request). Is it possible to run python manage.py startapp myNewDynamicApp through Django's view rather than through CLI? I could use shell scripts and call them through os.system() but I wanted to check for options in the current space rather than that. -
Dynamic Dual List Box with django
I'm try to realize a dual Dynamic Dual List Box with django. I try to adapt this jquery plugin: https://www.jqueryscript.net/form/Dual-List-Box-Multi-Selection.html but it doesn't work: button it seems doesn't be cliccable. This my code: forms.py from django import forms from station.models import Station station_all=Station.objects.all() class VdlForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) selected_stations = forms.ModelMultipleChoiceField(queryset=Station.objects.none()) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .forms import VdlForm def new_vdl(request): template_name = 'vdl.html' heading_message = 'Add a new vdl' if request.method == 'POST': form = VdlForm(request.POST or None) if form.is_valid(): vdl_name = form.cleaned_data.get("vdl_name") stations = form.cleaned_data.get("stations") return HttpResponseRedirect('new_vdl') else: form = VdlForm() return render(request, template_name, {'form': form, 'heading': heading_message, }) vdl.html {% extends 'base.html' %} {% block content %} <form method="post" novalidate> {% csrf_token %} <div class="jp-multiselect"> <div class="from-panel"> {{ form.vdl_name }} <br> {{ form.stations }} </div> <div class="move-panel"> <button type="button" class="btn-move-all-right btn-primary"></button> <button type="button" class="btn-move-selected-right"></button> <button type="button" class="btn-move-all-left"></button> <button type="button" class="btn-move-selected-left"></button> </div> <div class="to-panel"> {{ form.selected_stations }} </div> <div class="control-panel"> <button type="button" class="btn-delete"></button> <button type="button" class="btn-up"></button> <button type="button" class="btn-down"></button> </div> </div> <button type="submit">Submit</button> </form> <script> $(".jp-multiselect").jQueryMultiSelection(); </script> {% endblock %} in my base.html I import the js file mentioned in … -
How to debug and fix the error in the Django
One of the most important problems we face in Django is how to fix the error. There is an error below that I do not know how to troubleshoot and fix the error. What is the best approach and tools for error detection? E:\Bourse\BourseWebApp\BourseDjangoAPI>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\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 'rest_framework' Traceback (most recent call last): File "E:\Bourse\BourseWebApp\BourseDjangoAPI\manage.py", line 22, in <module> main() File "E:\Bourse\BourseWebApp\BourseDjangoAPI\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File … -
How to get field name from model in django forms?
I have a form and need to change its field name with model value ! I have a model named "Documents" and it has two fields "type and path" ! Now am using model form to create the form My question is when i display the form, the label of "path" is just "Path" but i need to change that to "type" How to achieve this ? -
Django id vs pk in fixtures/loaddata
A strange (to the uninitiated lol) issue with models using a CharField for a primary key/id: id = models.CharField(max_length=10, primary_key=True) Feeling I know what I'm doing, I've created the following (json) fixtures file: [ { "model": "products.product", "id": "am11", "fields": { "title": "Test Product A", } }, { "model": "products.product", "id": "am22", "fields": { "title": "Test Product B", } } ] , and proceeded with loading it: ✗ python manage.py loaddata fixtures/products.json Installed 2 object(s) from 1 fixture(s) Well, it kinda lied. A check on the admin page or in a shell shows that there's only one Product in the database - the last one in the fixture's list. Curiously enough, attempts to delete this Product via the admin page silently fail, only via the shell can it actually be deleted. Further investigation (in the shell) revealed an interesting problem - that (single) Product created has pk/id set to an empty string(?!). If I manually create another, either on admin page or in the shell, the new product appears without any issues, both id and pk set to the string given. But loaddata with fixture fails on this. Originally discovered this problem when a basic test failed - given the … -
React Native Render HTML bullet list is not centered with text
Im using react-native-render-html library (https://github.com/meliorence/react-native-render-html to display data from Django Rest Framework. As basic styling is working properly I have problem with <ul> tag - text is not centered with circle/square/number as shown in image. I tried using renderersProps like: <RenderHTML renderersProps={{ ul: { markerBoxStyle:{ paddingRight: 3, top: 5 }, markerTextStyle: { color: "red" } } }} /> but it works only style this for current text size. If I change text size in style in django admin, the element and text arent centered again. Is there any option how to fix it or what causes the problem? -
Converting dictionary's queryset
I am building a Simple Blog App and I made a queryset which is showing blog date and likes of every day since blog date, But it is showing in dictionary and i am trying to show both instances differently in table like. Blog Date Likes 20 Sep. 6 Likes 21 Sep. 2 Likes But it is showing like :- ({20: 1},{21: 4}) views.py def page(request): blogpost = get_object_or_404(BlogPost,pk=pk) totals = blogpost.likes_set.filter( blogpost__date=blogpost.date, ).annotate( date=ExtractDay('blogpost__date'), ).values( 'date' ).annotate( n=Count('pk') ).order_by('date').values() results = Counter({d['date']: d['n'] for d in totals}) context = {'results':results} return render(request, 'page.html', context) What have i tried ? :- I have tried lists = [{'id': blog.date, 'name': blog.n} for blog in results ] But it is showing only date like 24 not the likes. than i tried json.dumps(list(results )) Any help would be much Appreciated. Thank You -
Matching query does not exist ERROR: "__.models.__.DoesNotExist: __ matching query does not exist."
I'm trying to send data to my database using Django Models and Views file but I'm continuously getting this error: "raise self.model.DoesNotExist( crm.models.Time_Stamps.DoesNotExist: Time_Stamps matching query does not exist." I do have 'Time_Stamps' as a Model in models.py file. How to resolve it? views.py def update_counter(request): if request.method == 'POST': timestamp = Time_Stamps.objects.get() counterValue = request.POST['counter'] #timestamp.Task_ID = counterValue timestamp.startTime = request.POST['timestamp'] print(counterValue) print(startTime) timestamp.save() message = 'update successful' return HttpResponse(message) models.py class Time_Stamps(models.Model): TimeStamp = models.IntegerField(default=0) def __str__(self): return self.TimeStamp class Meta: verbose_name_plural = 'TimeStamps' ERROR ...................... File "C:\Users\kushw\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( crm.models.Time_Stamps.DoesNotExist: Time_Stamps matching query does not exist. [24/Sep/2021 15:44:27] "POST /update_counter/ HTTP/1.1" 500 73227 -
upgrading docker compose version in ubuntu linux
my system os is ubuntu ,docker-compose version was 1.25 but imported python-django web app has project has composefile in version was 3.9. how to upgrade my sysytem docker-compose version -
how to implement add another to django model form
I'm trying to implement + button for foreign key select field , if the foreign key doesn't exist instead of going to another page just pop up a form page to add new entry for the foreign key , I've implemented but its full size and dont go to the previous page and shows only a blank page when i submit the form : this is what i tried my models.py class MainGroup(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) def __str__(self): return self.main_type class Meta: db_table = 'maingroup' class PartGroups(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) def __str__(self): return self.part_group and this is my forms.py from django.contrib.admin import site as admin_site,widgets class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('some message'), 'unique':_('some message'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('placeholder')}) } class PartGroupForm(forms.ModelForm): main_type = forms.ModelChoiceField(queryset=MainGroup.objects.all(),empty_label=_('label')) def __init__(self, *args, **kwargs): super(PartGroupForm, self).__init__(*args, **kwargs) self.fields['main_type'].widget = ( widgets.RelatedFieldWidgetWrapper( self.fields['main_type'].widget, self.instance._meta.get_field('main_type').remote_field, admin_site, ) ) class Meta: model = PartGroups fields = ['admin','main_type','part_group'] error_messages = { 'main_type':{ 'required':_('some message'), }, 'part_group':{ 'required':_('some message'), } } widgets = { 'part_group':forms.TextInput(attrs={'placeholder':_('group')}) } and this is my views.py @login_required def create_productgroup(request): form = ProductGroupForm() if request.is_ajax() and request.method … -
Firebase cloud messaging app initialization - credentials
I'm trying to learn how to implement push notifications to an PWA app running Django backend and try to use Firebase Cloud Messaging as a push service. I've created a project in the Firebase control panel and a service account + downloaded credentials as a json -file. I installed a library called fcm-django and seems like the migrations went well and I got a new table into my database called fcm_django_fcmdevice. I built a simple test view just to test stuff, not to make actual push notifications yet, but I struggle with authentication. Every time I try to make a request into my endpoint /push/, I get this error: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started. I read that page and installed firebase-admin package into my app. I also run this in my terminal: export GOOGLE_APPLICATION_CREDENTIALS="/path/to/my/credentials.json", but the error is the same every time. I also tried to copy the creds.json into the same dir as my settings.py and did this: from firebase_admin import initialize_app, credentials cred = credentials.Certificate("creds.json") FIREBASE_APP = initialize_app(cred) With this, I get this error: FileNotFoundError: [Errno 2] No such file or … -
Retaining newlines in input form
I realise there are many questions similar to this, but they all seem to answer the flip-side: "How do I display..." I can show that I'm not getting the newlines from the request object environment django 2.2.1, qunicorn 19.9.0 .. running in a docker image build on a python 3.7 base image setup Pre-populate a database record: update api_entitlement set notes= E'line 1\nline2\nline3' where guid='44aa651c-ea98-4990-aa85-d87d21db6043'; .... and confirm the data is there: select * from api_entitlement where guid='44aa651c-ea98-4990-aa85-d87d21db6043'; id | guid | notes -------+--------------------------------------+-------- 14053 | 44aa651c-ea98-4990-aa85-d87d21db6043 | line 1+ | | line2 + | | line3 (1 row) The fragment of template that creates the textarea is thus: <pre id="{{ entitlement.guid }}_notes">{% if entitlement.notes == '—' or entitlement.notes is None %}—{% else %}{{ entitlement.notes }} {% endif %}</pre><textarea id="{{ entitlement.guid }}_notes_new" type="text" class="form-control" value="{% if entitlement.notes == '—' %} -{% else %}{{ entitlement.notes }}{% endif %}" style="display:none">{{ entitlement.notes }}</textarea> (there's some javascript that toggles from display to edit, from the <pre> to the <textarea>) and the code that reads the form is thus: def get(self, request, *args, **kwargs): logger.info(f"notes value is {request.GET}") # # snip irrelevant code # value = request.GET.get('notes') logger.info(f"notes value is {value}") if value != '-' … -
ManyToMany Field serializer in django
I have successfully serialized my Blog model, but in it, there are two ManyToMany Relationships, one is for Category and the other for SubCategory, all these can be one or more. The GET method is working as exactly expected, the issue stays with the POST. Models: ` class Category(models.Model): category_name = models.CharField(max_length=100) sub_category = models.ManyToManyField(SubCategory, blank=True, ) added_on = models.DateTimeField(auto_now=True) icon = models.CharField(default="pi-angle-double-right", max_length=30, help_text="Icons can be picked from https://www.primefaces.org/primevue/showcase-v2/#/icons") def __str__(self) -> str: return self.category_name @property def total_blogs(self): return Blog.objects.filter(category=self).count() class Blog(models.Model): """ Blog table """ colors = [("r", "danger"), ("s", "success"), ("i", "info"), ] title = models.CharField(max_length=250, help_text="Unique, catchy topic of the article", unique=True, null=True, blank=True) body = CKEditor5Field( 'Add a body', help_text="Full body of the article, supports markup", config_name='default', null=True, blank=True) introductory_file = models.ImageField( upload_to="blog_intros", null=True, blank=True, help_text="Cover image to introduce the rest of the blog", validators=[validate_image_file_extension, validate_img_extension]) author = models.ForeignKey(Author, on_delete=models.CASCADE) blog_color = models.CharField( choices=colors, null=True, blank=True, max_length=10) posted_on = models.DateTimeField(auto_now_add=True) upvotes = models.ManyToManyField( User, blank=True, related_name="upvoters") downvotes = models.ManyToManyField( User, blank=True, related_name="downvoters") slug = models.SlugField(unique=True, blank=True, null=True) category = models.ManyToManyField(Category, verbose_name="category") sub_category = models.ManyToManyField( SubCategory, blank=True, verbose_name="subCategory") schedule_to = models.DateField( null=True, help_text="If you are want to schedule the blog to a future date.", blank=True) contributors … -
Get multple related objects from Django ORM
I have such model in Django: from django.db import models class Document(models.Model): name = models.CharField(max_length=256) class Template(models.Model): name = models.CharField(max_length=256) document = models.ForeignKey(Document, on_delete=models.CASCADE) class SharedDocument(models.Model): workspace = models.CharField(max_length=256) document = models.ForeignKey(Document, on_delete=models.CASCADE) I need to get list of templates by workspace in SharedDocument. I was doing this query: >>> shared_documents = SharedDocument.objects.filter(workspace='1').prefetch_related('document') >>> [shared_document.document.template_set.get() for shared_document in shared_documents] But from my prospective it looks a little bit ugly. So the question is: "Is it possible to do what I want by forming query without this part: [shared_document.document.template_set.get() for shared_document in shared_documents]"? To clarify: As a result I want to have a list/QuerySet with Template objects. Regards, Oleg -
UnboundLocalError at /signin/ local variable 'user' referenced before assignment in Django
Function to let the user to login as follows=> Obviously this error pops def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password =password ) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) elif user is None: return render(request, "covi/signin.html", { "message": "Invalid username and/or password." }) else: return render(request, "covi/signin.html") -
Set-Cookie doesn't set cookies, problem with samesite Django & React
I try to store my refresh token which I get from django backend. The log() functions looks like it's working fine, I mean when I click F12 and open the Network tab I get an response login/ which has a Set-Cookie field, f.e. it looks like this: Set-Cookie: refresh_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXVlLjoicmVmcmVzaXIsImV4cCI6MTYzMjU2MTY4OSwianRpIjoiZTg2MjhkMjhmOWJmNPMxYzg4ZjAyNjE3ZDNmMzFmNGUiLCJ1c2VyX2lkIjoiNDU1OTZkNTktNDI1Yy00ZmMxLThlYmUtNWU2YjQzMFRkZjQkIn0.ALfovbSQGIw6Hq6607LXXyhXXcvoUvUUlElCxnvRJfg; expires=Sat, 25 Sep 2021 09:21:29 GMT; HttpOnly; Max-Age=300; Path=/ but there is a problem too with SameSite field: This Set-Cookie header didn't specify a "SameSite" attribute and was defaulted to "SameSite=Lax" and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The Set-Cookie had to have been set with "SameSite=None" to enable cross-site usage I don't get it because I delared the samesite=None in my django view: response = Response(details, status=status.HTTP_200_OK) response.set_cookie('refresh_token', str(refresh), httponly=True, secure=False, samesite=None, max_age=300, path="/", expires=int(SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'].total_seconds())) and the problem is that cookies are not stored in F12 > Application > Cookies > http://localhost:3000 My login function looks like this: export const login = async (data) => { const response = await log(data); if (response.data.access_token) { http.defaults.headers.Authorization = `JWT ${response.data.access_token}`; } else { delete http.defaults.headers.Authorization; } }; log() looks like this: export const log = async (credentials) => { return … -
Isadminuser or Allowyany permission based on the request method in APIView
I have to make a custom permission class based on the request method and the slug that has been passed. I am using APIView to write business logic. The requirements are as follows: 1. Allowany for all the methods except POST. 2. IsAdminUser for POST if slug is abc or Allowany if slug is xyz. My view looks like this: class Example(APIView): permission_classes = [CustomPermission] def get_by_slug(self, slug): return Example.objects.filter(slug=slug).first() def get(self, request, *args, **kwargs): slug = kwargs.get("slug") example = self.get_by_slug(slug) serializer = ABCSerializers(example) return Response(serializer.data) def post(self, request, *args, **kwargs): slug = kwargs.get("slug") setting = self.get_by_slug(slug) if slug == 'abc': ........................................ ///////////////////////////////// For this, I have to define Custompermission which inherits from BasePermission class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request, view): user =request.user if request.method == 'POST' and slugs == 'abc': return True Now, I dont know how to get slug here. The slug here is acquired form **kwargs. But kwargs cant be defined inside has_permission. How can we do this?? -
Django application not working because of uninstalled packages in aws producing 500 internal server error
I have developed a software in python on my system with all the needed packages downloaded and they all worked well. I have also configured aws lightsail to connect apache server following the article in https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ and it worked very well. I have tried to install the needed packages into aws but when I connected it to apache. it was producing error 500 internal server error then on further checking I discorvered that the packages I installed were not installed into proper directory where it was supposed to be located where apache would be able to find it so it was producing error 500. How can I install my python packages into the directory where apache would be able to use it? -
How to pre-populate (Multiple)ChoiceField in Django based on previous user selection
I managed to store and update a selection of categories made by the user to the database. Now I want to pre-populate the MultipleChoiceSelect with this selection once the user queries the form again to update his selection. So my current form will always return all available categories. How can I apply the users personal selection to this? # View @require_POST def save_category_filter(request): # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): # Get the cleaned data selection = filter_form.clean() # Check if user already has a filter instance instance_exists = UserCategoryFilter.objects.filter(user=request.user) # If not create, else update if not instance_exists: filter_instance = UserCategoryFilter(user=request.user, categories_selected=selection) filter_instance.save() else: # Update existing instance UserCategoryFilter.objects.filter(user=request.user).update(categories_selected=selection) else: .. # Models class UserCategoryFilter(models.Model): """ Saves the selected category filter by a user """ user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) class Category(models.Model): """ Model to store all available categories """ poller_category = models.CharField(max_length=30) # Form class SelectCategoryForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) This is how the selection of the user is currently saved: