Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - init registration specific fields without rendering form
I'm new and i'm using Python 2.7.15 and it is NOT Django REST Framework. There is my form: class RegForm(UserCreationForm): telephone = forms.CharField(required=False) user_type = forms.ChoiceField(required=False) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'telephone', 'groups', 'user_type', 'password1', 'password2', 'email' ) Fields: first_name, last_name, telephone, email, password1 and password2 are provided by mobile POST request. And the rest of fields I would like to init during saveing... but there comes a problems. Few of other fields like groups and username are required... so i have to add them to request.POST['username'] = some_function() request.POST['groups'] = [1, 2] and it works But i have problem passing groups, I need to push two values (group id = 1 and 2) When I'm trying request.POST['username'] = [1, 2], and then form = RegForm(request.POST) it passes by but the value inside is [[1, 2]] (double list), not [1, 2]. I don't know how to unpack [1, 2] that request.POST['username'] will take at the same time request.POST['username'] = 1 and request.POST['username'] = 2 I've tried: request.POST['username'] = 1, 2 request.POST['username'] = (1, 2) request.POST['username'] = {1, 2} request.POST['username'] = {1: 1, 2: 2} list = [1, 2] request.POST['username'] = *list # its python … -
Is there a Django setting to generate multiple_words table names for MultipleWords models?
Given an example app called x_y with a model called FooBar the generated table name is x_y_foobar rather than the expected x_y_foo_bar. This makes it harder to read and distinguish table names, especially with long names. Is there a global setting that I can use so I don't have to set each table name manually? PS: I would be fine with model names like TLA ending up as t_l_a in the table name. -
Purpose of Django FieldType Default String Parameter
In the Django 2.0 Mozilla tutorial, they sometimes use a initial string argument when defining various fieldTypes as part of there new models. For example, they do this with the author variable (ForeignKey FieldType) and isbn (CharField) in the below snippet. class Book(models.Model): """ Model representing a book (but not a specific copy of a book). """ title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') What is the purpose of this string? I looked through the Django Model Documentation and could not find an initial string parameter as an option. I assume it is the value used for the column in the database, but that is specified with the optional parameter db_column. Any insight is appreciated. Thanks. -
Django 1.11: Error during template rendering , __str__ returned non-string (type NoneType)
i get this error in django 1.11 Exception Type: TypeError at /posts/new/ Exception Value: __ str__ returned non-string (type NoneType) and this is my models.py file enter code here from django.conf import settings from django.core.urlresolvers import reverse from django.db import models import misaka from groups.models import Group from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name="posts") created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True,blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] and that's my urls.py of posts application from django.conf.urls import url from . import views app_name='posts' urlpatterns = [ url(r"^$", views.PostList.as_view(), name="all"), url(r"new/$", views.CreatePost.as_view(), name="create"), url(r"by/(?P<username>[-\w]+)/$" ,views.UserPosts.as_view(),name="for_user"), url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$" ,views.PostDetail.as_view(),name="single"), url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"), ] i google it but found nothing -
pytest+Django coverage: test class-method that utilizes other class methods?
I want to test the following snippet (see comments): class Article: ... @staticmethod def get_article_as_json(article_id): ... # already tested @staticmethod def parse_article_json(article_as_dict): ... # already tested @classmethod def get_final_article_json(cls, article_id): art = cls.get_article_as_json(article_id) # how do I test this? return cls.parse_article_json(art) #and this? No matter what I do, I can't get my test for get_final_article_json to cover the inner calls to the other functions (which I'm already testing in other tests). The lines for these two statements are always marked uncovered (red). One solution is to simply change the statements to Article.method instead of cls.method, but changing a convention just to gain a few more % of coverage seems wrong... -
How do I share a child foreign table amongst to parent tables in Django models
I currently have this setup: class Address (models.Model): Member = models.ForeignKey(Member, blank=True, null=True, on_delete=models.CASCADE) Unit = models.ForeignKey(Unit, blank=True, null=True, on_delete=models.CASCADE) Address1 = models.TextField(max_length=512) Address2 = models.TextField(max_length=512, null=True, blank=True) City = models.TextField(max_length=100) State = models.TextField(max_length=100) Zip = models.TextField(max_length=25) Latitude = models.FloatField(null=True, blank=True) Longitude = models.FloatField(null=True, blank=True) Primary = models.BooleanField(default=False) class Phone (models.Model): Member = models.ForeignKey(Member, blank=True, null=True, on_delete=models.CASCADE) Unit = models.ForeignKey(Unit, blank=True, null=True, on_delete=models.CASCADE) Phone = models.CharField(max_length=25) Type = models.CharField(max_length=25) Primary = models.BooleanField(default=False) class Member (models.Model): FederationID = models.FloatField(unique=True) UserId = models.ForeignKey(User, on_delete=models.CASCADE) height = models.IntegerField(blank=True, null=True) eye = models.CharField(blank=True, null=True) hair = models.CharField(blank=True, null=True) bio = models.TextField() class Unit (models.Model): Name = models.CharField(max_length=255) Hull = models.CharField(max_length=20) Type = models.CharField(max_length=20) I'm trying to use a single address table to mimic both Members and Units' Address. I'm asking if this is the right way to go about this? Is there a more DRY version of doing this correctly. Notice the Phone model as well. Same question. Thanks. -
How can I "replace" the name of a model's ID with a field from another model?
How can I "replace" the name of a model's ID (Memorandum) with the first_name of the other model (User) in a table list in a template? I use the default user model of django. Example: Pictures Template From (ID = de) | Date | Detail 2 | 2/2/2018 | Commentary TO From (ID = de) | Date | Detail Jane | 2/2/2018 | Commentary view.py def MemoList(request, usuario): instancia = get_object_or_404(Empleado, usuario_id=usuario) lista2 = Memorandum.objects.filter(para_id=instancia) for usuarios in lista2: lista_de_id = usuarios.de_id lista_para_id = usuarios.para_id lista_asunto = usuarios.asunto lista_fecha = usuarios.fecha context = { "lista2":lista2, "lista_de_id": lista_de_id, "lista_para_id": lista_para_id, "lista_asunto": lista_asunto, "lista_fecha" : lista_fecha } return render(request, 'app/admin/memolist.html',context) models.py class Memorandum(models.Model): de = models.ForeignKey(User) para = models.ForeignKey(Empleado) fecha = models.DateField(default=datetime.date.today) detalle = models.TextField() -
Django QuerySet - Joining tables on id in array
I've been having some difficulty figuring out how to implement the following PostgreSQL query using Django query set notation: SELECT * FROM table1 JOIN table2 ON table1.id_column = ANY(ARRAY[table2.array_column]); Any help would be greatly appreciated! -
How to submit Decimal to Django API?
I've got a model with a DecimalField(max_digits=40, decimal_places=20), but when I pass a string value of '1.10' to the relevant API endpoint it gets saved to the Postgres database as 1.10000000000000000000. How do I ensure that it gets saved as 1.10? -
Extracting Token from Django AuthTokenSerializer with React native
I am trying to extract a authorization token from the restframework of Django authtoken and can't seem to get the response token from the request. By using Postman I get the token with status 200. But when I try to do this with Fetch in my code I get status 200 a different response. Response from POST request From the server's perspective I get the POST request with 200 response.I believe it's just formatting of the response but I can't seem to figure out how. Below is the code for my Login Form. import React from 'react'; import {View,Text, TextInput, TouchableOpacity, StyleSheet} from 'react-native'; import {createStackNavigator} from 'react-navigation'; const fetch_url = 'http://192.168.0.17:8000/api/api-auth/'; export default class LoginForm extends React.Component { constructor(props){ super(props); this.loginHTTPRequest = this.loginHTTPRequest.bind(this); this.state = { username: '', password:'', respons:'', error:null, loading: false, } } loginHTTPRequest(){ if(this.state.username != '' && this.state.password != ''){ this.setState({ loading:true, }); fetch(fetch_url,{ method:'POST', headers:{ Accept:'application/json', 'Content-Type':'application/json', }, body: JSON.stringify({ username:'admin', password:'admin12345', }), }) .then((response)=>{ if (response.status >= 200 && response.status < 300) { //Where I want to extract the token from the response console.log(response); }}) .catch((error) => { this.setState({ error:error, loading:false, }); }); } } render(){ return ( <View style={styles.container}> <TextInput style={styles.input} autoCapitalize = … -
Django delete models from db
I have such issue, I created models, than deleted them. I did makemigrations and migrate, but when I want to create Group of Users in the Available permissions i see this models and permissions for them. models Group, Person, Membership How to remove them? -
Logger results not appearing in unittest output with Django
I'm having difficulty getting the desired behavior at the intersection of the django test runner, i.e. from django.test import TestCase and the logging solution. my logger is set up and works in other areas with something like this import logging logger = logging.getLogger(__name__) logger.warning("duck!") so when running the Django app, I see the message and metadata as I expect; however, the trouble is that these log lines do not show up in any location I am aware of when running the unit tests, i.e. django-admin run test I want to be able to run tests and see the log output, ideally in STDOUT, and presumably set the output log levels so that tests show those... my settings vis. logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'ERROR', 'handlers': ['sentry', 'console'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'WARNING', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'WARNING', 'handlers': ['console'], 'propagate': False, … -
Does web framework do it all?
I would like to know of what web framework is responsible off. I'm thinking to start a web app project, so I'm digging what frameworks should I use. So for HTML/CSS I'm thinking of Foundation framework, for JS I have chose to use React framework. For a backend I have chosen to use Django framework, and it says that Django is a web framework. Will I be able to implement Foundation and React to django, or django will take care off all those aspects? -
javascript / ajax if conditional (Django)
I have an ajax POST being sent if a form is submitted. How can i have the POST sent if the form isn't submitted but the submit button is clicked? example if form.submitted: send request elif button.click: send request This brings me to my second question, can an ajax function be stored in a variable? Here is my actual code (excluding the form). I'm working in the django framework. <script type="text/javascript"> var itemCity = ''; var itemPc=''; var itemState = ''; var itemCountry=''; var itemAddress= ''; var itemLat = 0.0; var itemLng = 0.0; google.maps.event.addDomListener(window, 'load', intilize); function intilize() { var autocomplete = new google.maps.places.Autocomplete(document.getElementById('txtautocomplete')); google.maps.event.addListener(autocomplete, 'place_changed', function () { $(".profileForm").submit(function(event) { //event.preventDefault(); var place = autocomplete.getPlace(); var arrAddress = place.address_components; itemLat = place.geometry.location.lat(); itemLng = place.geometry.location.lng(); // iterate through address_component array $.each(arrAddress, function (i, address_component) { if (address_component.types[0] == "locality"){ console.log("city:"+address_component.long_name); itemCity = address_component.long_name; } if (address_component.types[0] == "country"){ console.log("country:"+address_component.short_name); itemCountry = address_component.short_name; } if (address_component.types[0] == "administrative_area_level_1"){ console.log("state:"+address_component.short_name); itemState = address_component.short_name; itemState = address_component.short_name; } if (address_component.types[0] == "postal_code"){ console.log("pc:"+address_component.long_name); itemPc = address_component.long_name; } //return false; // break the loop }); $(document).ready(function(){ var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection … -
When to use different server for a static file in django
I am in a scenario where i have to resize existing images before displaying them on webpage. For that purpose is it wise to use different server for storing my images, as django server may take bandwidth to fetch images from another server. -
Django Trying to save my Array to the model
I have the following data coming from the manager_item = request.POST.getlist(manager_type_item) in my views: ['{"id":"1","title":"Bedroom"},{"id":"2","title":"Taps"}, {"id":"3","title":"Living Room"}'] Basically each one of these are {"id":"1","title":"Bedroom"} will need t be added into the model: index = 0 for index, item in enumerate(json.loads(manager_item)): print(item['id']) print(item['title']) But I not 100% sure the route to go. Hope someone can assist me. Still learning. I know how to save to the model I just need help with getting the data needed. -
Django Rest Framework Ordering Serializer.data
I have a 3 table and they releated between each other. Also i have some serializers.SerializerMethodField which is "elapsed_time" this field calculating elapsed_time so how can i order my Entites according to that MethodField. One way that i found i'm sorting serializer.data this returns OrderedList but this way taking so much time for 2k record. serializer = self.get_serializer(entites, many=True) result_page = get_pool_ordered_queryset(serializer.data) get_pool_ordered_queryset function takes OrderedDict and sorting. serializer_data = sorted(serializer_data, key=lambda k: k['elapsed_time'], reverse=True) Like this but when i add 2k record its taking almost 2 minutes. -
return string based on integer value in django view
I want to return string value based on some integer value in django using view function def picks(request): team = get_object_or_404(Team, user=request.user) all_picks = team.arr pick = team.arr[team.counter] return {'pick': pick, 'all_picks': all_picks} That is returning integer values but I want to return let say if pick is 1 return "Team A" if pick is 2 return "Team B" Also the limit of counter is of 1 to 5 so I need 5 conditions -
django-cleanup django-stdimage - delete image after its been replaced, how?
I'm using django-stdimage for various models that needs an image field. I'm using forms currently and I can upload a new image and replace the image which stdimage generates automatically and is working. I will likely have to use custom code to upload/save media files soon so I need help to have a solution that accounts for both methods of uploading/saving images. What isn't working is when I update an image field to an existing object that already has an image, the old image isn't deleted from the filesystem which I'm expecting django-cleanup to do. I've just installed django-cleanup which deletes images if I delete the model object but it doesn't delete the old image that was just replaced. I've searched and found a few posts but things are just not clicking. I'm using Django 2.0 I will likely be moving over to s3 at some stage so something that can transition to that automatically would be great which appears django-cleanup will do. I also want to avoid having to run a separate program to cleanup files no longer referenced. What do I need to do to get replaced images to existing db objects to be automatically deleted on the … -
How to get exactly one element from list in Jinja?
So I passed a render with directory as an argument in my views.py. Something like this: def foo(request): return render(request, 'webapp/foo.html', {'key': ['one', 'two', 'three']}) Now i want to use Jinja in my HTML file to get exactly one element from directory value, let's say first. All I know for know is how to get all elements with for loop: {% block content %} {% for val in key %} <p> {{ val }} </p> {% endfor %} {% endblock %} My question is if is there something like this? {% block content %} <p> {{ key[0] }} </p> {% endblock %} -
Django: Use logging inside settings.py
I successfully set up Django logging, but I find myself in need to log some information inside settings.py. Is that possible? Currently, the settings only come into effect after the entire file is parsed, which I believe is expected. Is there a way to force the set up of loggers right after specifying them? Otherwise, are there any alternatives that people recommend? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(levelname)s: %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'console' } }, 'loggers': { 'main': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, }, } # The below does not work because the setup declared above is not yet in effect logger = logging.getLogger('main') logger.info("Works?") -
Watching for changes with jquery ajax - django
I'm using a function reload method (setInterval(live,1000);) to reload a part of my web page. And swapping it with the updated content with jquery load() method. Is this a good way of implementing such functionality? if not what is a better way. Any valuable answer would be appreciated thanks. -
How to add placeholders to Textareas in Django
I have searched stack overflow, and I could find an answer to this question. What I'm trying to do is add a placeholder to a textarea element but I don't know to accomplish this. forms.py from django import forms from .models import Post from django.contrib.auth.models import User class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'price', 'title', 'body', 'contact_email', 'contact_number', 'picture', ) widgets = { 'price': forms.TextInput(attrs={'placeholder': 'Price'}), 'title': forms.TextInput(attrs={'placeholder': 'Item for sale'}), 'body': forms.TextInput(attrs={'placeholder': 'Describe the item'}), 'contact_email': forms.TextInput(attrs={'placeholder': 'Enter Price'}), 'contact_number': forms.TextInput(attrs={'placeholder': 'Enter Price'}), } So as you can see I've set placeholders that render correctly for all of the fields except the body field because unlike every other field, it's a <textarea></textarea> element, not an input element. create-post.html {% extends 'base.html' %} {% block head %} <!-- {% load static %} <link rel="stylesheet" href="{% static 'accounts/login.css' %}" type="text/css"> --> <title>Create Post</title> {% endblock %} {% block body %} <div class="container"><br> <form method="POST" action='' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="submit">Submit</button> </form> </div> {% endblock %} This is how the form renders right now. As you can see the body is not large like it's supposed to be here. How can I add … -
Django list in template without trailing comma in a nested for loop
I am trying to create a list of items in a Django template that are separated by commas, but with no comma after the last item. The list of items comes through a for loop within a for loop. I tried to do something like this. {% for thing in things %} {% spaceless %} {% for o in thing.otherthing_set.all %} <span>{{ o.name }}: </span> {% if o.attribute == 'this' %} <span>{{ o.otherattribute}}</span> {% if not forloop.last %} <span>, </span> {% endif %} {% endif %} {% endfor %} {% endspaceless %} <br> {% endfor %} But sometimes there is an extra comma because sometimes for the last item cycled through o.attribute == 'this' isn't always true. What I would like to do is somehow have {% for o in thing.otherthing_set.all %} be filtered for just for o.attribute == 'this' before even going through the for loop, but it doesn't seem that this is possible. Any suggestions? -
Can conditions apply on filtering results using django-filters?
How can I apply conditions of filtering results using django-filters For example I have a field say 'Bookscount' having integer values and if user opts for value > 5 then django-filter displays all those books having 'Bookscount' > 5 import django_filters as df from .models import Books class BooksListFilter(df.FilterSet): class Meta: model = Books fields = ['Bookscount']