Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Default Schema for Django in SQL Server
I am brand new to django, and I am working on setting up the basics of my first project and first app. I migrated my models to SQL Server, and all of the tables showed up under the schema dbo (default schema). I followed the direction of another SO question and set my default schema from within SQL Server to the schema of my choice. I deleted my migration history and migrated again from django. All the tables were created in the dbo schema again. Is it possible to set the schema for django to use? -
why class-based view returned type object 'Profile' has no attribute 'model'?
i have a website with django. this is the project urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('accounts.urls')), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^register/$', RegisterView.as_view(), name='register'), url(r'^logout/$', logout_view, name="logout") ] and this is the accounts.urls: from . import views urlpatterns = [ url(r'(?P<username>[\w]+)/$', views.Profile.as_view(), name='profile_cbv'), ] and this is Profile model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', verbose_name='user', on_delete=models.CASCADE) name = models.CharField(max_length=30, verbose_name='name') family = models.CharField(max_length=50, verbose_name='family') and at last, this is the Profile class-based view: class Profile(View): def get(self, request, username=None): profile = get_object_or_404(Profile, user__username=username) print(profile) pass for example, i go to below url: localhost:8000/ivan/ it raises below error: AttributeError at /ivan/ type object 'Profile' has no attribute 'model' if I pass a correct or an incorrect username with url to view, all the times, it raises that error. what's the problem? -
Accessing Existing Data in a SQL Server Table with Django
I have django connected to SQL Server with django-pyodbc-azure. I am brand new to django. I created a model in django models.py, and I was able to migrate the model to SQL Server. All the proper tables are created. I have historical data that will be eventually served up by the app. Is it possible to access an existing table that holds this historical data in the same DB? Or is it smarter to simply load the historical data into the new table that was created by django? -
Django admin: 'bool' object has no attribute 'startswith'
I am using django_smart_select package. I am getting the following error for the model in which I am trying to use the chained select option. AttributeError at /admin/tags/tag/add/ 'bool' object has no attribute 'startswith' Request Method: GET Request URL: http://127.0.0.1:8000/admin/tags/tag/add/ Django Version: 1.11.4 Exception Type: AttributeError Exception Value: 'bool' object has no attribute 'startswith' Error during template rendering In template C:\Users\gautammandewalker\Envs\django01\lib\site- packages\django\contrib\admin\templates\admin\base.html, error at line 3 'bool' object has no attribute 'startswith' 1 {% load i18n static %}<!DOCTYPE html> 2 {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> 4 <head> 5 <title>{% block title %}{% endblock %}</title> 6 <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}" /> 7 {% block extrastyle %}{% endblock %} 8 {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}" />{% endif %} 9 {% block extrahead %}{% endblock %} 10 {% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %} 11 </head> 12 {% load i18n %} -
How to filter values returned on a filed defined as foreign key
In models.py I have two models: class X(models.Model): id = models.AutoField(primary_key=True) class Y(models.Model): id_fk = models.ForeignKey(X,related_name='x_y') in views.py: class CreateY(generic.CreateView): model = Y now the field Y.id_fk will be a list of values of all in X.id the question is: how can i add extra condition? means if X.id = 1,2,3,4,5 then available values for Y.id_fk will be the same but what if i want to display only values <= 3 how can I accomplish this? -
Best way to structure a Django project
I'm new to django and plan on building a large django project. I'm starting to implement cookicutter django after reading through "2 Scoops of Django" but still have some questions on structuring a project. I've setup my project, we'll call it 'business_proj'. In business_proj I started an app called 'accounting' this might have an accounting dashboard for users in the accounting security group. Now, what if I want to have apps that belong to accounting, such as 'invoices' and 'purchase_orders'? Should I create those apps inside my accounting app? Or should I create all my apps in the main project root? The way I've started doing it is creating child apps inside of their parent apps but some parent apps are so big that even this gets messy. Is there a better way to do this? Thanks -
How to read the contents of drop-down menus in Django?
I have two drop-down menus and I want to retrieve its values to use them as variables to filter the retrieved data from an internal Web API. Views.py # I want to retrieve the year and week number, so I can use them as values in my filter def filter(): filters = {"filter": { "filters": [{ "field": "DateTime", "operator": "gte", "value": "2017-07-23 23:59:59" }, { "field": "DateTime", "operator": "lte", "value": "2017-08-18 23:59:59" }], "logic": "and" }} I did not use Django forms because I am not holding any other data than the years and I am generating the number of weeks, however, if you consider that it might be useful to use Django forms to facilitate the data handling then write your point of view, I want to make this web app better. header.html <form method="POST"> {% csrf_token %} <h6>Select year</h6> <select name="select_year"> <option value = "2016" >2016</option> <option value = "2017"> 2017</option> <option value = "2018"> 2018</option> </select> <h6>Select week</h6> <select name="select_week"> <!--range is not supported: the spaces represent the number of weeks --> {% for week in " " %} <option value="{{forloop.counter}}">{{forloop.counter}}</option> {% endfor %} </select> <button type="submit">Search</button> </form> Caveat: I am concerned that the code to generate … -
Permissions errors with "savefig" in Django
I'm creating a website in Django that generates graphs using Matplotlib and would like to save the figure in a media directory. Unfortunately, I run into a permissions error when attempting to save a file to a specific directory. I've taken a look at this answer: Python Matplotlib errors with savefig (newbie). and it seems to be in parallel with my issue, but I'm not exactly sure how to implement the solution. It says that I am trying to save the file somewhere that the Python process doesn't have permission to access. How would I go about solving this issue? -
Fixing External Library Python
I've been using an external Library for my Django project Called djutils. But since it has been discontinued a lot of outdated stuff were there. Because of it, I've to fix a couple of mistakes in multiple files and now I need to export it to my production application, but I don't to simply write all the modifications again. How could I do that? I just need to copy it from : /usr/local/lib/python3.5/dist-packages/djutils And overwrite at my production application virtual env? There are any other easy ways to do that? Cheers, Pedro Gabriel. -
how to get an object according to parent table field in django ORM?
I have a table named Profile with below code: class Profile(models.Model): user = models.OneToOneField('auth_user', related_name='profile', verbose_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30, verbose_name='name') family = models.CharField(max_length=50, verbose_name='family') and the User table is like below: class User(models.Model): id = models.IntegerField(primary_key=True) username = models.CharField(max_lenght=255) password = models.CharField(max_lenght=255) I want to get profiles with username with this function: def get_profile(request, username): # some codes how can i get a profile with username? what should i write in get_profile function? tanx -
Checking Django settings with a function
I'm new to working with Python and Django, and I'm having trouble figuring out how to use a function to check if a certain configuration has been set for one of the apps within a project. Here's an example of the setup: from django.conf import settings from sites.general import ( SITE1_ID, SITE2_ID, SITE3_ID ) def current_item(): return { SITE1_ID: 'sitetext1', SITE2_ID: 'sitetext2', SITE3_ID: 'sitetext3', }[settings.SITE_ID] I want to create a function that checks to see if the current site being served matches one of the strings from current_item. So I was thinking of doing something like: def is_SITE1(): return current_item == 'sitetext1' Although I'm stumped over what the right format is, since this function isn't registering the right site. -
retrieving all Django HTML variables
I'm looking to extract all variables in a html template in django such as {{variable1}} and place them into a list. This list will be used to query a database for the corresponding values. so variable1 could correspond to Home Page etc. and I would pass back {'variable1' : 'Home Page'} Is there something built in or a third party application to do this? The closest thing I found was this in Django Docs. using Django 1.11, python 3.x -
Tastypie: getting "AttributeError: 'NoneType' object has no attribute '_clone'" Error
When I try to issue a GET to my model (using TastyPie), I get the following traceback error: File "/Library/Python/2.7/site-packages/tastypie/resources.py", line 2141, in get_object_list return self._meta.queryset._clone() AttributeError: 'NoneType' object has no attribute '_clone' Below is my resources.py file for the relevant Model. from tastypie.resources import ModelResource from swtr.models import Com class ComResource(ModelResource): class Meta: query_set = Com.objects.all() resource_name = 'com' object_class = none I'm particularly confused given that Com.objects.all() returns at least one record that I created and saved within the python shell. So I'm not sure why the queryset is being returned as a "Nonetype." -
Many-to-many relationship as list
I have a project where I have a PlayerModel and a GameModel. A player can take part in multiple games and a game can be played with a variable number of players. Thus, it seems obvious to me that this is exactly a many-to-many relationship. However, in a game I should also store the score of each player. Thus, my first idea would be to design the Game table with two fields, namely a list of player ids and a list (same size) of scores (one for each player taking part in the game). Thus, I am wondering if my idea is the optimal one in my case. -
I need to fill the second part of the form that i created in a model using the username from the first part?
class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=20,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) experience = models.IntegerField(default=0) skills = models.CharField(max_length=200, default='') emp_rating = models.FloatField(default=0) this is my model i want to fill this form using an html page. Can somebody tell me how to import user name from users from django admin. -
Setting a field on a model not using a form
I have a site that when a user clicks a bootstrap glyphicon link they should be redirected to another page, this page is of the same glyphicon but in a green color to make it seem as if by pressing the link they activated the button. During this trasition I want the field active on my Profile to go from False to True. I have the following code: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) university = models.CharField(max_length=30, blank=True) ROLE = ( ('CUSTOMER', 'User'), # (value to be set on model, human readable value) ('WORKER', 'Worker'), ) role = models.CharField(max_length = 20, choices = ROLE, default = 'USER') active = models.BooleanField(default = False) views.py def active(request): request.user.profile.active = True; return render(request, 'core/customer_active.html', {'user': request.user}) home.html: <a href="{% url 'active' %}"><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span></href> I am not sure why request.user.profile.active = True; does not update the state of the field, what will? -
Sum and Count in nested foreign key relationship?
I have the following models: class Building(): class Floor(): building = models.ForeignKey("Building") class Suite(): floor = models.ForeignKey("Floor") area = models.FloatField() available = models.BooleanField() In the serializer for Building, across the whole building, I would like to count 'available' suites sum 'available' suites 'area' fields I'm pretty sure that I can sum area of a list of suites like this: models.Suite.objects.filter(Q(available=True)).aggregate(Sum('area')) I don't know how to nest this so that I can query the data for the entire building... -
How to cancel celery chain from inside task (request.chain, request.callbacks are missing)
First S/O question! I know this has been partly covered in some other S/O threads but I haven't found a working solution based on related issues so far. I have a celery chain i'm calling like so: result = chain(do_one_search.s(user_id) | do_another_search.s() | and_now_score.s() | and_another_task.s() | order_product.s()).apply_async(expires=10, retry=True) Where each task is set up like so: @shared_task(bind=True, max_retries=3) def do_one_search(self, user_id): user = User.objects.get(user_id=user_id) user.do_one_search_worker_id = current_task.request.id user.save() if user.passes_a_check: some_util = SomeUtil() result = some_util.search_util(user_id) if user.fails_a_check_after_util_runs: revoke(current_task.request.id, terminate=True) # this doesn't work self.request.chain = self.request.callbacks = None # this doesn't work else: return guid else: self.request.chain = self.request.callbacks = None # yup, doesn't work. So revoke isn't working — the next task in the chain runs anyway. Setting self.request.chain/callbacks to None is also not working. I can't access anything in the chain or callbacks on the self.request object -- they both return empty. I thought it might be a Celery version syntax issue and tried self.request.chain[:] = [] and that throws an error (NoneType). I have also raised an exception in the fails_a_check_after_util_runs block to make sure the task ID is accessible via current_task — it is. I thought it might be that results are disabled but … -
Blogging Site architecture
I am building a blogging site in Django. Currently the architecture is as described in the image below. My Concern is if this architecture is good enough for SEO. Master template contains the dynamic meta data for the page fetched from DB. Any help will be helpful for better architecture design. -
Issues creating a nested serializer in Django Rest Framework with pre existing objects
I've been fiddling with the same code for a week now and I've been stuck on this, reading through docs, scouring stack overflow, and I can't figure out whats causing this to go wrong.... opening a new question from here since I have some newly formed issues. I'd like to make a nested serializer that returns this as the result: { "id": 1, "sender": { "id": 2, "name": "anotherUser", "email": "anotherUser@email.com" }, "recipients": [{ "id": 1, "name": "aUser", "email": "user@email.com" }], "subject": "asdf", "body": "asdf", "read": false } So here is my Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'email') extra_kwargs = { 'id': { 'validators': [UnicodeUsernameValidator()], } } class MessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) recipients = UserSerializer(many=True,read_only=True) class Meta: model = Message fields = ('id', 'subject', 'body', 'read', 'sender', 'recipients') def create(self, validated_data): sender_data = validated_data.pop('sender') recipient_data = validated_data.pop('recipients') message = Message.objects.create(**validated_data) for user in recipient_data: user= User.objects.get(id=user['id']) message.recipients.save(user) for user in sender_data: user= User.objects.get(id=user['id']) message.sender.save(user) return message And here is my Models.py class User(models.Model): # TODO Make user idNum a UUIDField id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) email = models.CharField(max_length=75) def __str__(self): return self.name class Message(models.Model): # TODO make message id a UUIDField id … -
Django BaseCommand works locally but does not work on Amazon AWS EB
So, I am in the process of deploying a Django website using Amazon AWS EB + RDS database. It is all working fine except from a script that I have that is in charge of populating the database programmatically. I managed to have it running locally following this very nice and short tutorial: http://eli.thegreenplace.net/2014/02/15/programmatically-populating-a-django-database So locally it works as it is supposed to. My problem comes when I run this script on my amazon AWS EB (both with cron or manually with my env activated). I get this error message: ''' Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/opt/python/run/venv/local/lib64/python3.4/site-packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/python/current/app/BetzCenter/manage.py", line 22, in execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File … -
Is it possible for a function to reference the class on which it's called?
I have some models defined in Django such as these: class Post(models.Model): text = models.CharField(max_length=50) class Thread(models.Model): title = models.CharField(max_length=50) And I would like to have an external function that, called inside either of these classes, does something related to the class on which it was called. For example, a ListAll() function that, called inside Post(), lists all Post objects, but called inside Thread, lists all Thread objects. How would I do this? I've seen replies using __this__ but apparently that references specific class instances, which confuses me a little. Thank you. -
Django admin show __str__ value in name
I have a many to many field like this: class Retailer(models.Model): name = models.CharField(max_length=100, db_index=True) city_gps = models.ManyToManyField(City, blank=True, related_name='retailers', db_index=True) def __str__(self): retailer_city = "" if self.city_gps: retailer_city = self.city_gps.all().first().name return slugify(self.name) + slugify(retailer_city) I would like the admin to show a combination of the name and all related cities. However, when I set the admin to show this field like this: class RetailerAdmin(admin.ModelAdmin): search_fields = ['name'] list_display = ['name', 'city_gps', 'icon_tag', 'logo_tag', 'header_tag'] I get the error: : (admin.E109) The value of 'list_display[1]' must not be a ManyToManyField. So, how can I solve this? Is there a way to show the value of the __str__ method in the the admin? -
OneToOne field in a django modelform
I have a OneToOne field corresponding to a user (user_id), and in my avatar upload form I get a drop down list of all users to select one, but I want django to fill it with the current logged in user. Also, when submitting the form, for some users I get this message "Profile with this User already exists." For the first problem I think that inline-formsets are the solution, but I don't know how to apply this to my form. I have no clue about the second problem. I am creating the Profile with a signal every time a new user is created, and I don't know how to just update it. I'm new to django. Here is the code for my model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar_img = models.ImageField(upload_to='avatars', blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The form: from django import forms from profiles.models import Profile class AvatarForm(forms.ModelForm): class Meta: model = Profile fields = ('user', 'avatar_img', ) And the view: from django.shortcuts import render, redirect from profiles.forms import … -
Conditional Expression on multiple models
Background: My customer's shop has Internet wifi for customer and also his staff. Shop owner would like to visualize the heatmap of his shop in order to arrange the desk and furniture for sake of convinient. Schema: https://gist.github.com/elcolie/7bb56c286afacadff63eccae94bda713 Goal: 1. I want to determine mac address to be a pin_value Constraints: 1. One mac can has many imc(username). Public computer serves many customer 2. One imc can has many pin_value. Customer got promote his pin 3. imc does not need to has pin_value. Staff account has no pin_value 4. mac does not need to has imc. May be somebody their just passing by without turn off his wifi Question: How do you use conditional expression to do single query and get mac:pin_value? My poor solution is brute-force search which is very slow. Location model has record per day is about 100k rows.