Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I make it not redirect to default template page?
I am making google auth system using django-allauth. What I want to do is basically just to redirect to home page when a user is logged in or logged out. But when I try to log in, it redirects to /accounts/social/signup/ and default template is showing up even though I set LOGIN_REDIRECT_URL home page. What is the best way to avoid using default template pages that are given by django-allauth? -
How to receive dropdown values from outside model
I am new to Django and I have what I'm sure is a simple question so please be kind -_^ I have two models “cat” and “litter” I want my model view for “cat” to include the current values for “litter” as a dropdown select. As a User I can select the “litter” name values already present in the database via a dropdown select. How can I accomplish this? here is code from my serializers.py for the two... ... class LitterSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Litter fields = ( 'id', 'name' ) class CatSerializer(serializers.HyperlinkedModelSerializer): litter = LitterSerializer() class Meta: model = Cat fields = ( 'id', 'name', 'slug', 'reference_id', 'short_name', 'gender', 'cat_type', 'litter', 'color', 'weight_unit', 'weight', 'notes', 'birthday', 'photo', 'created', 'modified', 'alert_feeder' ) ... Here is a snippet from my models.py so you can see my many-to-many relation class Litter(models.Model): name = models.CharField(max_length=255) notes = models.CharField(max_length=2048, blank=True, null=True) created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): # Save time Litter object modified and created times self.modified = datetime.datetime.now() if not self.created: self.created = datetime.datetime.now() super(Litter, self).save(*args, **kwargs) def __str__(self): return self.name class Cat(models.Model): litter = models.ManyToManyField(Litter) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) gender = … -
How can i deploy 1 python-django app and 1 java app on the same ec2 instance, where the java one serves the other app?
I am new using AWS, I am trying to deploy a django rest api to and a java app into an aws ec2 instance, the fact is that the java app is used by the rest api, and i dont know if an ec2 instance can support both apps from diferent languages, i will really appreciate your help, thanks in advance. -
Error with my boolean if statement (Django)
I am building a table like the following: <table> <tr> <th>List of car parts available:</th> </tr> <tr> <th>Name</th> <th>Price</th> </tr> {% for product in products_list %} <tr> <td>{{ product.name }}</td> <td>${{ product.price }}</td> <td>{% if product.in_cart == False: %} <a href="products/cart/">Add to cart</a> {% else %} {{ print('')}} </td> </tr> {% endfor %} </table> I would like to say if the product's value for in_cart is False (meaning it is not in cart), then add a link to the cart url. However I get this error: Could not parse the remainder: ':' from 'False:' Then, how can I change its value to true? This is my views: def index(request): products_list = Product.objects.all() template = loader.get_template('products/index.html') context = {'products_list': products_list} return HttpResponse(template.render(context, request)) def cart(request): cart_list = Product.objects.filter(in_cart = True) template_cart = loader.get_template('cart/cart.html') context = {'cart_list': cart_list} return HttpResponse(template_cart.render(context, request)) Thanks! -
Show and serialize the results of select_related() model method
I have two simple models: User (standard Django User) AND class Post (models.Model): class Post (models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name My front end (SPA) sends a request to get all posts, so my Django API would go and fetch Post.objects.all(). However I would like to also pull in the User.username into the response. My understanding is that I can do this by running: posts=Post.objects.select_related('user').all() When I run posts.query from the resulting SQL query I can see that the User fields are being pulled in, however I can't seem to be able to see them when I try to serialize this data. Am I missing something very basic here? What is the way to serialize the related data together with the parent data and send it out with the DRF Response? I have tried approach described in this article, but the serializer built with this approach does not seem to return related data for me: http://ses4j.github.io/2015/11/23/optimizing-slow-django-rest-framework-performance/ -
Apply filter based on relationship between objects - Django-rest-framework
I have 2 models. Account: id, name, age, discoverable Friendship: id, requestor, acceptor (requestor and acceptor are Account IDs) I need to write 2 apis. To get all accounts having discoverable=True. Which I accomplished by applying filter on query set like following in AccountViewSet: def filter_queryset(self, queryset): queryset = queryset.filter(discoverable=True).all() return queryset To get Account detail using following url scheme <server-url>/accounts/1 where 1 is account id. This api should return: NULL if account 1 is not discoverable and also account 1 is not friend with the authenticated account who is calling this api It should return account 1 detail if both requesting account and account 1 are friends, i.e they have an entry in Friendship table, even if the account 1 is not discoverable. -
Django Elasticsearch Global Query
I would like to implement a global search feature on the project I'm working on, but I'm having trouble finding out how to construct the right query. Right now it always returns no results. Here's what I have: models.py class Product(models.Model): name = models.CharField(max_length=200) model_number = models.CharField(max_length=20, blank=True, null=True) url = models.URLField(max_length=250, blank=True, null=True) description = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) [... more non-relevant fields here...] def __str__(self): return self.name class Meta: db_table = 'products' ordering = ['name'] documents.py from django_elasticsearch_dsl import DocType, Index from myapp import models as myapp_models from users import models as user_models products_index = Index('products') products_index.settings(number_of_shards=1, number_of_replicas=0) @products_index.doc_type class ProductDocument(DocType): class Meta: model = myapp_models.Product fields = ('id', 'name', 'model_number', 'description') ignore_signals = True [ .. other document definitions ... ] views.py client = Elasticsearch() search_provider = Search(using=client) class GlobalSearchView(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): query = request.query_params.get('q', None) # How to build the query here? el_query = search_provider.query('term', query=query) el_response = el_query.execute() # Returning EL response for debugging purposes for now. return Response(el_response.to_dict()) I would like to know how to build the query in the view, because trying with match query and term query, the hits array in the response is always … -
Automatically populate relations in Django admin
I'm working on my first Django app. My goal is to have two models, one for offices and one for employees, and when a person record is created (in the admin site), creating and specifying the room also populates that room with that person. I was able to create the models, but now I'm stuck in a catch-22 where when I add a person, I have to create a room, but to create a room I have to add a person, etc... How can I create and automatically populate a room like this? Here is the relevant code from models.py: class Room(models.Model): number = models.CharField('Room number', primary_key=True, max_length=50) occupant = models.ManyToManyField('Person') # Can have multiple occupants class Person(models.Model): name = models.CharField('Full name', max_length=200) office = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) -
Django DecimalField not respecting max_digits and causing Buffer Overflow/Truncation
I'm using Microsoft SQL Server, ODBC Driver 13 for SQL Server with Django 2.0.1 This is actually happening among all my decimal fields and I'm hoping I'm missing something simple. I have declared in my models: Overhead = models.DecimalField(max_digits=6, decimal_places=4, db_column='overhead') A modelform is made with it, and it actually validates having too many digits (ex: 100.0000), and updates correctly when set to one less than the declared amount (ex: 9.0000). Any amount of digits matching max_digits gives a truncation error: String data, right truncation: length 14 buffer 12 If I repeat the same situation with a DecimalField declared like: models.DecimalField(max_digits=9, decimal_places=2, db_column='subtotal') I get the same error type from the database driver (22001) and a slightly different amount of overflow: String data, right truncation: length 26 buffer 24 The SQL that gets generated for the update statement in the log can be copy/pasted and with the exact same parameters in the SQL Editor for SQLServer, and it updates the records happily. I keep thinking something is happening in-between when Django compiles the SQL and the Database driver executing it, but I'm not sure what I would even be looking for, so any help is appreciated. -
Search by contents of integer field in Django
I have a table containing a list of phone prefixes, stored as integers. However I want to be able to search in those in a 'contains' way, so e.g. when searching for '32' I would like to see all records that contain the actual text '32' in the prefix. That is no problem if using plain SQL of course, but I can't find any guidance on how to accomplish this in Django. Basically the part that matters is now: if search_value: destinations = destinations.filter(description__icontains=search_value) And it would have to be something like: if search_value: destinations = destinations.filter(description__icontains=search_value, prefix__icontains=search_value) However, since 'prefix' is an integer column, this does not yield any results. What is the best approach for this? I was thinking of a generated field in MySQL, but then again I don't know how to make that field available in the Django model. -
Django Multisite Dynamic 404 page, editable in the Django Admin interface
I've seen references to custom 404 pages which are static. Has anyone tried making a new Page Type in DjangoCMS, allowing admins to edit it, and serving multisite variants of that dynamic admin-defined page? I'm fumbling through this unsuccessfully. -
How to get all object children in one query?
I have a person model. Each person has it's children. Children may have children as well. I want to get all children (recursively) in one query. How can I do that? class Person(models.Model): name = models.CharField(max_length=40) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') def __str__(self): return self.name def add_person(request): if(request.method == 'POST'): name = request.POST['name'] parent_id = request.POST.get('parent_id') person = Person(name=name, parent_id=parent_id) person.save() return redirect('/persons') else: return render(request, 'add_person.html') -
Javascript html tables checkboxes help needed
I am creating django table app whose columns are configured by admin. Rows can be dynamically added and deleted in table. Columns can be dropdown, checkbox, datepicker, textbox. columns must be in all rows so that user can pick up any value from them and populate cell from chosen value, But I am having some problem with this. Just take an example: I am adding dropdown in a cell by following this link Django Forms and Bootstrap - CSS classes and <divs> but interesting as this value comes in a table I can append other values in that cell as well which is not the requirement. I have attached images that may help you to understand what I am trying to say. Any help would be appreciated as I am new to javascript. Check Image 1- It contain table app structure and columns Image-2: problem I am facing, you can see how it is appearing in cell I can append other values with this value as well which is wrong. I want user to select value from this combobox -
Django: How can I reverse objects with DetailView?
I have used generic views. In views.py I have these: class SeasonList(generic.ListView): template_name = 'episodes/episodes.html' context_object_name = 'all_seasons' def get_queryset(self): return reversed(Season.objects.all()) class SeasonDetails(generic.DetailView): model = Season template_name = 'episodes/season_details.html' In the list view I used reversed() to show the latest season first. Similarly, In the detail view, I want the episodes to appear in the descending order because the latest episode should appear at the top of the page. Is there any way how I can do this? -
NoneType error pops up when trying to delete an object
I have a model called Lecture which has a foreign key to my Courses model. When I try to add a lecture everything goes fine, but when I try to delete one, there is like a 50% chance it will give an error. I don't know why some can be deleted but for some I get the following error: http://dpaste.com/2N043QZ Also, this is my Lecture model: class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, null=True, related_name='lectures', ) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', ) lecture_title = models.CharField(max_length=100, blank=True) content = models.TextField(blank=True) def __str__(self): return str(self.lecture_title) -
"Can't connect to ('0.0.0.0', 5000)" when trying to deploy Django app to Heroku
I am trying to deploy a Django app to Heroku. I get following error after I run heroku local command and go to http://0.0.0.0:5000 Invalid HTTP_HOST header: '0.0.0.0:5000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS However, allowed hosts is already set up like this. My setting.py file: cwd = os.getcwd() if cwd == '/app' or cwd[:4] == '/tmp': import dj_database_url DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } #honorowanie naglowka xforwardedproto dla request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #zezwolenie na wszystkie naglowki hosta ALLOWED_HOSTS = ['0.0.0.0'] #konfiguracja zasobow statycznych BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Initially I had allowed hosts set to ['*'], but it didn't work as well. I am using gunicorn and also tried restarting it using pkill gunicorn, but that didn't help. Is there a better way to restart gunicorn or maybe another solution to the problem? -
should I use Django Groups or a simple model
I'm new to Django and I'm trying to figure out which path to take to solve a problem. Many-to-one OR Django Groups? I have a cat model and now I want to associate any new cats entered into my app with cat litters. (think new kittens) I've been reading about Django Groups but only see this associated with the User model. Can Django Groups be used for any models I create? Is that the best path to get to what I want or should I just rely on a regular Many-to-One model relationship and build out regular models that way? -
Pyinstaller compiles but 404 error on Static javascript files
I've managed to get my applications to compile, but anytime it references a static file I receive a 404 error on my javascript files. I verified they do exist in the dist application. My application structure is setup as the following: I've added my static files to the datas of the .spec file as shown below: # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['C:\\python\\dsssecurity'], binaries=[], datas=[('mysite/static','static_root'),('mysite/search/templates','mysite/templates')], hiddenimports=['django_select2.apps','django.contrib.admin.apps','django.contrib.auth.apps','django.contrib.contenttypes.apps','django.contrib.sessions.apps','django.contrib.messages.apps','django.contrib.staticfiles.apps','django_filters.apps','widget_tweaks.apps','django.contrib.messages.middleware.apps','django.template.loaders.apps'], hookspath=['C:/Python/dsssecurity'], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='dsssecurity', debug=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='dsssecurity') I've also added the static settings to my mysite > search > urls.py as shown below: from django.conf.urls import url, include from django.contrib import admin from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^results/$', views.results, name='results'), url(r'^submitted/$', views.submitted, name='submitted'), url(r'^update/$', views.update, name='update'), url(r'^submittedupdate/$', views.submittedupdate, name='submittedupdate'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my output of the console shows: [22/Jun/2018 14:24:02] "GET /search/?employeentname=&employeelastname=&qv_statusid=1&employee_status_id=1&title=&coid= HTTP/1.1" 200 841390 [22/Jun/2018 14:24:10] "POST /search/results/ HTTP/1.1" 200 36667 Not Found: /static/search/selectallrep.js Not Found: /static/search/selectall.js Not Found: /static/search/rolebased.js [22/Jun/2018 14:24:10] "GET /static/search/selectall.js HTTP/1.1" 404 2354 Not Found: /static/search/buttonsubmit.js [22/Jun/2018 14:24:10] "GET … -
Django Rest Framework return Dicts instead of OrderedDicts
I have a serializer with two attached SerializerMethodField fields: class BentoSerializer(ModelSerializer): zones = SerializerMethodField() lead_zone = SerializerMethodField() def get_zones(self, obj): zone_queryset = obj.get_zones() return ZoneSerializer(zone_queryset, many=True).data def get_lead_zone(self, obj): zone_queryset = obj.get_lead_zone() return ZoneSerializer(zone_queryset).data class Meta: model = Bento fields = ('lead_zone', 'zones', ) I need the data coming out of the serializer to be nested JSON (the ZoneSerializer contains similar SerializerMethodFields of its own, alongside normal model fields) but instead it comes out as an OrderedDict. Is there a way to configure the serializer such that BentoSerializer(obj).data return nested JSON, should I be recursively turning the OrderedDicts into dicts, or is there some other serializer method I don't know about for getting non-ordered data? Many thanks! -
django-allauth; How can I use it without using default templates?
I'm new to Django and I am trying to use django-allauth and create google auth system. What I want to do is basically just to redirect to home page when user log in or log out. But a default template pages are showing up and I don't know how to avoid using these. Anyone can give me tips? -
Trouble using axios to post to django with react
Currently trying to get the comment data to be sent from my react end to django rest backend. Using redux form to grab the data and some initial actions to grab other information. The data successfully gets through redux but when it hits axios I continue to get a bad request. I'm assuming I'm possibly not submitting it in correctly as params. I'm fairly new to this so any help would be appreciated! Comment Action export const createComment = (comment) => { return dispatch => { console.log(comment); return axios.post(COMMENT_API_URL, {type: comment.type, slug: comment.slug, parent_id: `${comment.parent != null ? comment.parent : ''}`, content: comment.content, }) .then((response) => { console.log(response); }).catch((err) => { console.log(err); }) } } Error {type: "post", slug: "first-post", parent_id: null, content: "qwefqwef"} 127.0.0.1:8000/api/comments/create/:1 POST http://127.0.0.1:8000/api/comments/create/ 400 (Bad Request) -
Django: Using CreateView in a model with a foreingkey attribute
I'm trying to use CreateView generic-class in my views.py and the model it refers to have a user attribute (wich is from built-in User class in django) as foreignkey. #models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.urls import reverse class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) def get_absolute_url(self): return reverse('profile', kwargs={'pk': self.pk}) #views.py from accounts.models import UserProfile from django.views.generic.edit import CreateView class RegisterUserView(CreateView): model = UserProfile fields=['username','first_name','last_name','email','password1','password2'] #urls.py path('register/',RegisterUserView.as_view() , name='register') It's given the erros: FieldError at /accounts/register/ Unknown field(s) (last_name, password1, username, email, password2, first_name) specified for UserProfile Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 2.0.6 Exception Type: FieldError Exception Value: Unknown field(s) (last_name, password1, username, email, password2, first_name) specified for UserProfile Exception Location: /home/gaspar/anaconda3/lib/python3.6/site-packages/django/forms/models.py in __new__, line 266 Python Executable: /home/gaspar/anaconda3/bin/python3 Python Version: 3.6.5 Python Path: My question is: the CreateView can get the data from user attribute and create a Modelform, or I have to create a custom ModelForm? -
django with heroku , can't redirect http to https
I have an app deployed to heroku. The app uses djange, gunicorn. I tried to redict http to https with Following settings but no effect : SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True PREPEND_WWW = True BASE_URL = "https://www.etherkar.com" ALLOWED_HOSTS = ['www.etherkar.com', 'etherkar.com'] Any idea thank you -
Django database(sqllite3) doesn't import the excel file values
I am developing a web appp using Django. I started creating admin page and the data I need for the app is in excel sheet(the excel sheet contains almost 250 rows in it), I am using the Django import_export built in feature to import the excel file data to the Django admin database. I click on the table required, then click on Import button, then select the excel file sheet from my computer and select format as .xlsx and click import. After I click import, all the column names get displayed and the id column has the values till 240 but none of the value from excel sheet gets imported to the database. For better understanding of my problem I am attaching an image, which shows no values getting inserted into the database.enter image description here -
Generating UUID in Django migrations (RunPython) is generating identical UUID
Similarly to the question here, I'm trying to add a unique UUID field to a database table with existing rows. I've tried to follow the instructions and break down the migration into 3 operations: def create_user_id(apps, schema_editor): User = apps.get_model('authentication', 'User') for instance in User.objects.all(): if not instance.user_id: instance.user_id = uuid.uuid4() instance.save(update_fields=['user_id']) class Migration(migrations.Migration): dependencies = [ ('authentication', '0002_auto_20180101_1422'), ] operations = [ migrations.AddField( model_name='user', name='user_id', field=models.UUIDField(blank=True, editable=False, null=True), ), migrations.RunPython(create_user_id), migrations.AlterField( model_name='user', name='user_id', field=models.UUIDField(blank=True, default=uuid.uuid4, editable=False, null=True, unique=True), ) ] However I still get an integrity error on the 3rd operation. Closer inspection shows that the created user_id's are all identical. What could be causing this?