Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I raise HttpResponseForbidden in CreateAPIView
I tried this in perform_create method: if not user.is_active: return HttpResponseForbidden() But no errors occured, it still responsing 201 -
django rest bad request error M2M
I have two models: Task and Scenario: class Task(models.Model): stakeholder = models.ForeignKey(User, related_name='tasks', blank=True, ) project = models.ForeignKey(Project, related_name='project_tasks' ) title = models.CharField(max_length=50, blank=True, null = True, ) ... class Scenario(models.Model): stakeholder = models.ForeignKey(User, related_name='scenarios', blank=True,) tasks = models.ManyToManyField(Task, blank=True) Their serialzers: class TaskSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Task fields = '__all__' class ScenarioSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True, required=False) class Meta: model = Scenario fields = '__all__' def create(self, validated_data): tasks = validated_data.pop('tasks') instance = Scenario.objects.create(**validated_data) for task_data in tasks: task = Task.objects.get(pk=task_data.get('id')) instance.tasks.add(task) return instance def update(self, instance, validated_data): tasks = validated_data.pop('tasks', []) instance = super().update(instance, alidated_data) for task_data in tasks: task = Task.objects.get(pk=task_data.get('id')) instance.tasks.add(task) return instance And view to perform CRUD operations on both these models: @api_view(['GET', 'POST']) def task_list(request): tasks = [] """ List all tasks, or create a new task. """ if request.method == 'GET': #get all the tasks in aspecific project if request.query_params.get('projectId'): # get a specific project projectId = request.query_params.get('projectId') project = Project.objects.get(id=projectId) tasks = project.project_tasks.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) else: tasks = Task.objects.filter(stakeholder=request.user) serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save(stakeholder=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', … -
IntegrityError: NOT NULL constraint failed: Django formsets with multiple images to a Post
Hi Everyone, I am new to Django. I have a Post model. lets imagine that this post model is of "Famous Criminals". Lets say I want users to write about all criminals from history and around the world. It has class Gagnster(models.Model): user = models.ForeignKey(User, related_name='posts') created_at = models.DateTimeField(auto_now=True) gagnster_name = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) history = models.TextField() gangster_image = models.ImageField() #It has other attributes like "like/dislike" but ignoring them as they are not relavent def save(self, *args, **kwargs): self.slug = slugify(self.gagnster_name) super().save(*args, **kwargs) Now lets imagine that title is of the main guys say "Butch Casidy" or "Bonnie & Clyde". It has a title (their names) slug(for SEO) and a post_image of the main guys Now I have another model "GangMember" this has a list of people who were in their gangs. now this model has the below details class GangMember(models.Model): gagnster = models.ForeignKey(Gagnster, on_delete=models.CASCADE) gangmember_image = models.ImageField(upload_to='images/', blank=True, null=True, default='') gangmember_name = models.CharField(max_length=100, default='') gangmember_description = models.CharField(max_length=250, default='') Now here are my views Views.py @login_required def gagnster_create(request): ImageFormSet = modelformset_factory(GangMember, fields=('gangmember_image', 'gangmember_name', 'gangmember_description'), extra=7) if request.method == "POST": form = GagnsterForm(request.POST or None, request.FILES or None) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() … -
Filtering Foreign Keys in Django 2.0
So I need to filter posts, posted by users, who the user currently logged in is following. Here's my models: class ProfileDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) provider = models.CharField(max_length=20, null=True, blank=True) firstname = models.CharField(max_length=25, null=True, blank=True) lastname = models.CharField(max_length=25, null=True, blank=True) username = models.CharField(max_length=24, null=True, blank=True, unique=True) def __str__(self): return str(self.user) class Posts(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(ProfileDetails, on_delete=models.CASCADE, null=True) text = models.TextField(max_length=280, null=True, blank=True) video = models.CharField(max_length=24, null=True, blank=True) timestamp = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return str(self.user) class Connection(models.Model): follower = models.ForeignKey(ProfileDetails, related_name='follower', on_delete=models.SET_NULL, null=True) following = models.ForeignKey(ProfileDetails, related_name='following', on_delete=models.SET_NULL, null=True) # follower = models.ManyToManyField(ProfileDetails, related_name='follower') # following = models.ManyToManyField(ProfileDetails, related_name='following') date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.follower) And then in my views, my bit of Python / Django knowledge kind of directed me to write something like this (take a look particularly at the last bit, where I try to filter it so it only gets details from the users I follow. if ProfileDetails.objects.filter(user=checkuser): print("user previously logged in") sns = get_object_or_404(SocialAccount, user=checkuser) autoupdateprofile = get_object_or_404(ProfileDetails, user=checkuser) autoupdateprofile.lastlogin = datetime.datetime.now() autoupdateprofile.save(update_fields=["lastlogin"]) # print(sns.provider) details = get_object_or_404(ProfileDetails, user=checkuser) videos = Posts.objects.filter(media=True, imade=True).order_by("-timestamp")[0:6] followercount = Connection.objects.filter(follower=details).count() follows = Connection.objects.filter(follower=details) followerposts = Posts.objects.filter(user=follows) for a in followerposts: … -
How can I delete data is checked in checkbox?
I want to delete data is checked in checkbox.I wrote in html <div id="now"> <form action="/app/delete" method="POST"> {% for item in data %} <div class="left"> <input type="checkbox"> <p>{{ item.name }}</p> <p>{{ item.email }}</p> </div> {% endfor %} <button type="submit">SUBMIT</button> </form> </div> in views.py @csrf_exempt def done(request): delete_ids = request.POST.getlist('delete_ids') print(delete_ids) if delete_ids: Data.objects.filter(id__in=delete_ids).delete() return render(request, 'top.html') My ideal system is when I check checkbox of items and put SUBMIT button, done method is called, and checked data is deleted.But when I check checkbox and put SUBMIT button, nothing happens.print(delete_ids) shows empty list like [],so I think checked data cannot be gotten.How can I send checked data to Django?What is wrong in my codes? -
Create multiple related objects in Django Admin
I am using Django 2.0 I have two models class Chapter(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE) class META: verbose_name_plural = 'chapters' db_table = 'chapters' def __str__(self): return self.name class ChapterQuestion(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) word = models.CharField(max_length=250) definition = models.CharField(max_length=250) class META: verbose_name_plural = 'chapter questions' db_table = 'chapter_questions' def __str__(self): return self.word Since Each ChapterQuestion belongs to only one Chapter, I think it could be Many-to-one relation. My admin.py contain only admin.site.register(Chapter) admin.site.register(ChapterQuestion) I want to be able to add/edit multiple questions while creating/editing chapter using Django Admin. But Django Admin is showing only chapter fields Also, I want created_by column to be field automatically by logged in user and remove from form. -
Python and django user authentification link
i have a django web application and a python desktop application i want to login to python desktop applocation with users and password that was available on django web application anyone has an idée to link auth_user django table and to authenticate with user/password of my django application python desktop applocation -
Django - .save() not saving data to DB
I am trying to create a page where a user can select 17 soccer players and save to their profile, using a ModelForm. The form class ProfileForm(ModelForm): class Meta: model = Profile fields = ['GK1', 'GK2', 'DF1', 'DF2', 'DF3', 'DF4', 'DF5', 'MF1', 'MF2', 'MF3', 'MF4', 'MF5', 'FW1', 'FW2', 'FW3'] The View def selectteam(request): print('request.post=', request.POST) print(request.user) if request.method == "POST": form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): print("form confirmed valid") #let me know that the data is valid form.user = request.user #set the user's data we are changing form.save() #save the form to db for x in form.cleaned_data: #check what the data is??? print(x) return redirect('/accounts/profile/selectteam') else: print(form.errors) form = ProfileForm() else: selectedplayers = Player.objects.all() # if not, you need an empty form for GET request form = ProfileForm() context = {'selectedplayers': selectedplayers, 'form': form} return render(request, 'selectteam.html', context) For the life of me, I cannot get the data to actually submit. Here's the console output: [28/Apr/2018 10:27:33] "GET /static/images/pitch.png HTTP/1.1" 200 40216 request.post= <QueryDict: {'MF1': ['301'], 'MF2': ['301'], 'GK1': ['301'], 'DF5': ['301'], 'FW1': ['301'], 'DF1': ['301'], 'MF3': ['301'], 'FW2': ['301'], 'GK2': ['301'], 'MF5': ['301'], 'csrfmiddlewaretoken': ['RtvpMLuPVXaupYNzJdt1yvuJsOhfouH51FUQw73IRzUnKqZRLkzcNHWvoMFyVX4N'], 'DF4': ['301'], 'DF3': ['301'], 'DF2': ['301'], 'FW3': ['301'], 'MF4': ['301']}> request.method= POST Johnny form … -
Configure Django's test debugging to print shorter paths.
I'm not sure how to approach this, whether it's a Django, Python, or even Terminal solution that I can tweak. The thing is I'm learning Django following a book (reference here, really like it), and whenever I run the tests, I get really long output in the terminal for debugging matters. Obviously there's many traceback functions that get called after another, but what started bugging me is that the file paths are very long and they all have the same project folder... which is long by itself, and then it adds all the virtualenv stuff like this: Traceback (most recent call last): File "home/user/code/projects/type_of_projects_like_hobby/my_project_application/this_django_version/virtualenv/lib/python3.6/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) Since the paths take two or more lines, I can't focus on what functions I should be looking at clearly. I have looked at the verbosity option when calling manage.py test but it doesn't help with the paths. If anyone has an idea on how to ~fix~ go about this issue, it'd be cool. Thanks guys. -
get next and previous object in DetailView in Django
I'm using Django 2.0 and UUID for primary key. I'm using DetailView to get detail of particular record. class ChapterDetail(DetailView): template_name = 'courses/chapter/chapter_detail.html' model = Chapter I want two buttons to in the template to navigate to next and previous chapter If I would be using Auto Increment Integer value for primary key, I would have generated next link by increment current object pk and previous link by decrement current object pk. But how to get neighboring objects in this case? -
Render returned string in django template
I have been working a lot with Django's template language lately, and it works well in most cases, but recently I've come across a small problem it hasn't been able to solve. I'm iterating over a bunch of database objects, and building a button in the template from each of them. Something like this: {% for item in items %} <button id="{{ item.action.id }}"> {{ item.action.text }} </button> {% endfor %} This works fine, but my Action class is inheritable, and may have a different button structure. Say I wanted to sometimes have a javascript function attached as well. My first though was well, let's just create a render method in my class, and then call that in my template. class ScriptAction(Action): def render(self): return ''' <button id="{}" onclick={}> {} </button>'''.format(self.id, self.func, self.text) Because no the template is much more elegant, and doesn't rely on a fixed button structure: {% for item in items %} {{ item.action.render|safe }} {% endfor %} And now for my actual problem: what if this rendered string needs further processing by django? Maybe render method returns a string like <button id="action-button-id" onclick="console.log('clicked')"> {{ item.name }} </button> Currently, {{ item.name }} will not be rendered in … -
'WSGIRequest' object has no attribute 'session' and 'user'
enter image description here my project middle setting is blew,and i have check request as above picture ,it's really don't have user and session in request ,i don't know where is problem,have anybody give me some suggest ? MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
django: get_language() in JavaScriptCataLog do not return the page displayed one
As in my case, I want to translate strings within a js script. Basically I can made it work. I found that what the 'jsi18n' view returned depends on the preferred language of my chrome browser. If I set the preferred language to Chinese(Simplified), everything goes fine. But if I change the most preferred language to English, the 'jsi18n' view will return empty catalog array. I figured out that the controlling variables is 'request.LANGUAGE_CODE'. This is done by a test view: def test_language(request): res = ""; res += "translation.get_languages = %s<br>"%(translation.get_language(),) res += "request.LANGUAGE_CODE = %s<br>"%(request.LANGUAGE_CODE,) res += "get_language() = %s<br>"%(get_language(),) return HttpResponse(res); The result of above code will be consistent with my browser settings. So is there any way to control the request content(LANGUAGE_CODE or anything relevant) sent by browser? -
How to handle the download response receive from server in javascript
I try to send a download request to the server using ajax, and then the backend confirms that the current user has permission to download the current file and decides whether to send an error message or download the file to the browser. However, browsers can only handle error messages but cannot process download response, I have no ideal to solve this problem this the ajax code: <script type="text/javascript"> function fdownload(file_pk){ $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ url:"{% url 'file_download' %}", type:"POST", data:{"file_pk":file_pk}, success:function(error_message){ if(error_message == "true"){ $.Pop('you have no permission to download this file!',{Animation:'showSweetAlert'}); } else{ ....... } }, }); } this is backend code: def download_util(download_file): file=open(download_file.file.path,'rb') response =FileResponse(file) response['Content-Type']='application/octet-stream' response['Content- Disposition']='attachment;filename='+"".join(download_file.file.name.split('/')[-1:]).encode('utf-8').decode('ISO-8859-1') return response def file_download(request): file_pk = request.POST["file_pk"] download_file = get_object_or_404(models.Download_file,pk = file_pk) user_group = [] file_group = [] if request.user.is_authenticated: for e in get_object_or_404(User,username = request.user).groups.all(): user_group.append(e.name) for e in download_file.download_permission.all(): file_group.append(e.name) if 'anyone' in file_group or list_in(user_group,file_group): return download_util(download_file) else: return HttpResponse('true') -
chart.js not working in browser with django. no error for template and static folder setting
I have created view to render simple HTML page which uses bootstrap and chart.js bootstrap working properly but chart is not getting displayed. there is not error in code. no error regarding Staticfile and Directory setup. However, Chart is not displaying in page. is there any prerequisite for chart.js or it does not work with Django. -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
I'm trying to make MongoDB and Django get on with each other the way I want them to. That's the error I'm getting when trying to import viewsets from rest_framework_mongoengine. The whole error looks like this: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. It doesn't find settings.py or what? If so I can't figure out why! Namely, say, why did this problem not appear with other modules then? Here are my INSTALLED APPS INSTALLED_APPS = [ 'rest_framework', 'rest_framework_mongoengine', 'mongoengine.django.mongo_auth', 'rest_framework.authtoken', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'core', 'core.essences.user', 'core.essences.user.authentication', 'core.essences.test_result', ] -
Why is data missing in request.POST dict on form submit
On form submit I get the csrf_token and quantity in the request.POST, but not the tickets checkbox. I have a lot more checkboxes but omitted them from the example. Do I need to add the values to input elements under the submit tag with JS? <form id="tour-form" role="form" class="tour-form clearfix" method="post" action="{% url 'tour:add-to-cart' tour_id=tour.pk slug=tour.get_slug %}" novalidate> {% csrf_token %} <strong>You are booking</strong> <span>{{tour.name}}</span> <ul> <li> <label class="custom-check" for="tour-form-tickets"> <input type="checkbox" id="tour-form-tickets" name="tickets" value="1" price="{{tranport_prices_total|floatformat:'0'}}"/> <i></i> <strong>Corresponding airplane packages</strong> - <span>{{tranport_prices_total|floatformat:"0"}} €</span> </label> </li> </ul> <span class="total-box"> Total <span>0 &euro;</span> </span> <input type="submit" value="order tour"/> <input type="hidden" name="quantity" value="1" /> </form> -
Removing model name from queryset in template
I am trying to display records from my model called Standard. The result in django comes in a list, but everytime i try to display it in template using the following code: {% if standard %} {{ standard }}<br> {% endif %} It displays Standards<QuerySet ['LKG', 'UKG', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']> I have tried converting to list, also using values_list. standard = Standard.objects.all().values_list('class_name',flat=True) How do i remove the Standards part from the response? -
Django AJAX delete request using the fetch api
I am trying to send an AJAX delete request using the fetch api: let data = new FormData(); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); fetch('', { method: 'DELETE', body: data, credentials: 'same-origin', }) It gives me the CSRF token missing or incorrect error. If I, however, change the method to 'POST', it works completely fine. I remember having the same issue sending AJAX requests with jQuery, which I solved by setting the request header X-CSRFToken to the csrf_token variable. However, if I try the same approach with the fetch: let data = new FormData(); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); fetch('', { method: 'DELETE', headers: { "X-CSRF-Token": '{{ csrf_token }}' }, body: data, credentials: 'same-origin', }) It doesn't fix it. Appreciate your suggestions! -
Between React and Angular5, which one is best for Django?
I want to know which frontend framework fit best for Django projects, any response will be appreciated, Thanks. -
Django-case insensitive string comparison in django template
How to do case insensitive string comparison? In my case , i need to add a class menu_active when topic.title equals page.slug. but,now topic.title= home page.slug = Home so my condition fails nav_bar.html {% for topic in landing_pages %} <li role="presentation"> <a class="{% if topic.title == page.slug %}menu_active{% endif %}" href="/{{topic.slug}}/">{{topic.title}}</a> </li> {% endfor %} -
what is mean 'Request object has no attribute "accepted_renderer" '?
Request object has no attribute "accepted_renderer" These messages were in my log. There was error encountered while processing this event. Discarded invalid value for parameter 'timestamp' Expand -
Importing models from one project into another (gives RuntimeError)
How do I import certain models from one project in one directory, into another project in another directory? Both projects share the same database. My directory structure is like this: root directory1 project1 app1_of_project1 models.py ... manage.py directory2 project2 app1_of_project2 models.py ... manage.py App1_of_project2 needs some models from app1_of_project1. I tried this answer, but I get: RuntimeError: Model class app1_of_project1.models.Model1 doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. INSTALLED_APPS of project1 has app1_of_project1 included, and INSTALLED_APPS of project2 has app1_of_project2 included. This answer gives me a ModuleNotFoundError. I cannot merge the two projects and make them separate apps within one project. Also, I do not want to move the project directory to PYTHON_PATH. Can anyone suggest a workaround? Thanks! -
How to use mongoengine with django REST framework
I want to use a mongodb database together with the django REST framework. But I am very confused how to connect mongo db with django. Here is my settings.py - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy', } } models.py - from mongoengine import * connect( db='test', username='', password='', host='localhost' ) class User(Document): email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50) versions - Django==2.0.4 django-mongodb-engine==0.6.0 djangorestframework==3.8.2 mongoengine==0.15.0 pymongo==3.6.1 It returns django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
Django REST Framework forces me to submit values
I am trying to save an instance using AngularJS 1.6.5 and DRF(Django REST Framework). The problem is that I am not able to understand why DRF is trying to force me to submit the values that aren't required. Here is my models.py:- class Course_Module(models.Model): part_of = models.ForeignKey(Course, related_name='modules') name = models.CharField(max_length=200) video = models.FileField( upload_to=content_videofile_name, blank=True, null=True ) Presentation = models.FileField( upload_to=content_pptfile_name, blank=True, null=True ) Assignment = models.FileField( upload_to=content_assignmentfile_name, blank=True, null=True ) topics = models.TextField(blank=True, null=True) def __unicode__(self): return self.name As you can see that the fields video, Presentation, and Assignment can be null or blank in the above model. Here is the serializer for this model that I am using:- class Course_ModuleSerializer(serializers.HyperlinkedModelSerializer): video = serializers.FileField(max_length=None, use_url=True, required=False) class Meta: model = Course_Module fields = ('id', 'url', 'part_of', 'name', 'video', 'Presentation', 'Assignment', 'topics') Now the viewset to handle the above serializer:- class Course_ModuleViewSet(viewsets.ModelViewSet): queryset = Course_Module.objects.all() serializer_class = Course_ModuleSerializer Now comes the frontend part:- Here is the template form that I have created to make the $http.post method:- <form class="form-horizontal"> <div class="form-group"> <label class="control-label col-sm-2" for="name">Module Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" placeholder="Module Name" name="module_name" ng-model="new_module_name" ng-required="true"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="new_ass">Assignment:</label> <div class="col-sm-10"> <input type="file" …