Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i set default permission classes to my custom permission (Django Rest Framework)
I created a custom permission to allow users only with a specific API KEY to access my API endpoints.. from rest_framework import permissions from django.conf import settings class CustomerAccessPermission(permissions.BasePermission): def has_permission(self, request, view): is_allowed = request.META.get('HTTP_X_APIKEY') == settings.API_KEY return is_allowed How do i apply this to my REST_FRAMEWORK configurations in settings.py as a default PERMISSION_CLASS OR is there a better way for me doing this.. (NOTE: i have already handled authentication, i don't want authenticated users to access my end points) -
Is it possible to get the render initiator in django-cms?
Is there a way to find out where the render_plugin-call occurred? Example: I have a CMS Plugin A that renders its children regularly, but I want to include another CMS plugin B to also render A's child plugins, so I'd like to check in A's child plugin template wether it was initiated by parent A or parent B. -
How to implement Social Auth with django and swift?
If I am using swift to obtain the user token from social sign in like (facebook, google). How safe it will be for me to get userId from those tokens and hash it with my backend and save it in my database. So that every time, users login with social providers, their userID's will be updated and hashed. -
Render Django M2M Field with selection
I have a list of models of class A. I would now like to transfer these instances of A to an M2M field via a selection. I would like to have a selection like in the example picture. Is there already a finished widget here, or do I have to make it completely myself? enter image description here many thanks -
save the corresponding id of a selected values from a multiselect field django form
I am new to django and I am trying to implement if user selectes his category interest from a multi select form I want to save its corresponding category id in database.my django code is like below Interest table looks like category_id. category_name 101. Food **models.py** class Interest(models.Model): category_id=models.IntegerField() category_name=models.CharField(max_length=50,null=True) class User_Interest(models.Model): userCD=models.ForeignKey(User,on_delete=models.CASCADE) category_id=models.ForeignKey(Interest,on_delete=models.CASCADE) **forms.py** class UserInterestForm(forms.ModelForm): class Meta: model = User_Interest fields=['userCD','category_id'] choice=Interest.objects.all() ch_list=[] for ch in choice: ch_list.append([ch.category_name,ch.category_name]) interest = MultiSelectFormField(choices=ch_list) **admin.py** class User_InterestAdmin(admin.ModelAdmin): exclude = ('category_id',) list_display=('userCD','category_id') form=UserInterestForm Here am able to select interest in checkboxes but category id's storing category_id as "Null".Can anyone please guide me what should I need to do achieve my requirement. expected output:User_Interest table UserCd category_id xxxxx. 101 -
How to hide variables in the URL?
I am getting a "Method not allowed (POST)" error on my site and I try to understand how to avoid that. I have a django-tables2 table with a button, that calls a SingleTableView. I had a working piece of code that looked like this: class AllProductsColumn(tables2.Column): empty_values = list() def render(self, value, record): return mark_safe(f"""<a href="/product_all/{record.get_store_id}/{record.name}"> <button class="btn btn-secondary">view</button></a>""") and in the table I called it with view = AllProductsColumn(orderable=False) and this worked using this url pattern: path(r"product_all/<int:store_id>/<store_name>", views.ProductView.as_view(), name="product-all"), Then I came to the point where I wanted to make everything "nicer" and therefore hide the variables. So I rewrote the table as: ViewTemplate = (f"""<form id="params" action="/device_all/" method="POST">{{% csrf_token %}} <button class="btn btn-secondary"> <input type="hidden" name="store_id" value="{{ record.get_store_id }}"/> <input type="hidden" name="store_name" value="{{ record.name }}"/> view</button> </form>""") and changed the URL pattern to: path(r"product_all/", views.ProductView.as_view(), name="product-all"), and this obviously does not work, because the SingleTableView has no method post. So ... how can I hide my variables? view: class ProductView(SingleTableView): model = Product template_name = "app/product_all.html" table_class = ProductTable paginate_by = 10 -
Determine if Django REST Framework serializer is used in context of many=True
I have a Django REST Framework serializer that is used in several places. One of the fields is a SerializerMethodField that I only wanted to include if the serializer is used to serialize only a single object. Basically, I want to not include one of the SerializerMethodField (or change it's behavior) when I have that MySerializer(objects, many=True). Any ideas how to do this? -
I don't understand why my form is not validating in django
I am still new to django. Playing around with a leadmanager app and I don't know why my form is not validating. views def index(request): lead=LeadForm() if request.method == 'POST': lead=LeadForm(request.POST) if lead.is_valid(): messages.success(request, f'Thank you for registering. Someone will be contacting you soon.') return redirect('index') else: lead=LeadForm() messages.error(request, f'Something went wrong. Please try again later.') return render(request, "frontend/index.html", {'lead':lead}) in index.html <form action="" method="POST" class="lead-form"> {% csrf_token %} <fieldset class="lead-info"> <div class="form-control"> <label for="">Full Name</label> {{ lead.fullname }} </div> <div class="form-control"> <label for="">Email</label> {{ lead.email }} </div> <div class="form-control"> <label for="">Phone</label> {{ lead.phone }} </div> <div class="form-control"> <label for="">City</label> {{ lead.city }} </div> </fieldset> <button type="submit" class="btn-pill">Submit</button> </form> in forms.py class LeadForm(forms.ModelForm): email = forms.EmailField() class Meta: model = Lead fields = ['fullname', 'email', 'phone', 'city', 'contact_preference'] widgets = {'contact_preference': forms.RadioSelect } Any help is appreciated. contact_preference is rendering FYI, I just cut the code to keep this question not that long. -
Vue.js + Axios not assigning response
I have the following vue.js code using django as a backend. The response is coming through fine, but I can't seem to set the variable properly. Am I doing something wrong with the assignment? Thanks <script> import axios from 'axios' //Datatable export default { data () { return { items: [], } mounted () { this.getItems() }, methods: { getItems() { const newLocal='http://127.0.0.1:8000/items/' axios({ method: 'get', url: newLocal, auth: { username: 'login', password: 'pass' } }).then(response => { let result = []; result = response.data; console.log(response.data); console.log("Data length: " + response.data.length); /// Returns '7' console.log("Result length: " + result.length); /// Returns '7' this.items = result; console.log("Item length #1: " + this.items.length) /// Returns '7' }) console.log("Item length #2: " + this.items.length) /// **Returns '0' ???** }, -
Change a boolean value after a click on a button in Django does not work
I need some help regarding button clicks and boolean value changes in django. My model: class Topic(models.Model): subject = models.CharField(max_length=255) category = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics') slug = models.SlugField(unique=True) isReported = models.BooleanField(default=False) startPrice = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')]) I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button: <button type="submit" class="btn btn-primary btn-block">Report</button> How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button. I somehome tried to adapt the code of the link: views.py: def ajax_change_status(request): isReported = request.GET.get('isReported', False) pk = request.GET.get('pk', False) # first you get your Job model job = Topic.objects.get(pk=pk) try: job.isReported = isReported job.save() return JsonResponse({"success": True}) except Exception as e: return JsonResponse({"success": False}) return JsonResponse(data) xxx.html: <form method="post" novalidate> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button> </form> <script> $("#change").on('click', function () { var pk = '{{ topic.pk }}' var isReported = 'True' $.ajax({ url: '/ajax/change_status/', data: { 'isReported': isReported 'pk': pk }, dataType: 'json', success: function (data) { if (data.success) { alert("ajax call success."); // here you update the … -
Django Integrity Error: Unique Constraint Failed [closed]
strong textHere is the input. And the output is giving me the error. -
django unittest to use "real" database
I am currently writing test cases for views, Which eventually uses database also. By default a test database is being created and removed after test are run. As the database itself is development database, I don't want my test to create a separate db but use exciting only. Also I will like to bring to your notice, that in my environment, database are created and provided and django can't run migration or create database. How can I create unittest which uses real database ? -
How to make an IAM Role for a Django Application?
I want to make an IAM Role for my Django app. How can I do this both from AWS side and Django side? Also, I have heard that this is best practice, but don't really understand why it is important. Could someone explain? Thanks! -
Django error for image upload to S3 bucket using Rest Post Request
I am learning and trying how to upload file in Django using Post method, and here I encountered two errors for the same code Postman uploading via Post->form-data error is {'bookName': [ErrorDetail(string='This field is required.', code='required')], 'bookCover': [ErrorDetail(string='No file was submitted.', code='required')]} Uploading via web-based Django Framework : { "bookCover": [ "The submitted data was not a file. Check the encoding type on the form." ] } Serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['bookName', 'bookCover'] # '__all__' for all View.py @api_view(['GET', 'POST']) def book_list(request): elif request.method == 'POST': # user = request.user # if not user: # return Response(status=status.HTTP_403_FORBIDDEN) serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Url.py path('books/', book_list) I am using the same URL for post and get request. books/ and books/?name=Book1 get request books/ for post I am trying to upload books image to s3 using post request. If I remove the image field then its working fine for web-based API it's creating the book object but for the postman, it just gives error even if I try the raw data instead of form-data. for web-based Post request: { "bookName": "Book8", "bookCover": null // here should I use … -
i have to transfer cust data to book. any possible method ? let me know please
from.models import Book,Cust Cust.objects.get(acc, no1) Book.objects.create(ac="acc",no="no1") -
How to reduce latency in a web application that uses Django in the backend?
What is the most suitable tech stack for a web application, keeping the priority to low latency? I have knowledge in Django but Python isn't really the solution for latency. Di need to start coding the entire backend in c++ or just a part and make it work with the Django server? If You happen to know any solution, please attach links for reference. I am a beginner. -
DevTools failed to load SourceMap: Could not load content http://localhost:8000/static/assets/plugins/bootstrap/css/bootstrap.min.css.map
Could you please tell me why I am getting this error when I tried to run a project in local django server(localhost:8000),the application is loaded with this error in console... DevTools failed to load SourceMap: Could not load content for http://localhost:8000/static/assets/plugins/bootstrap/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE Thanks in advance, Parvathy -
can i show data with Pagination in two different html pages from views using Django?
hello i want show data with pagination in two different html pages i mean i have model called PCgames and i want pass data to ( two different html page ) i have added this in views.py : def pc_games(request): app = PCgames.objects.all() page = request.GET.get('pc-games-page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pc_Games_one = paginator.page(page) except PageNotAnInteger: pc_Games_one = paginator.page(1) except EmptyPage: pc_Games_one = paginator.page(paginator.num_pages) return render(request,'html_file/pc_games.html', { 'pc_Games_one': pc_Games_one }) this code is render to pc_games.html and i want pass same data to home.html how i can do that ? -
ERROR 1045 - A big problem with the access to my mysql db
I was trying to execute "python manage.py migrate" in my project directory made in django. The output was: django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") So, I thought that I was having a problem with the db password of root user, I saw toturials to change the password, then, I try to enter with "mysql -u root -p" and it tried to enter but it did not accept, it said it was invalid. I tried "sudo" and if it worked, I changed the password and everything was fine. but when I try to migrate data I still have same dilemma. django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") I assumed that I had to see that I could only do it with "sudo", the question is that I needed to use the data for my project to make use of them auth': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'api_db_project', 'USER': 'root', 'PASSWORD': 'PASSWORDRANDOM', 'HOST': 'localhost', 'PORT': 3306 }, I thought that I had not solved the problem so I look for more guides and I find:https: //stackoverflow.com/questions/39281594/error-1698-28000-access-denied-for-user-rootlocalhost $ sudo mysql -u root # I had to use "sudo" since is new installation mysql> USE mysql; mysql> UPDATE … -
How to call python OpenCV on the browser in a WSGI application
I am building a face detection web app. I have a WSGI client & server. The client is supposed to capture the frames and pass it to Redis datastore. The server is supposed to process the images and send it back. The problem I am facing is that the WSGI client is calling the python OpenCV library on the browser which isn't being loaded. Is there anyway I can use the python OpenCV library on the browser using Django maybe? I'm quite new to Django/WSGI so any help would be much appreciated! Thanks. -
Can't access errors when rendering a field individually
In views.py: if form.is_valid(): # ...process form... return HttpResponseRedirect(reverse('auctions:index')) else: return HttpResponseRedirect(reverse('auctions:create')) In the template, doing {{ form.fieldname }} renders the form field correctly. However, if I submit a value for this field that passes html validation but doesn't pass is_valid(), the error message doesn't render in the template even though I put {{ form.fieldname.errors }}. What am I doing wrong? -
Django: Values list for a many to many relation
I'd like to know why I cannot get the item names in the same order as they are presented in the QuerySet when using values_list. print(self.prd_obj.basket.values_list()) <QuerySet [(2, 27, Decimal('20.00')), (1, 23, Decimal('12.50')), (3, 28, Decimal('15.00'))]> (above is understood as id 2 item on a ManyToMany list, this item in turn refers to id 27 on a global items list. On the global item list, id 27 is Honda that costs 20, id 28 is Mazda that costs 15 and id 23 is Ford that costs 12.50) The same order re-appear when I ask for price, as below. print(self.prd_obj.basket.values_list('price')) <QuerySet [(Decimal('20.00'),), (Decimal('12.50'),), (Decimal('15.00'),)]> However, when asking for brand (through the items field) the order is not the same. Later when re-assembly the values, Honda now costs 15, Mazda 12.50, and Ford 20.00 print(self.prd_obj.basket.values_list('items__brand')) <QuerySet [('Ford',), ('Mazda',), ('Honda',)]> This is the Model for the basket, I refer to this as a ManyToMany field as I needed a model to connect Item with a price. class ShoppingBasketItem(models.Model): items = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=5, blank=True, null=True) Why is it happening and is there a better way to refer to item and its price within a "shopping basket"? -
Check which model is the current user an instance of in Django
The Employee model in my Django project has a OneToOneField relationship with the built-in Django User model. I have then further inherited this Employee model into two different Manager and Associate models. Now, when a user logs in, I want to check if this user is a Manager or an Associate in my HTML template so that I can display different options, depending on whether they are a Manager or an Associate. What is the best way to that? Models.py- GENDER = [('male','Male'),('female','Female')] class Employee(models.Model): user_def = models.OneToOneField(User,on_delete=models.CASCADE,null=True) name = models.CharField(max_length = 50) age = models.IntegerField() gender = models.CharField(max_length = 10,choices = GENDER) def __str__(self): return self.name class Manager(Employee): dept = models.CharField(max_length = 50) def __str__(self): return super().__str__() class Associate(Employee): reports_to = models.ForeignKey(Manager,on_delete=models.CASCADE) def __str__(self): return super().__str__() -
I am trying to display added items to my cart page. But when I render my cart page I get attribute error at /cart/
This is a portion of my cart.js file function updateUserOrder(productId, action){ console.log('User is logged in, sending data..') var url = '/update_item/' fetch(url, { method: 'Post', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId': productId, 'action':action}) }) .then((response)=>{ return response.json() }) .then((data)=>{ console.log('data:', data) }) } This is a function in my 'views.py' file. def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context={'items': items, 'order':order} return render(request, 'store/cart.html', context) I am getting this error. I would appreciate it if someone could help me out here. File "C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'customer' [07/Sep/2020 09:15:43] "GET /cart/ HTTP/1.1" 500 70674 I don't think I even have a "User" object. I don't know where this error came from. -
My Django app passes authentication on localhost, but not on heroku
So I created a simple "social media website" where by using API I GET data from a database and I can also POST to create a social media post after I register and log in. On my localhost it all works well. I can register, login, then write a social media post and it displays on the screen. However, when I use Heroku, GET API works fine, but after I log in (and I am sure I am logged in as I can log in on admin), I cannot write anything on my website. In my IDE I get: Forbidden: /api/posts/action/ In the network page I can see this: Request URL: http://localhost:8000/api/posts/action/ Request Method: POST Status Code: 403 Forbidden Remote Address: 127.0.0.1:8000 Referrer Policy: no-referrer-when-downgrade Any idea where should I look for an error? If there is any code I should send, let me know. Thank you!