Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make an HTTP request to Django Rest Framework with Session Authentication?
I'm trying to access an API endpoint protected with DRF's session authentication. This requires passing the CSRF cookie in the request headers, which I have done following the Django docs, like this: import * as Cookies from "js-cookie"; var csrftoken = Cookies.get('csrftoken'); fetch('/api/myendpoint', { headers: { 'X-CSRFToken': csrftoken }}) .then(response => ...) I have turned on session authentication in my settings.py like this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Django login and authentication is working correctly for normal pages, but not for my API calls. I always get a 403 error with the response Authentication credentials were not provided. I have checked that the X-CSRFToken header value is correctly set to the current csrftoken cookie value by looking at the request in Chrome's network panel. -
django smart select does not work with inline formset and jquery.formset.js
I'm using django smart-select in a formset, it works fine on the first line, but adding more products does not work, how could I fix it? enter image description here -
Prepopulate ModelForm fields based on referring URL
I have a website which catalogs local hikes. Users can "log" that they have completed these hikes. I have both of these models+forms working as intended. Right now, though, in order to log a hike, you have to select the hike from a long list which contains all the hikes in the database. I'd like to be able to pre-populate that field so that if you are coming from the detail page of the hike in question, then that field is filled in with the hike. Here's some code: models.py: model Hike(models.Model): name = CharField(max_length=255) slug = models.SlugField(unique=True) ...other fields... model UserLog(models.Model): hike = models.ForeignKey(Hike, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py: class LogHike(forms.ModelForm): class Meta: model = UserLog fields = ('hike', 'date', ... other fields) views.py: def hike_detail(request, slug): hike = Hike.objects.get(slug=slug) log = UserLog.objects.filter(hike__slug=slug) ... more stuff here ... return render(request, 'hikes/hike_detail.html' { 'hike': hike, 'log': log, }) def log_hike(request): if request.method == "POST": form = LogHike(request.POST) if form.is_valid(): obj = form.save(commit=False) userid = request.user obj.user = request.user obj.save() return redirect('user_profile', uid=userid.id) else: form = LogHike() return render(request, 'log_hike.html', {'form': form}) So if a user is viewing the "hike_detail" view, I want to have a link that sends them … -
Django ORM - filtering on related objects
Let's suppose I have a model: class Post(models.Model): user = models.ForeignKey(User, related_name='users') I want to query all users and have list of today's posts for each of them. Here are some good solutions, for example using model methods or iterating through each User, but it seems to me that they do not really have a good performance, because ORM is not used by them. Maybe there is any way like User.objects.all().annotate(filtered_posts = ...)? -
Django, how can I loop through the choices in HTML and display in radio buttons?
In Django I have defined some Questions and I want to give a form to users to create own Choices. The output I'm getting in HTML is drop down box but I want to have it in 'radio button' format. HTML: <form action="" method="post" autocomplete="off"> {% csrf_token %} {% for question in context %} <input type="radio" name="{{ question.questionText }}" value=""> {{ question }} <label for=""></label> {% endfor %} <input type="submit" value="Submit"> Models.py: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choiceText = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choiceText Views.py: def addchoice(request): form_class = AddChoiceForm if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): context = form.save() else: context = form_class() return render(request, 'polls/add_a_choice.html', {'context': context}) The output I am getting is attached is added as image. Screenshot is here -
How to get queryset value outside of loop in Django template?
I have this below scenario as an example Current scenario {% for city in cities %} <div id="{{city.country}}"> <p>Choose a city</p> <li>{{ city.name }}</li> </div> {% endfor %} What I want <div id="{{city.country}}"> <p>Choose a city</p> {% for city in cities %} <li>{{ city.name }}</li> {% endfor %} </div> How can I achieve that? Thanks -
vim plugin to autocomplete blocks in django templates but *not* a generic snippets plugin?
I recently started working with django templates and was wondering whether there are any autocompletion plugins for template directives like {% block|if|... %}etc that do not involve a snippets library. I specifically do not want a snippet plugin because I find them quite distracting when editing code. Most snippet plugins would require digging thru' the docs and to figure out configuration to disable (rather than enable) snippets. I am thinking something along the lines of auto-pairs and xmledit which does something like (assuming | is the cursor): {% block ... %}| <-- recognize I entered a "%}" complete it to: {% block ... %} | <------- place the cursor here {% endblock %} -
Django Filter query - ignoring if the parameter is null
In my django APIView class, I am taking in month and year from a POST in the following way: month = request_data.get("month") year = request_data.get("year") Then I am calling a query to get the data where the month == month and year == year. queryset = Expenses.objects.filter(month=month, year=year) This totally works if I am posting the month and year. But I want to do the following: If month is null, i want to get every record in the POST-ed year. At the moment if I POST month as null, then I don't get any results. I know this can be sorted by a simple if-else, but I want to know if there is any simpler way. -
CreateViews and assigning values to two OneToOneFields
I am trying to set the value of two OneToOne fields on save in a CreateView. Here are the two models (each living in separate apps). CompanyProfile app Models.py: class CompanyProfile(models.Model): user = models.OneToOneField(User, related_name='user') company_name = models.CharField(max_length=255) CompanyData app Models.py: class CompanyData(models.Model): user = models.OneToOneField(User) companyprofile = models.OneToOneField(CompanyProfile) num_cust = models.FloatField() I would like to set user and companyprofile using the CreateView. I can set the user with form_valid code below. CompanyData CreateView: class CompanyDataCreateView(generic.CreateView): model = models.CompanyData fields = ['num_cust'] template_name = 'company_data/companydata_form.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super(CompanyDataCreateView, self).form_valid(form) Question: How do I also set CompanyProfile to that user's companyprofile at the same time? Is there a way to do this in form_valid before the save? -
ELSE statement is getting skipped
In my template, I am trying check if a list is not empty. If it is not empty, I check for something. However, if the list is empty, it 'else' is never evaluated. {% for secret in secrets %} <div class="secrets"> <p>{{secret.secret}}</p> {%load humanize%} <p>({{secret.created_at|naturaltime}})</p> <p>{{secret.likes.all|length}} likes</p> {% for like in secret.likes.all %} {% if like %} {% if like.id == request.session.user_id %} <p>You liked this</p> {% else %} <a href="{% url 'secrets:like_it' id=secret.id %}">Like</a> {% endif %} {% else %} <!--This seems to get skipped--> <a href="{% url 'secrets:like_it' id=secret.id %}">Like</a> {% endif %} {% endfor %} </div> {% endfor %} -
create_superuser for custom authentication model
I have created the following code to build a custom Django authentication model and I am attempting to create a superuser with the custom user manager but when I attempt to use the python manage.py createsuperuser command, I receive the following error: TypeError: create_superuser() got an unexpected keyword argument 'password' UserHandler/models.py # Custom Auth Manager class AuthManager(BaseUserManager): def create_superuser(self, supplied_email, supplied_password, supplied_first_name, supplied_last_name, supplied_language): # Make this password great again (w/ salting and hashing) hashed_salted_password = AbstractBaseUser.set_password(supplied_password) superuser = AuthLookup() superuser.email_address = supplied_email superuser.password = hashed_salted_password superuser.first_name = supplied_first_name superuser.last_name = supplied_last_name superuser.language = supplied_language superuser.save() # Abstract Auth Model class AuthLookup(AbstractBaseUser, PermissionsMixin): email_address = models.EmailField(unique=True) password = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) organization_id = models.UUIDField(null=False, max_length=36, default=uuid.uuid4) # Firebase tokens(Max length represents 5 device tokens at maximum length of 256 characters plus 4 commas.) associated_devices = models.CharField(max_length=1284) is_requester = models.BooleanField(null=False, default=0) is_responder = models.BooleanField(null=False, default=0) user_identifier = models.UUIDField(null=False, max_length=36, default=uuid.uuid4) language = models.CharField(max_length=6, default='US_EN') user_added = models.DateTimeField(default='1970-01-01 00:00:00') object = AuthManager() USERNAME_FIELD = 'email_address' REQUIRED_FIELDS = ['first_name', 'last_name', 'language'] Settings.py AUTH_USER_MODEL = 'UserHandler.AuthLookup' -
Local field 'created_at' in class 'BandRating' clashes with field of the same name from base class 'Rating'
I've recently tried to create two separate models inheriting from Rating but upon migration I get the error mentioned in the title. I assume this is due to rogue migrations as it seems that there should be no clashes in my code? I initially had Rating which had two optional fields, Venue or Band but I feel this is better structure. For future reference, what would be the ideal way to do this without running into this kind of issue? class Rating(models.Model, Activity): created_at = models.DateTimeField(auto_now_add=True, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) rating = models.IntegerField(default=0) description = models.CharField(max_length=200, null=True) class Meta: abstract = True def get_author(self): if self.author is None: return "Anonymous" else: return self.author @property def activity_actor_attr(self): return self.author class BandRating(Rating): band = models.ForeignKey(Band) def __str__(self): return str(self.band) + " rating" class VenueRating(Rating): venue = models.ForeignKey(Venue) def __str__(self): return str(self.venue) + " rating" -
Social signup and duplicate email error
Here is my issue with django-allauth. I have a custom user model with email as USERNAME_FIELD. I don't use custom signup form. As for social providers they are Facebook and Google. My allauth settings are: ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" ACCOUNT_USERNAME_REQUIRED = False SIGNUP_PASSWORD_ENTER_TWICE = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' Here is the problem in steps: User successfuly signs up first time using standard signup or social, email test@test.com User logs out and tries to log in using another social account which uses the same email test@test.com used in social provider. Allauth on '/accounts/social/signup/' asks to input email "You are about to use your Google account to login to XYZ. As a final step, please complete the following form". Email field is automatically prefilled with value received from Google. User clicks 'submit' and gets form validation error: "An account already exists with this e-mail address. Please sign in to that account first, then connect your Google account." User puts another email into the field test2@test2.com and gets 500 page. IntegrityError at /accounts/social/signup/ (1062, "Duplicate entry 'test@test.com' for key 'email'") Questions: Why does the form accept the new email … -
Django, trying to change the class attribute of an extended nav bar
I created a "base.html" template to hold my nav bar and other elements that are recurrent on my website. When I extend this template and put values into my blocks one of them doesn't want to work properly. In my code I try to set the class value of my nav element to "active" depending on which page I'm in (it might not be the best solution). This block never works. Thank you for your help :) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^addProduct/$', views.addProduct, name='addProduct'), ] views.py def index(request): latest_product_list = Product.objects.all().order_by('-id')[:5] return render(request, 'main/index.html', {'latest_product_list': latest_product_list}) def addProduct(request): # Do things return render(request, 'main/add_product.html', {'form':form}) base.html <!DOCTYPE html> <html lang="fr"> <head> #header informations </head> <body> <div class="container-fluid"> <div class="row"> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} </div> <ul class="nav nav-pills" role="tablist"> <li role="presentation" class="{% block navbar_class-index %}{% endblock %}"><a href="{% url 'main:index' %}">Index</span></a></li> <li role="presentation" class="{% block navbar_class-addProduct %}{% endblock %}"><a href="{% url 'main:addProduct' %}">Ajouter un produit</a></li> </ul> <div class="row" id="content"> {% block content %}{% endblock content %} </div> </div> </body> index.html {% extends "base.html" %} {% block navbar_class-index %}active{% endblock %} {% block content %} <div class="col-md-12"> ## Here is my content </div> {% endblock … -
Django template and Pandas
I am using Django, and I have a pandas dataframe in my view, and from this df I am creating a graph. I want to plot this graph on a template, how is it possible? thanks -
Django Rest Framework and Angular 2 File Upload
I am using Django Rest Framework and Angular 2 to upload a file. My files looks like this. What do I do wrong? Tell me please. Thank you very much. Django file: view class ProjectTaskViewSets(viewsets.ModelViewSet): queryset = ProjectTask.objects.all() serializer_class = ProjectTaskSerializers parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer, format=None): file = self.request.data.get('file', False) if file: serializer.save( text=serializer.validated_data.get('text'), project=serializer.validated_data.get('project'), file=file) else: serializer.save( text=serializer.validated_data.get('text'), project=serializer.validated_data.get('project') ) def filter_queryset(self, queryset): project = self.request.query_params.get('project', False) if project: queryset = queryset.filter(project_id=project) return queryset serializers class ProjectTaskSerializers(serializers.ModelSerializer): class Meta: model = ProjectTask fields = '__all__' def create(self, validated_data): return ProjectTask.objects.create(**validated_data) model class ProjectTask(models.Model): text = models.CharField(_('text'), max_length=200, blank=True, null=True) file = models.FileField( _('file'), blank=True, null=True, upload_to=directory_path ) project = models.ForeignKey( DashboardProject, verbose_name=_('project'), related_name='task_list', on_delete=models.CASCADE ) class Meta: verbose_name = _('project task') verbose_name_plural = _('project tasks') ordering = ('-id',) def __str__(self): return self.text[:20] def __repr__(self): return '<ProjectTask {}>'.format(self.text[:20]) Angular files component saveTask() { this.taskForm.value.file = this.file; console.log(this.taskForm.value); this.taskService.addTask(this.file).subscribe( (data) => { console.log(data) }, (error) => { console.log(error) } ); } onChange(event) { let files = event.target.files; console.log(files); let formData: FormData = new FormData(); formData.append('file', files[0], files[0].name); //if (files.length > 0) { // let formData: FormData = new FormData(); // for (let file of files) { // formData.append('files', … -
Error whith command python manage.py makemigrations
Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/makemigrations.py", line 150, in handle self.write_migration_files(changes) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/makemigrations.py", line 179, in write_migration_files with open(writer.path, "wb") as fh: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/django/contrib/auth/migrations/0008_auto_20170226_1950.py' -
Rendering list of query_set as row on html template
I would like a list of Articles tagged associated with Stories to be rendered on rows exclusive to their Story. Currently the template returns only articles from the last Story on three separate rows. The code as written and understood is: Many Articles can belong to a single Story. /models.py class Article(models.Model): feed = models.ForeignKey(Feed) title = models.CharField(max_length=200) url = models.URLField() publication_date = models.DateTimeField() class Story(models.Model): title = models.CharField(max_length=200, default= "") description = models.TextField() publication_date = models.DateTimeField() article = models.ManyToManyField(Article, default=None, blank=True) Using queries, get a list of all story_ids. If entry in story_id_lst is equal to story_id in articles then append that story to row list. /views.py def articles_list(request): articles = Article.objects.all() story_id_lst = list(range(articles.values('story').order_by('story').distinct().count())) for entry in range(len(story_id_lst)): rows =[] for story_id in articles.values('story'): if entry == story_id['story']: rows.append(articles.filter(story=entry)) Running that code in the shell returns three list, one empty, one with all articles matched to story 1 and one with all articles matched to story 2. I believe the problem is somewhere in the following code. /views.py return render(request, 'news/articles_list.html', {'rows': rows}) /articles_list.html <div class="container" style="background-color: #DCDCDC; border-radius: 25px;"> <div class="row"> {% for row in rows %} <div class="col-md-12"> {% for entry in row %} <div class="container-fuild"> … -
Django Pandas AWS
I was able to get Pandas to compile properly on my Elastic Beanstalk hosted site. When I SSH into the instance I can load and load and call Pandas properly, however when I call a view that utilizes Pandas via the browser, EBS simply hangs and will not serve the page. Eventually it times out with an HTTP 504 error. I checked the logs and nothing jumps out at me. Any help would be greatly appreciated! -
How to configure STATIC_ROOT for a Django project on Heroku?
I am trying to run the following command: git push heroku master But I'm getting the following error: raise ImproperlyConfigured("You're using the staticfiles app" django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Error while running '$ python manage.py collectstatic --noinput'. My directory looks like this: myproject myapp static ... myproject setting.py ... In my settings.py file I am setting these: ... STATIC_ROOT = os.path.join(BASE_DIR, 'myapp', 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'myapp', 'static'), ) ... How can I solve this? Note: I'm a beginner on Django and Heroku, this is my first project. -
Django form POST with NoReverseMatch error
In html: <form role="form" method="post" action="{% url 'myappapp:add_review' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-sm-10"> <input id="review" name="review" type="text"> </div> </div> <button type="submit" class="btn btn-default"> Submit </button> </form> In views: def add_reviews(request): if request.method == "POST": print "Post is here:", request.POST['review'] return render(request, 'myapp/single_item.html') //or this?? return redirect('myapp:single_item') In urls.py app_name = 'myapp' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), # register, login, logout url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'^login/$', views.login_user, name='login'), url(r'^logout/$', views.logout_user, name='logout'), # individual article page url(r'^(?P<item_id>[0-9]+)/$', views.single_item, name='single_item'), url(r'^(?P<item_id>[0-9]+)/add_review/$', views.add_review, name='add_review'), ] Really basic stuff, in each individual item page, I want a form to write and post reviews for each item, and go back to the same item page. When I'm in the individual item page, gives me the following error: Reverse for 'add_review' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P[0-9]+)/add_review/$'] -
How to fix Django Rest API error?
How to fix this error? Traceback (most recent call last): File "C:/Users/HP/Downloads/cv_api/cv_api/manage.py", line 10, in execute_from_command_line(sys.argv) File "F:\Anaconda2Installation\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "F:\Anaconda2Installation\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management__init__.py", line 316, in execute settings.INSTALLED_APPS File "F:\Anaconda2Installation\lib\site-packages\django-1.10.5-py2.7.egg\django\conf__init__.py", line 53, in getattr self._setup(name) File "F:\Anaconda2Installation\lib\site-packages\django-1.10.5-py2.7.egg\django\conf__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "F:\Anaconda2Installation\lib\site-packages\django-1.10.5-py2.7.egg\django\conf__init__.py", line 97, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "F:\Anaconda2Installation\lib\importlib__init__.py", line 37, in import_module import(name) ImportError: No module named cv_api.settings -
Django aggregate not returning any value
I have a view: class ExpenseDateFilterTotal(APIView): def post(self, request, format=None): queryset = Expenses.objects.all().aggregate(total=Sum('day')) return HttpResponse(queryset, content_type="application/json") access from the url: url(r'^expenses_date_filter_total/$', expenses.ExpenseDateFilterTotal.as_view()), I am expecting a response equal to: {"total":234} but all I am getting is: total I am new to django and i read the api doc at https://docs.djangoproject.com/en/1.10/topics/db/aggregation/. The count() functions are working perfectly. But the sum/avg/max etc is not. -
Accessing a key value pairs in a JsonResponse in Django Unit Testing
I want to access the data returned in the following jsonResponse object: {"results": [[1, "Probability and Stochastic Processes", 9781118324561, "Roy D. Yates", "2014-01-01", "Wiley"], [2, "Interaction Design", 9781119020752, "Rogers Price", "2015-01-01", "John Wiley & Sons"], [3, "Microeconomics", 9780077501808, "Colander", "2013-01-01", "McGraw Hill"], [4, "jfalksdjf", 123123, "test", "1990-01-01", "Penguin"]]} I am running into trouble however and I have tried many things def test_noIDGiven(self): response = self.client.get(reverse('allTextbooks')) #returns the json array above #check that there are three textbooks in the response #print(response.content['results'][0][0]) - this didnt work self.assertEquals(response.content[0][0], 1) #basically want to access the id of the first object and make sure it is 1 Any help on how the best way to go about accessing the key value pairs of this object would be nice. thanks in advance -
python-social-auth disconenct raises NotImplementedError
I'm trying to add python-social-auth 0.2.10 to a project using Django 1.6. There are existing users which need to be able to link to a github account and disconnect. Authenticate GitHub Seems to work - albeit only once. Once I've connected to a github, I can no longer connect to github again, even if I log into another account. Further: Disconnect gives me "NotImplementedError at /account/preferences/". I have not modified the disconnect pipeline in any way at all.