Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing data from javascript file and using it in views in Django
I have a javascript file in the static folder (static/app/index.js) to store few values from input fields in an HTML page and perform operations on them. I want to receive data from that js file (for eg. a variable storing an integer) and use it in views. How to achieve this? -
Django Defender in Django Rest Framework
Anyone used Django Defender to prevent bruteforce attack in Django Rest Framework? Django Defender work fine if only login failed on admin page But its not detected Rest Framework Token Authentication failed attempt -
How to save tags of a post with taggit package by calling save_m2m() manually in forms?
Hey guys I am new to django, I have this form and uses the taggit package but the tags are not getting saved while I update. How to properly implement the save_m2m() functionality manually.? I need to do the save function manually since I need to check some fields to another value, so can't use the default one. views form = UpdateForm(self.request.POST or None, instance=post) if form.is_valid(): obj = form.save(commit=False) ... ... obj.save() form.save_m2m() forms.py class UpdateForm(forms.ModelForm): class Meta: model = Post def save(self, commit=True): # Tags doesn't work if activated post = self.instance post.title = self.cleaned_data['title'] ... ... if commit: post.save() return post def save_m2m(self, commit=True): post= self.instance if self.cleaned_data['tags']: post.tags = self.cleaned_data['tags'] post.save() return post If I don't have this save_m2m function here, then if I try to run the update, it shows error, but if I add this function, it doesn't save the tags while updating the rest. Thanks -
Multiple Custom user model authentication using Djangorestframework-simplejwt
I am working on a multitenant application, which I have applied authentication using Djangorestframework-simplejwt. I want to have several custom user models(Staff,Student,Admin) authentication using Djangorestframework-simplejwt. Any ideas on how to implement it will be deeply appreciated -
How can i check content type file uploaded in django?
I want to check type of file that are used in model Django. i do not want to check extension,i want to check content of file. -
anacaonda download in atom text editor
i have downloaded anaconda in my computer then when i try to use conda in my atom text editor i am getting an error like this, can i get a solution ? onda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 conda + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Model that combines all the attributes (which will sometimes be useless) or several small models?
I'm trying to build my first website, a little RP game to play in school. It is a hero who plays an adventure and must make the right decisions. In my program I have a model for each component: hero, NPC, trap, obstacle, closure ... all of which have a generic relation with an Interaction class. It would be simpler for me to have only a global interaction class which includes all the necessary attributes. In each instance it would suffice for me to specify what type of interaction it is and to fill in only the attributes concerned. But then I will end up with instances containing most of the time many empty fields. Is it a problem? Bad practice? Thx ! -
Add same group of fields to django models
I am working on a blog project in django. I have to link multiple posts to a single post. What I am trying to do is something similar to the above picture(Similar to taggit). I have to link multiple post with particular type by adding new set(post_id and type). How can I create a model similar to the above picture? -
How to make a private database for each user in django rest framework
Now I am creating a to-do list web application with django rest framework and React so how can I make for each user a private database including thier own to-do items -
Using short_description as column header when exporting to csv in Django
New to django and have already looked at answers here and here Setting the short_description is what I have got sorted - issue is being able to use it as column headers when exporting the data to csv. This is what I have got within models.py class Person(CustomModel): def get_name(self): return u'Returns some calculations' def get_lang(self): return u'Returns some calculations' get_name.short_description = 'First Name' get_lang.short_description = 'Mother Tongue' Code within utils.py header_data = {} for name in headers: if hasattr(self, name) and hasattr(getattr(self, name), 'short_description'): header_data[name] = getattr(getattr(self, name), 'short_description') else: field = None try: field = self.model._meta.get_field(name) except FieldDoesNotExist: pass if field and field.verbose_name: header_data[name] = field.verbose_name else: header_data[name] = name header_data[name] = header_data[name].title() writer.writerow(header_data) What I am getting in my csv export is get_first get_lang <- header row some data some data instead of First Name Mother Tongue <- header row some data some data -
Django - The current path, didn't match any of these
In my first django project I need to retrieve a team by its name, this is the url config I have: in urls.py router.register(r'team/(?P<name>.+)/$', views.TeamViewSet, basename='teamviewset') in views.py class TeamViewSet(viewsets.ModelViewSet): serializer_class = TeamSerializer def get_queryset(self): name = self.kwargs['name'] queryset = Team.objects.filter(name=name) return(queryset) When I type a team's name in the url this is the answer I'm receiving: The current path, team/Barcelona, didn't match any of these. Thanks in advance for any hint or help -
Swagger is not working with python3.7 and django 1.10
while integrating the swagger for project which has djangorestframework==3.7.7 and django django==1.10.7 and python3.7.5 and followed swagger setup document but it is not functioning correctly. earlier it was working fine with python2.7 and django 1.8 and restframework was djangorestframework==3.1.1 -
Create OneToOne field user object in Django serialization
I am trying to create the User object using my Staff class. My staff model looks like following, class Staff(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return self.user.username My serializer class is here, # create staff serializer class StaffSerializer(serializers.ModelSerializer): class Meta: model = Staff fields = "__all__" def create(self, validated_data): username = validated_data.pop('username') email = validated_data.pop('email') password = validated_data.pop('password') user_instance, created = User.objects.get_or_create( username=username, email=email) if not created: user_instance.set_password(password) staff_instance = Staff.objects.create( **validate_data, user=user_instance) return staff_instance Viewset class, class StaffViewSet(viewsets.ModelViewSet): serializer_class = StaffSerializer queryset = Staff.objects.all() permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): staff = serializer.save() return Response(serializer.data) I tried the post request as below, {"username":"tekson", "email":"tekson@gmail.com", "password":"admin"} But it shows the error { "user": [ "This field is required." ] } I don't know how to create the user object from the staff. Please help me to figure out this error. -
Ajax call to form field to auto-populate other fields
I am using python django and regular html form So i had a very specific situation where I have a form and it builds "Menus" for food programs in the Menus it has meal types: BreakFast, AM snack, lunch, supper etc.. per meal type there are components: grain, veg, fruit, meat, beverage a unitized meal is built up of food items and components. when user chooses unitized meal (component: meat and fruit) how can i construct a way when i choose a unitized meal, it auto populates the Meat and fruit fields of the form, based on the items of the unitized meals.. all my models with many-to-many fields are linked proper i just need to know what kind of way can i approach this. if any additional code is needed please let me know page -
Unexpected behavior of order_insertion_by attribute in django-mptt?
I am creating a CMS, to store the hierarchy of pages I am using django-mptt. Here is the simplified version of the code. from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Post(MPTTModel): title = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ## some columns are omitted def __str__(self): return self.name class MPTTMeta: order_insertion_by = ['title'] The django-mptt documentation states that the order_insertion_by is used to specify the natural ordering of objects. So, if I set order_insertion_by = ['title']. It orders all the posts and child posts in ascending order by title. So far so good. However, If I set order_insertion_by to id, the posts are ordered in descending order by id. Why is that? Debugging the issue also reveals that in the latter case, the following query is executed. SELECT "wiki_post"."id", "wiki_post"."title", "wiki_post"."slug", "wiki_post"."tree_id", "wiki_post"."level" FROM "wiki_post" WHERE NOT ("wiki_post"."post_type" = post) ORDER BY "wiki_post"."tree_id" ASC, "wiki_post"."lft" ASC As you can see, the posts are getting ordered by the tree_id and lft column, not by the id column. Which is what I want. How can I achieve this? -
How to display celery results in a django template?
Here I am crawling the sites implementing the celery. In the spider logs I can see the results from crawling but I am not being unable to display the results in a django template. How can I display the results returned by the celery task in a django template ? celery.py app = Celery('my_project',broker='amqp://localhost', backend='db+sqlite:///results.sqlite', include=['crawler.tasks']) tasks.py from my_project.celery import app @app.task def schedule_task(): running_tasks = Task.objects.filter(status=1) for task in running_tasks: if task.scraping_end_date > timezone.now().date(): settings = { 'spider_count': len(task.targets.all()), 'keywords': task.keywords.all(), 'scraping_end': task.scraping_end_date, 'unique_id': task.unique_id, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } for site_url in task.targets.all(): domain = urlparse(site_url.domain).netloc spider_name = domain.replace('.com', '') task = scrapyd.schedule('default', spider_name, settings=settings, url=site_url.domain, domain=domain, keywords=task.keywords.all()) -
Setting timezone on a DateTime Field based on the location selected - Django ModelForm UpdateView
I have a model related to real world events that contains both DateTimeField and Location(PointField). The DateTime will always be entered/updated by the user in the TZ of the location (I'll refer to it as local time). Therefore, once the form is posted, I need to get the timezone for the location, and apply it to the local DateTime before it is saved to the DB. As it is an UpdateView, I also need to be able to take an instance stored in the DB and present it to the user in local time in the form when the user get's the form. I'm comfortable with getting the timezone for the location, and using Django's timezone to convert the datetime if necessary. However, I'm not sure what the best approach is. The two I have come up with are: Use django.utils.timezone's activate(). This seems the most pythonic approach but I'm 70% N00b and can't figure out which method to override in order to ensure the get and post are both handled correctly. Override get_context_data() and form_valid(). With this approach I would perform the change from timezone aware datetime to local and back in each method. Thank you for any help. … -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "crud_history"
When I try to migrate the database with sqllite, there was no problem. Then I tried to change it to postgresql, this error came out : django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "crud_history" Even if I add : id = models.BigIntegerField(primary_key = True) in the History model, the error still comes out class Biodata(models.Model): lastname = models.CharField(max_length=50) firstname = models.CharField(max_length=50) dob = models.DateField() class History(models.Model): biodata = models.OneToOneField(Biodata, on_delete = models.CASCADE, primary_key_True) fhx = models.CharField(max_length=200, blank=True) shx = models.CharField(max_length=200, blank=True) -
Django 3.0 , Csrf token for login page , html page displaying just as code instead of rendering as a page
I'm a beginner in django, I made my first login page, and added csrf token, but when the login page is run, it doesn't render as a page, instead shows the template code and each time it is refreshed I can see the csrf token changing in the displayed template code. I'll put the code below: views.py: . . from django.template import RequestContext from django.template.context_processors import csrf from django.shortcuts import render #from django.template import context from django.http import HttpResponse import datetime from .models import Book from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.middleware.csrf import get_token ....... def loginpage(request): context = RequestContext(request) context_dict = {} context_dict.update(csrf(request)) return render(request,'login.html', context_dict, context) template code getting displayed on browser instead of rendered page: . . . template code getting displayed on browser instead of rendered page: . . . . I've been trying to sort this out for a few days, but there was no use. Would be wonderful if anyone can help me out here. -
ValueError: The view didn't return an HttpResponse object. It returned None instead
I have been getting the valueError where post_edit returns None instead of an HttpResponse object. This is my views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect, request from django.urls import reverse from markdown import Markdown from django import forms from . import util md = Markdown() class createPage(forms.Form): title = forms.CharField(label="Title", widget=forms.TextInput(attrs={'cols': 60})) description = forms.CharField(label="Description", widget=forms.Textarea(attrs={'cols': 120})) def pages(request, name): page_name = util.get_entry(name) if page_name is None: return render(request, "encyclopedia/invalidPage.html", { "title": name.capitalize() }) return render(request, "encyclopedia/wikiPages.html", { "page": md.convert(page_name), "title": name }) def post_edit(request, name): if request.method == "POST": form = createPage(request.POST) if form.is_valid(): description = request.POST.get('description') title = form.cleaned_data["title"] description = form.cleaned_data["description"] util.save_entry(title, description) return HttpResponseRedirect(reverse('pages', kwargs={'name': title })) else: description = { 'title': name, 'description':util.get_entry(name) } return render(request, "encyclopedia/edit.html", description) My edit.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} | Edit {% endblock %} {% block body %} {{message}} <form action="{% url 'post_edit' title %}" method="POST"> {% csrf_token %} <table> <tr> <th><label for="title">Title:</label></th> <td><input type="text" name="title" cols="60" required disabled value="{{title}}" id="title"></td> </tr> <tr> <th><label for="description">Description:</label></th> <td> <textarea name="description" cols="120" rows="10" required id="id_content">{{ Description | linebreaksbr}}</textarea> </td> </tr> </table> <input type="submit" value="Edit"> </form> {% endblock %} My urls.py from … -
Running Django celery on load
Hi I am working on a project where i need celery beat to run long term periodic tasks. But the problem is that after starting the celery beat it is taking the specified time to run for the first time. I want to fire the task on load for the first time and then run periodically. I have seen this question on stackoverflow and this issue on GitHub, but didn't found a reliable solution. Any suggestions on this one? -
Access to XMLHttpRequest at 'https//www.yahoo.com/...' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy
I am using django, and in front end I am tring to get a json sting from API end point. Here is my code in front end: $.ajax({ url: yahoo_endpoint, type: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, success: function (data) { console.log(JSON.stringify(data)) }, error: function (xhr, status, error) { }, dataType: 'json', cache: false, contentType: false, processData: false }); however I am getting the following error: Access to XMLHttpRequest at 'https://yahoo....' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://yahoo.com/*' that is not equal to the supplied origin. the url end_point works fine when I use browser. I was wondering if someone can shed some light here to see whats the problem, Thanks, -
Using class method data in charts
i'm trying to display data on my charts using some model values and charts.js. My values are a country field and a class method that i'm not sure how I'm to call it. I keep getting the error "TypeError: 'Organization' object is not subscriptable django charts.js" or nothing displays at all. Please help. models.py from django_countries.fields import CountryField class Organization(models.Model): country = CountryField(blank_label='(select country)') def Total_Score(cls): Total_Score = cls.grants_score() + cls.internal_score() #This is a sum of other class methods. This part works as is. return Total_Score Views.py def scores_charts(request): labels = [] data = [] orgz = Organization.objects.values('country').annotate(Total_Scores=Organization.objects.values('Total_Scores()')) for org in orgz: labels.append(org['country']) labels.append(org['Total_Scores']) return JsonResponse(data={ 'labels': labels, 'data': data, }) Template.html <div class="card-block-big"> <canvas id="scores_charts" data-url="{% url 'scores_charts' %}"></canvas> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> $(function () { var $scores_charts = $("#scores_charts"); $.ajax({ url: $scores_charts.data("url"), success: function (data) { var ctx = $scores_charts[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: [{ label: 'Scores', backgroundColor: 'blue', data: data.data }] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Scores Bar Chart' } } }); } }); }); </script> -
NoReverseMatch Unless Url Is In Main Project Urls.py
I have a project called 'my_project' and within that project I have an app called 'my_app' so I have two urls.py files. All of my url's for my_app are located within it's urls.py file and work correctly, except one. That one is 'download_file'. My site works when this is included in my_project's urls.py, but when it's in my_app's urls.py I get a NoReverseMatch error on page load. I don't know why this url only works when it's located in my main projects url's folder. Id rather it be in my_app's urls.py file as the link is located within this app. I suspect it has something to do with the regex, though I can't figure it out. my_project.py urlpatterns = [ # this works url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'), ] my_app.py urlpatterns = [ # if I remove the url from my_project.py this one returns NoReverseMatch on page load url(r'^download_file/(?P<file_path>(.+)\/([^/]+))$', users_views.DownloadFile.as_view(), name='download_file'), ] Thank you. -
Unable to retrieve the current user
I've recently moved to AWS. When I try to access one particular area of my site, I get a 500 error. The trackback provides no details as to what the problem is aside from this: Request information: USER: [unable to retrieve the current user] GET: No GET data POST: No POST data FILES: No FILES data COOKIES: No cookie data Thanks!