Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: Got AttributeError when attempting to get a value for field `images` on serializer `ArticleViewSerializer
What i am trying to do is create a serializer to post multiple images for an article as ArrayField(ImageField()) does not work. I have checked if there is any typo or so but it seems like there is no typo.Serializers work fine separately,only i get this problem where i try to combine them. Here are the codes: Here is the serializers.py class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(many=True) class Meta: model = Article fields = ('id',''images','author') def create(self, validated_data): images_data = validated_data.pop('images') article = Article.objects.create(**validated_data) for image_data in images_data: ArticleImages.objects.create(article=article, **image_data) return article Here is the views.py class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) … -
How can I get custom form field value from within Django Admin's response_change?
I've added a custom functionality to a model by overriding change_form.html. Basically, I'm letting users change the objects of a model if these changes were approaved by the admin. I added two buttons, named accept-suggestion and decline-suggestion and I intend to handle the custom functionality through response_change method: def response_change(self, request, obj): if "decline-suggestion" in request.POST: # do stuff... if "accept-suggestion" in request.POST: # do stuff... Both buttons will send an e-mail to the user saying if the suggestion was declined or approaved. So far so good. The problem is that I want to add the possibility to the admin write a brief justification explaininig why the suggestion was declined. So I changed change_form.html again. <div class="submit-row"> <div class="float-left"> <a class="decline-button-outlined accordion" type="button" href="#">DECLINE SUGGESTION</a> </div> <div class="float-right"> <input class="accept-button" type="submit" name="accept-suggestion" value="ACEITAR SUGESTÃO"> </div> </div> <div class="additional-infos"> <fieldset class="module aligned"> <div class="form-row"> <label for="decline-reasons">Reasons for rejection:</label> <textarea placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion" id="decline-reasons" class="vLargeTextField" rows="5"></textarea> </div> <div class="submit-row"> <div class="float-right"> <input class="decline-button" type="submit" name="decline-suggestion" value="DECLINE"> </div> </div> </fieldset> </div> This is the best approach? If yes, how can I get the value of the <textarea> above from … -
How to solve CSRF "Forbidden Cookie not set" error in Django?
I am using Angular 8 as frontend and Django 1.11.18 as backend. I am running my Angular project on https://127.0.0.1:4200 through command ng server --ssl true and Django API's are deployed on a separate redhat server and can be accessed through https://192.xxx.x.xx:7002/ My Login is a GET Request that returns success response with csrf token in header but cookies are not received on the browser at that time and when I call my POST request this cause "Forbidden" error due to CSRF Token. Middleware in my settings.py is: MIDDLEWARE = [ 'Common.customMiddleware.ProcessRequest', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have also added: CSRF_TRUSTED_ORIGINS = ["127.0.0.1","192.xxx.x.xx"] but still cookies are not received on the browser Any kind of help will be appreciated. One thing more I would like to mention is that When I deploy the Angular project on the same server on which Django API's are applied then application works fine. -
Disable lint on single line within django template in vs code
Given this html <div class="img-background" style="background-image: url({% static '/img/information_juniors.jpg' %});"> <div class="content"> <h5>Juniors</h5> <p>{{ page.juniors }}</p> </div> </div> Is it possible to disable linting on the single line containing the django tag in VS Code? It is bringing up these errors ) expected css-rparentexpected semi-colon expected css-semicolonexpected at-rule or selector expected css-ruleorselectorexpected at-rule or selector expected css-ruleorselectorexpected I have this for my args, but I can't find any info on linting and django templates "python.linting.pylintArgs": [ "--load-plugins=pylint_django", "--disable=C0111", // missing docstring ] -
Django __exact queryset filter - case sensitivity not working as expected
I am trying to filter a Django queryset where the case should be sensitive, although I am not getting the results I expect from the "__exact" filter, which I believe to be case-sensitive: https://docs.djangoproject.com/en/3.0/ref/models/querysets/ My code looks like this: lower_case_test = MyObject.objects.filter(name_exact="d") for item in lower_case_test: print("item.name: ", item.name) I have 2 in the "MyObject" model, one with name "d" and one with name "D". The output of the above code is: (u'item: ', u'D') (u'item: ', u'd') Can anyone suggest what might be the issue here? Thanks in advance. -
My Post Request is not giving the response i want for NestedSerializers
I am trying to get multiple images throughout POST request but i am having an issue,here are my codes. Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') images = models.ManyToManyField('Article',symmetrical=False,through='ArticleImages',related_name='fodssfsdmaers', blank=True,) class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True) Serializers.py class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True,read_only=False) class Meta: model = Article fields = ('id',''images','author') def create(self, validated_data): return Article.objects.create(**validated_data) Here is the issue ,the images are not processed throughout the post request so I cannot see any data related to images. { "id": "74e708b1-d045-45b5-8957-d0ac3df6b6d7", "author": "4e9ae720-e823-4e2f-83b3-144573257d73", } Does anybody know why i am facing this issue? -
Problem in Django after Ajax post request
I want django to render my maps.html.Then I click on the google map,ajax send post request with coordinate data and I render other html file with answer.Answer is result of my function which named Get_Answer.It's located in Data_Analysis module.Get_Answer(lng,lat) takes about 3-4 second to get answer and it gets two parameters.I did ajax post request,I see that django render(maps.html) ,when I click on the map,I see that django understand that it's post request and ajax request ,but django doesn't render other html file (answer.html).I don't know why? But I can print result of my function and I see result in the console.My views.py file How can I force Django execute return render(request,'answer.html','form':Data_Analysis.Get_Answer(lng,lat)) or find other way to do what I want. -
How to query database based on user inputs and show results in another page?
Good day everyone. I am trying to build a form which queries the database based on user data inputs and then returns the results in a new page. but I don't know exactly how to do it and I am getting errors. I've looked for a solution but couldn't find any. Please help me if you know any solutions. Thanks in advance. Here are my codes: forms.py class AttendanceForm(forms.Form): course = forms.CharField(max_length=50) department = forms.CharField(max_length=10) semester = forms.IntegerField() views.py class AttendanceForm(generic.FormView): form_class = CrsAttForm template_name = 'office/crsatt_form.html' success_url = reverse_lazy('office:members_list') class MembersList(generic.ListView): template_name = "office/crs_att.html" context_object_name = 'members' def get_queryset(self): return Members.objects.all() # I know I should use .filter method but how could I set the parameters to data received from the form urls.py url(r'^CourseAttendanceForm/$', views.AttendanceForm.as_view(), name='courseattendance'), url(r'^CourseAttendanceForm/Results/$',views.MembersList.as_view(), name='memebrs_list'), -
Django OAuth Toolkit: Custom user : Error: Request is missing username parameter
I am using a custom django user model i have also specified the AUTH_USER_MODEL in settings.py file. My model doesnot contain any field named 'Username'. still encountering an error : {"error":"invalid_request","error_description":"Request is missing username parameter."} when sending post request to http://127.0.0.1:8000/o/token -
I want to add comment functionality in my blog site and i want to save that comment with article name and the user also with the help of "foreign key"
basically i want a comment box where in database i can check for which article this comment is for and in front end in want a comment in which behind every comment there is a username showing models.py class comments(models.Model): user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) article = models.ForeignKey(article, null=True, on_delete=models.CASCADE) comment = models.TextField(max_length=255) timedate = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.comment form <form action="." method="post"> {% csrf_token %} <div class="form-group" style="margin: 10px;"> <textarea class="form-control" name="comment" id="exampleFormControlTextarea1" rows="3" placeholder="Write your feedback"style="margin-bootom: 10px;"></textarea> <button class="btn btn-info">Comment</button> </div> </form> view.py def readfull(request, slug): fullarticle = article.objects.get(slug= slug) if request.method == 'POST': comment = request.POST.get('comment') if MyUser.is_authenticated: feedback = comments(comment = comment) instance = feedback instance.user = request.user instance.save() print('comment saved') return redirect(request, 'readfull',slug=fullarticle.slug) else: print("none") return render(request, 'full.html', {'fullarticle':fullarticle}) -
How to iterate through self made dictionary and access its attributes in DJANGO templates.?
I am getting a Dictionary from the ajax Base function {'Name': 'Dawn Bread Milky', 'Pricse': 60, 'Barcode': 11111, 'Quantity': 2, 'Total_pricse': 120} I send it to an template using genrate_bill = {"Order_ID":Bill_Genrated.id, 'Khaata':is_Khaata,'CustomerName':is_Khaata.name, 'Bill': Bill_Genrated, 'CartList':cart[0], ## Here is an dict i send 'SubTotal':total_amount, 'Discount':0, 'TotalPricse':total_amount } Problem is that how can I access it KeyVallues Like in Django template {% for item in CartList %} <tr> <td>{{item.Name}}</td> <td class="text-center">Rs.{{item.Pricse}}</td> <td class="text-center">{{item.Quantity}}</td> <td class="text-right">Rs.{{item.Total_pricse}}</td> </tr> {% endfor %} It not showing any result -
Removing an object from database and the DOM via AJAX
So I have this simple AJAX post request that is deleting the object from the Model as I want it to but I am struggling to delete it from the DOM correctly. function removeFriend(id){ let dataId = `${id}` $.ajax({ type: 'POST', url: `/delete/friend`, data: { friend_id: `${id}`, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function(json){ let tbody = document.querySelector('tbody'); let row = tbody.querySelector('tr[data-id=dataId]'); console.log(row); row.remove(); alert('friend has been deleted') }, error: function(xhr, errmsg, err) { console.log(error) } }) } I keep getting index.js:119 Uncaught TypeError: Cannot read property 'remove' of null and the console.log(row) is showing up as null. I have tried let row = tbody.querySelector('tr[data-id=`${id}`]'); and same result. I have tried let row = tbody.querySelectorAll('tr[data-id=dataId]'); but then the output for console.log(row) is an empty NodeList NodeList [] followed by index.js:119 Uncaught TypeError: row.remove is not a function. This is what my table looks like: <table class="table table-striped table-sm" id="my_friends"> <thead> <tr> <th>Nick name</th> <th>First name</th> <th>Last name</th> <th>Likes</th> <th>DOB</th> <th>lives in</th> <th>Remove friend</th> </tr> </thead> <tbody> {% for friend in friends %} <tr data-id="{{ friend.id }}"> <td>{{friend.nick_name}}</td> <td>{{friend.first_name}}</td> <td>{{friend.last_name}}</td> <td>{{friend.likes}}</td> <td>{{friend.dob | date:"Y-m-d"}}</td> <td>{{friend.lives_in}}</td> <td><button type="button" class="remove-friend" name="remove-friend" value="{{ friend.id }}">Remove</button></td> </tr> {% endfor %} </tbody> </table> I know I … -
Accessing django model attribute passed as a parameter
I'm using django with a legacy database where I can not change the original table columns. I have similar models which have slightly varying field names. The following model is an example. class EURegister(models.Model): record_id = models.AutoField(primary_key=True) reg_no = models.CharField(max_length=45, blank=True, null=True) company_name = models.CharField(max_length=300, blank=True, null=True) In some models, reg_no is a different name such as registration_id. Hence, I have to access the model attribute passed as an argument. But I can not use it since the model doesn't allow to use attributes as they were dict keys. It gives the following error. TypeError: 'EURegister' object is not subscriptable -
Django Dynamic initial values for current user
I want the current user to be able to upload a file in my html page. I try a method but it didn't work. I have an error message :"File.userFile" must be a "Customer" instance Thanks in advance! Here's my code models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.user.username class File(models.Model): userFile = models.ForeignKey(Customer, on_delete=models.CASCADE) document = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.document forms.py class FichierUpload(ModelForm): class Meta: model = File fields = '__all__' exclude = ['userFile'] views.py def my_view(request, **kwargs): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' # Handle file upload current_user= request.user.username #fileuser = Customer.objects.get(user=current_user) form = FichierUpload(request.POST or None, request.FILES) if request.method == 'POST': # if form.is_valid(): file = form.save(commit=False) file.userFile = request.user file.save() # Redirect to the document list after POST return redirect('my-view') # else: # message = 'The form is not valid. Fix the following error:' else: form = FichierUpload() # An empty, unbound form # Load documents for the list page documents = File.objects.filter(userFile__name=current_user).order_by('-uploaded_at') # Render … -
Django dynamic form subclass list
I'm trying to understand how can I define model as a class containing 2 integers and 1 charfield and then make it a part of another model. Example of data I need I guess in object oriented programming I should define model class like this: class Component(models.Model): pipe_type = models.CharField(max_length=200) length = models.IntegerField() amount = models.IntegerField() And then I don't know how can I use it with django models, it should be something like this: class Item(models.Model): name = models.CharField() components_needed = ? LIST OF Component class ? Also, since components needed size will wary for objects, it should be possible to extend it's size with button on a page, for example there could be 3 input fields and next to them would be "+" and "-" button to add/remove another set of 3 input fields I spent entire day looking for solution, but at this point I'm not sure if django can handle this. I'm new to python and django, so there are many things I do not understand. I will be grateful for any kind of help -
How can I nest one Django form within another?
I want to nest one of my forms - AddressForm, in a few different forms, without having to re-add all the fields to each form. I want to do this without relying on models, which is what Djangos inline form seems to do. I tried adding the address form as a field in the parent form, which renders correctly, but doesnt get returned when the form is cleaned. -
Building a Fantasy Football App. If player name is not in JSON data file, set score to zero. Sounds simple, but how do I get it to work?
I'm building a very simple fantasy football web-app using django for a course. One bug I discovered recently was that if a player isn't present in the JSON data that I'm pulling from an api, then it throws an error stating that the local variable for that player's score is being referenced before being assigned. Makes sense given that there is no actual data for that player. So, to fix this, I figured all I needed to do is add an elif (or else) statement to my logic to set that player's score to zero. Here's my code for this so far. for score in scores: if score['player_name'] in QBname: QBscore = float(score['points']) totalpoints.append(QBscore) I'm looping through a list called "scores" where I have the player scores coming in from an api call, then I'm comparing the player's name, which is stored in a variable called "QBname", to score['player_name]. Obviously, if score['player_name'] is a match and is in "QBname", I'm then appending that player's score to the variable "totalpoints." Now, to "fix" the problem, and assign a score of 0 to an absent player, I thought I would need something like this... if score['player_name'] in QBname: QBscore = float(score['points']) totalpoints.append(QBscore) … -
Error in passing filtered data to template. Reverse not found. 1 pattern(s) tried. What query should be used to avoid this error?
I am trying to create a dynamic url that displays all the sub-courses in course. To do this I am passing the course name through the url and filtering the sub-courses to only send the ones for this course. However I cannot seem to find the correct query to filter and pass the data. I attempted to follow the official Django documentation and search stack to find an answer but found nothing. My experimentation has also gotten me no results. the view is def subcourse(request, course): if request.method == 'GET': course = Course.objects.get(slug=course) subcourses = Subcourse.objects.all().filter(course=course) context = {'subcourses': subcourses} return render(request, 'subcourse.html', context) and my models are: class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) thumbnail = models.ImageField( upload_to='images/courses', null=True, blank=True ) position = models.IntegerField() def __str__(self): return self.title class Subcourse(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) thumbnail = models.ImageField( upload_to='images/subcourses', null=True, blank=True) position = models.IntegerField() def __str__(self): return self.title and the current error message is Reverse for 'subcourse' with arguments '('',)' not found. 1 pattern(s) tried: ['training/(?P<course>[-a-zA-Z0-9_]+)$'] I have read through the documentation regarding queries and filters but cannot seem to find my error. -
Django avatar images broken
I'm trying to learn django and was following this tutorial: https://django-avatar2.readthedocs.io/en/latest/ I can upload an image and it shows up in myproject/avatars/admin/ as it should, but when I go to the html page, the image appears broken. in u.html I have: {% load avatar_tags %} {% avatar user 150 %} In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'avatar', 'boards', In urls.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^admin/', admin.site.urls), url(r'^u/(?P<username>[\w.@+-]+)/$', views.u, name='u'), url('avatar/', include('avatar.urls')), ] When I upload the avatar or go to my profile page the image is broken. Change page Direct address to image -
Django RestFrameWork Security
How can I protect my endpoints? Currently, I'm working on a project but I don't know how to secure the API URLs. How can I prevent the user from login through the rest framework (backend using the API URL)? I'm currently using IsAuthenticated but still, it gives a prompt to enter username and password which I want to prevent. -
How to get querysets which "has" value on the lists?
I'm not sure my title is precise question I wanna ask if i have list like [2, 3, 4] Then i wanna get querysets which has list of value!! 'in' is simillar with my question but kinda different. (https://docs.djangoproject.com/en/dev/topics/db/queries/#the-pk-lookup-shortcut) For example, Blog.objects.filter(pk__in=[1,4,7]) then it will return queryset which has 1 and 4 and 7. I wanna get queryset has 1 or 4 or 7 !! Somebody help me :( class UniversityViewSet(generics.ListAPIView): """ View Set of University Model """ queryset = University.objects.all() serializer_class = UniversitySerializer filter_class = UniversityFilter def get_queryset(self): queryset = University.objects.all() topiks = self.request.query_params.get("topiks", None) if topiks is not None: topik_coverage = topiks.split(",") for topik in topik_coverage: queryset = queryset.filter( tuitions__requirement_topik__in=topik_coverage <=== HERE!!!!! ) return queryset else: return queryset -
Django admin - Allow deletion only for users in a specific group for all models
I want to allow hard deletion in the Django administration site only for members of a specific group. To achieve this, I could create a mixin where I override has_delete_permission and get_actions to check if the user is a member of the group. Then, I could use it in all admin classes. However, I have a lot of admin classes and I don't want to update all of them and to always think about adding this mixin every time I create a new one. Is there a better way to achieve the same? -
What is the best text to Html formatter to use for my Django project
I am currently using markdown but I don't like the way my code's are being formatted. Is there a better text formatter that can give my code snippets a nice look..?? -
sockjs.js?9be2:689 Uncaught Error: SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS
I am deploying Vue + Django app in Heroku but Django is working well coming to the vuejs it is displaying the above error. What I need to change in the place of "http://127.0.0.1:8080". Actually, Django templates are working well but coming to the Vue js files it is not displaying and I got the following error Uncaught Error: SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS at new SockJS (sockjs.js?9be2:689) at new SockJSClient (SockJSClient.js?0a33:43) at initSocket (socket.js?e29c:20) at Object.eval (client?7017:176) at eval (index.js?http://127.0.0.1:8080&sockPath=/sockjs-node:177) at Object../node_modules/webpack-dev-server/client/index.js?http://127.0.0.1:8080&sockPath=/sockjs-node (bundle.js:9374) at __webpack_require__ (bundle.js:790) at fn (bundle.js:101) at Object.1 (bundle.js:9967) at __webpack_require__ (bundle.js:790) vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" transpileDependencies: ["vuetify"], publicPath: "http://127.0.0.1:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, //uncomment before executing 'npm run build' css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, } }; -
How should i create, save and open user specific checklist data in django?
I need to develop this app using Django. I have given checklist of 25 checks. This checklist is related to PCB designing. The checklist will get updated as PCB passes through different stages. Before sending PCB for manufacturing user has to complete all the checks. To avoid the error in later stages and the cost this checklist has been created. Requirement is, User need to login to the application. After login if he wants to create new project, he should be able to create new project and after creating a new project the checklist should open when he should be able to check and uncheck those 25 checks. Suppose user is working on 5 different PCB designs then he should be able to save those 5 projects individually. After login if he wants to open old project then also, he should be able to open the old project and see how many checks he has completed and how many are remaining? I am new to Django. Before 2 weeks I started learning Django. I already have created user registration and login page and stored user data in postgresql. Now my question is, how should I create or open a new …