Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Categories and sub-categories in django
I have an entity of Products, category and sub-category. A category can have many products and also a category can have many sub-categories. For example a product called Iphone-4 can fall on smart phone subcategories of Electronics & Gadgets Category. Similiary samsung product can fall on same smart-phone sub-categories of Electronics&Gadgets Category. How could i show this relation effectively? Here is what i did class Category(models.Model): name = models.CharField(max_length=80, null=True) parent = models.ForeignKey('self', blank=True, null=True, related_name="children") class Meta: unique_together = ('parent',) verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False) category = models.ForeignKey(Category) company = models.ForeignKey(Company, related_name="company_product") name = models.CharField(max_length=200, null=True) model = models.CharField(max_length=100, blank=True, null=True) specification = models.TextField(null=True, blank=True) price = models.PositiveIntegerField(default=0) This way in my admin, the categories and sub-categories are shown so vaguely. Category Electronics & Gadgets is shown multiple times. It is shown as per the number of sub-category that falls under this category. Is this expected behavior or has to handle this other effective way? -
pls help on the exception resolving in django payment gateway
Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/usr/local/lib/python2.7/dist-packages/pip/utils/inienter code heret.py", line 267, in renames shutil.move(old, new) File "/usr/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/usr/local/bin/django-admin' -
Django's analog of SQL "INNER DJOIN"
#models.py # class Students(models.Model): StudentID = models.IntegerField(primary_key=True) FIO = models.CharField(max_length=50) StudGroup = models.CharField(max_length=10) NYear = models.IntegerField() class Phone(models.Model): Code = models.AutoField(primary_key=True) StudentID = models.ForeignKey(Students) Phone = models.BigIntegerField() #views.py # def show_all(reqest): all_students = Students.objects.all() return render_to_response('demosite/index.html', {'All_students': all_students}) This code is working normally. Now my view returning this request: SELECT * FROM Students But variable all_students should contain data from 2 tables. How do i get django to run this request: SELECT Students.FIO, Phone.Phone FROM Students INNER DJOIN Phone ON Students.StudentID = Phone.StudentID -
Django - How can i set a value in the settings files from database?
(first of all sorry for my bad english) i need to know if exist any way to set some values in the settings files using some data stored in the database. for example the Mail config EMAIL_HOST = '' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 EMAIL_USE_TLS = True i like to fill that variables using the data that i save in the model that i have for settings in the Company App. but like the settings files are readed before the server starts then i don't know if exist any way to do this. hope you can understand me. Thanks! -
Accessing a mailing list from python
I need to know if there is any way to get mailing lists assigned to an email account on an external server, from python. That is to have access from the code to the mailing lists created in the server \ r for that account -
When to create a new app within a Django project structure?
I have seen other questions on stackoverflow (When to create a new app (with startapp) in Django?) and read some slides on the topic but still am a little confused on when to create a new app in a Django project? I am coming over from a MEAN stack and I am new to Django. If I want to create a web application with the following four main features: -Register -Login -Chat with other users -Upload files Will these be 4 separate apps with their own views.py, urls.py, etc.? Or do I create 1 app and they share app files? It seems that 'apps' in Django projects are described as reusable modules, but these features would only be used once in my whole web application so they would not be reusable? If I wanted to build two completely separate websites, do I create 2 separate Django projects or 1 project with separate apps inside of it and would reuse an app such as registration? Just trying to wrap my ahead around how to structure this. Below is from Django's poll tutorial: Projects vs. apps What’s the difference between a project and an app? An app is a Web application that … -
Get user object from token string in DRF?
I have a token string from Django REST Framework's TokenAuthentication. I need to get the corresponding user object. How would I go about doing this? -
Proper model relationship for Player and Prizes?
I seem to have a mental impediment when it comes to abstracting model relationships. I want to have prizes available to players. Not all players have prizes, but a list should be available if needed. This is what I have so far: class Prize(models.Model): player = models.ForeignKey(Profile, related_name="gifts", null=True, blank=True) I should be able to do Profile.prizes and get a list if any exists, but ... a) this is probably the wrong relationship b) this is probably backwards... I just need some slight adjustment to get back on track here. Thanks. -
Django QuerySet: Figure Out Model Attribute Trend Between 5 Returned
notifications = DeviceNotification.objects.all() for n in notifications: time_period = n.time_period logs = DeviceLog.objects.all()[:time_period] for l in logs: print(l.celsius) I'm trying to wrap my head around how I would discover the temperature "trend" or "spread" between the object attributes (lets use celsius) returned. Basically, I want to be able to tell if the temperature has risen by a certain amount, or dropped by a certain amount... for example: if celsius has increased by 2 degrees within the past 5 hours I'm not sure if this can be done by way of a filter or if I'll have to add each celsius value to an array and compare the array with abs or something similar. -
'REGISTRATION_AUTO_LOGIN = True' doesn't log user in upon clicking on activation link in Django Registration Redux
I have followed the Django Registration Redux docs to implement a login system where the user receives an activation link via email. According to the docs this setting automatically logs user in when clicking the link. REGISTRATION_AUTO_LOGIN = True However, it doesn't seem to work. These are the Redux settins I have: #Django-Registeration-Redux variables REGISTRATION_AUTO_LOGIN = True REGISTRATION = True LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/' ACCOUNT_ACTIVATION_DAYS = 7 SITE_ID=1 This is the project's url.py: urlpatterns = [ url(r'^', include('<proj_name>.urls')), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.default.urls')), ] -
Dango view function to create a post to the database
from django.db import models from django.contrib.auth.models import User class Paper(models.Model): title = models.CharField(max_length=255, null=False) abstract = models.TextField(null=False) keywords = models.TextField(null=False) class Rate(models.Model): user_id = models.ForeignKey(User) paper_id = models.ForeignKey(Paper) isLike = models.BooleanField() created = models.DateTimeField(auto_now_add=True) I have the following models in Django. And I am unsure how to write a function in views that create a Rate when the Button URL is triggered. isLike should be set as True if the user rated the paper or False if they did not. Thanks you For your assistance. -
NoReverseMatch when trying to access view from template
I am getting a NoReverseMatch error for the following: <a href ="{% url 'mainapp:secondaryapp:generateCSV' file_ids=fileids %}">Hello</a> Where I passed a string fileids from my view to my template when rendering. Reverse for 'generateCSV' with arguments '()' and keyword arguments '{'file_ids': '11111111_22222222'}' not found. 1 pattern(s) tried: ['mainapp/secondaryapp/generateCSV/(?P[\d{8,20}]+\_*)/$'] My mainapp/urls.py is: from django.conf.urls import url, include from mainapp import views urlpatterns = [ ... url(r'^secondaryapp/', include('secondaryapp.urls', namespace="secondaryapp")), ] and secondaryapp/urls.py is: from django.conf.urls import url from search import views urlpatterns = [ url(r'^$', views.secondaryapp.as_view(), name='secondaryapp'), url(r'^generateCSV/(?P<file_ids>[\d{8,20}]+\_*)/$', views.generateCSV, name='generateCSV'), ] generateCSV is a functional view, and secondaryapp is the name of the class-based view. I am rendering the template within the class based view, and attempting to call the functional view with the parameter fileids. If I simply hard-code the url as follows: <a href = "generateCSV/{{fileids}}/"> Everything works as expected. Thanks very much for your time reading and for any help you can give me! -
If a value is in the 2nd slot of a 2-length tuple
I've got a tuple like this: CATEGORY_CHOICES = ( ('1', 'first'), ('2', 'second'), ('3', 'third'), ('4', 'fourth'), ('5', '5th'), ('6', 'sixth'), ('7', 'seventh') ) If a value is in the 2nd slot of the tuple (first, second etc..) do nothing. But if it isn't, change it to an empty string: via = some_string for a, b in CATEGORY_CHOICES: if via == b: break So i've done the first bit (check to see if via equals one of the b values), but I'm not sure what to do once via has gone through all the b values and doesn't equal any of them. At that point I want assign an empty string to via. Any idea? -
Post commit, execute function on all instances of Django - PostgreSQL
We're working on caching bits of our Django system for the most egregious RPCs and have a bit of a conundrum when scaling to a production environment. We use a NGINX and uWSGI setup with multiple Django instances. We don't actually use the web font end much. Instead we've adopted the JSONRPC API for linking into applications and python packages. Currently, we're using something that resembles an augmented version of python memoized in order to hang on to RPC results for a given function however, when we wish to clear the cache results due to a new row being added/changed which would result in different results, that becomes challenging when we have so many instances of Django running. @rpcmethod(name="foo.bar", ...) def bar(request, **kwargs): return _pvt_rpc_func(request, **kwargs) @use_rpc_cache def _pvt_rpc_func(request, **kwargs): # ... Work with data that may change #... def _on_data_changed(...): _pvt_rpc_func.reset() The function itself works great and in a development world, where we only utilize once instance, it works great. The trouble comes in on the production end. With every instance holding a cache, we have to invalidate all of them once a part of the data becomes "dirty" My research has led me to a couple ideas: Using … -
Erratic behavior of Django with environment string
My settings.py has this: DEBUG = os.environ.get('MY_VAR', True) print(DEBUG) I set MY_VAR from command line in one of the following ways, doesn't matter which, outcome is the same: export MY_VAR='False' export MY_VAR=False When I start my server... I am outputted: False False Performing system checks... System check identified no issues (0 silenced). May 26, 2017 - 17:50:44 Django version 1.11, using settings 'my_app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, the application will always run in debug mode. I know that because of the yellow error screens I get along with the indication at the bottom that the app is in debug mode. It is in debug mode Unless I explicitly define this: DEBUG = False I have no idea on even how to begin explaining this. I need my application to decide to run in debug mode or not based on an environment string, not explicit defining in settings.py. What am I doing wrong? -
Django get field from ForwardManyToOne Descriptor object
I've got two models here: class Organization(models.Model): name = models.CharField() website = models.URLField() etc. def __str__(self): return name def __unicode__(self): return name Class OrgDetail(models.Model): org = models.ForeignKey(Organization) detail_1 = models.CharField() detail_2 = models.CharField() etc. I am using generic ListViews to navigate from the organization to the detail entries. class OrganizationListView(ListView): model = Organization class OrgDetailListView(ListView): model = Organization What I want now is to add a function (or do something else) to the second view that allows me to display the name of the organization linked to the orgdetail entity via a Foreign Key field. Right now I've got: def get_context_data(self, **kwargs): context = super(OrgDetailListView, self).get_context_data(**kwargs) context['name'] = OrgDetail.org print(context) return context however this just gives me < django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x03592B50 > rather than the name of the name of the organization. I'm new to Django and have been banging my head against the wall for hours on this. I'm trying to build a web-based data entry platform. The OrgDetails data points cannot be added to the Organization model as I want to see year-over-year changes for the organization. Anyway, feel like I've just got a fundamental lack of understanding of some basic principal. Please help. <3 -
Django 1.11 OuterRef generating invalid Postgres
I have a model named Brand with a field named "name", so this works fine: brands = Brand.objects.annotate(as_string=models.functions.Concat('name',models.Value("''"))) I have a model named Item with a foreign key to Brand. The following does NOT work: annotated_brands = brands.filter(pk=models.OuterRef('brand')) Item.objects.annotate(brand_string=models.Subquery(annotated_brands.values('as_string'))) Specifically, I get a ProgrammingError: missing FROM-clause entry for table "policeinventory_item" LINE 1: ... FROM "PoliceInventory_brand" U0 WHERE U0."id" = (PoliceInve... This is born out when I inspect the SQL query. Here is the broken query: 'SELECT "PoliceInventory_item"."id", "PoliceInventory_item"."_created", "PoliceInventory_item"."_created_by_id", "PoliceInventory_item"."_last_updated", "PoliceInventory_item"."_last_updated_by_id", "PoliceInventory_item"."brand_id", "PoliceInventory_item"."type", (SELECT CONCAT(U0."name", \'\') AS "as_string" FROM "PoliceInventory_brand" U0 WHERE U0."id" = (PoliceInventory_item."brand_id") ORDER BY U0."_created" DESC) AS "brand_string" FROM "PoliceInventory_item" ORDER BY "PoliceInventory_item"."_created" DESC' Note how the nested id comparison is performed with PoliceInventory, NOT "PoliceInventory" as it is referred to everywhere else. The following query works as expected: 'SELECT "PoliceInventory_item"."id", "PoliceInventory_item"."_created", "PoliceInventory_item"."_created_by_id", "PoliceInventory_item"."_last_updated", "PoliceInventory_item"."_last_updated_by_id", "PoliceInventory_item"."brand_id", "PoliceInventory_item"."type", (SELECT CONCAT(U0."name", \'\') AS "as_string" FROM "PoliceInventory_brand" U0 WHERE U0."id" = ("PoliceInventory_item"."brand_id") ORDER BY U0."_created" DESC) AS "brand_string" FROM "PoliceInventory_item" ORDER BY "PoliceInventory_item"."_created" DESC' The problem seems pretty clearly to be OuterRef incorrectly failing to use the same table reference as the outer query, resulting in a mismatch. Does anyone know how I can persuade OuterRef to behave correctly? -
Django - trying to concetinate with email
The goal is to send email with the current, logged in, users association name like so: asoc_name@mail.com The error i get is: The annotation 'email' conflicts with a field on the model. I've tried changing field and other solutions with no luck. Really appreciate your help, folks! Django: 1.10 Python: 3.6 views.py class mailPost(FormView): success_url = '.' form_class = mailHandler template_name = 'post/post.html' def form_valid(self, form): messages.add_message(self.request, messages.SUCCESS, 'Email Sent!') return super(mailPost, self).form_valid(form) def form_invalid(self, form): messages.add_message(self.request, messages.WARNING, 'Email not sent. Please try again.') return super(mailPost, self).form_invalid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): sender = Association.objects.filter(asoc_name=self.request.user.association).annotate(email=Concat('asoc_name', Value('@mail.com'))) receiver = form.cleaned_data.get('receiver') subject = form.cleaned_data.get('subject') message = form.cleaned_data.get('message') time = datetime.now() asoc_pk = Association.objects.filter(asoc_name=self.request.user.association) asoc = Association.objects.get(id=asoc_pk) Email.objects.create( sender=sender, receiver=receiver, subject=subject, message=message, association=asoc, sentTime=time ) msg = EmailMultiAlternatives(subject, message, sender, [receiver]) msg.send() return self.form_valid(form) else: return self.form_invalid(form) models.py class Email(models.Model): sender = models.CharField(max_length=254) sentTime = models.DateTimeField(auto_now_add=True, blank=False) subject = models.CharField(max_length=254) receiver = models.CharField(max_length=254) cc = models.CharField(max_length=254) bcc = models.CharField(max_length=254) message = models.TextField() association = models.ForeignKey(Association) class Meta: db_table = 'Email' class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True, unique=True) class Meta: db_table = 'Association' -
What would be the right architecture between django and multiple charts (D3.js)?
I have a template: dashboard.html which has multiple blocks. Each block relies on a chart in d3.js. For each chart, I have implemented two urls: One that extends my "base" template i.e. dashboard.html and the other url as an api to return only data as JSON. For example, for the chart i: urlpatterns = [ url(r'^chart_i$', chart_i), url(r'^api/get_data_chart_i', get_data_chart_i,name='get_data_chart_i'), ] I am struggling to put everything together. I mean I want to have "something" that triggers all views during the same process. Do I have to create a view that encompasses all views. If so, how do we build such a view? Or is it possible to create an url that call dasboard.html and trigger my views? What do you suggest? Many thanks in advance for your help Gilles -
Django template namespace
I read that for every app of my INSTALLED_APPS in settings.py, Django will look for a templates subdirectory. But I'm a little confused. For instance, when creating my HTML templates in the initial project below: myproject/ manage.py myapp/ __init__.py settings.py urls.py wsgi.py templates/ Should I simply create a template subdirectory within the myapp directory and put my HTML files inside? -
how to pass the an authenticated user to forms.py in django
I have a django app with which every registered user can create categories. For the authentication I am using django-all-auth. My models.py looks like this: class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) create_date = models.DateTimeField('date added', auto_now_add=True) modify_date = models.DateTimeField('date modified', default=timezone.now) class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=200, unique=True) create_date = models.DateTimeField('date added', auto_now_add=True) modify_date = models.DateTimeField('date modified', default=timezone.now) On the index page the user can see the created categories and create new ones. The views.py: def CategoryView(request): user = 0 if request.user.is_authenticated(): user = request.user form = CategoryNameForm() form.user = user context = { 'categories': Category.objects.all(), 'form': form, 'user':user, } if request.method == 'POST': form = CategoryNameForm(request.POST) form.user = user if form.is_valid(): form.save() return render(request, 'myapp/index.html',context) forms.py: class CategoryNameForm(forms.ModelForm): class Meta: model = Category fields = ('name',) The authentication works. So I was thinking to just put pass the user field into the form : class CategoryNameForm(forms.ModelForm): class Meta: model = Category fields = ('name','user',) hide it and then, just select it via JS since the user is in the context. I was just wondering if there is an easier way. This form.user = user for some … -
Override serializer delete method in Django RF
I have a serializer that inherits from the django rest framework serializer ModelSerializer. To overwrite the create method, I can redefine create. To redefine the update method, I redefine update. I'm looking through the code though and can't find the method to overwrite for deletion. I need to do this in the serializer so I can grab the deleting user. Any thoughts would be appreciated! -
Django error while trying to create custom model class
I started organizing my models in a package as specified here : https://docs.djangoproject.com/en/1.11/topics/db/models/#organizing-models-in-a-package I'm using a legacy Oracle database I also created a module containing some extensions/inheritances of the Model class This is my structure : models/ __init__.py geo_classes.py tables.py The error is the following : django.db.utils.DatabaseError: ORA-00904: "TABLE_NAME"."TABLECLASS_PTR_ID": invalid identifier I couldn't find anything online about this PTR_ID it is trying to catch, maybe I missed something about extending base Models? Files (only the important parts) : geo_classes.py : from django.db import models class EsriTable(models.Model): objectid = models.BigIntegerField(unique=True, editable=False, verbose_name='OBJECTID') class TableClass(EsriTable): cod = models.BigIntegerField(primary_key=True) def __str__(self): return str(self.cod) tables.py : from .geo_classes import TableClass from django.db import models class MyClass(TableClass): #Fields name = models.CharField(max_length=50) #Keys #Relations class Meta: managed = False db_table = 'TABLE_NAME' -
Uploading 2 single files on a form using separate inputs: Django
I'm trying to build an application that asks users to upload 2 different pdf files, each from a separate input button/area. I'm new to Django and through reading the documentation a bunch of times I've gotten a few things to work. Using <form method="post" enctype="multipart/form-data"> I was able to get 2 fields for input which look something like this: App Screenshot of 2 input areas. However, when I click the select button in either case and select the file and click 'Upload', The same 2 files show up in both input areas. I've experimented with this alot and can't seem to find any resources that attempt to solve my problems. Quick note: I know there are ways to upload multiple files in a single input area, but I don't want to do that. I want to specifically have 2 different input areas as a design decision. I'm not sure if this even close to the right approach or if there are better tools for handling this type of situation. Below are chunks of the code I've written. If anyone could give me advice on how to better approach this problem or tell me how to fix my code it would … -
Django rest framework jwt and custom authentication backend
I have a custom user model and have created a custom authentication backend. I am using django rest framework, and django rest framework jwt for token authentication. User model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) mobile = models.IntegerField(unique=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'mobile'] Auth backend: class EmailOrMobileAuthBackend(object): def authenticate(self, username=None, password=None): try: user = get_user_model().objects.get(email=username) if user.check_password(password): return user except User.DoesNotExist: if username.isdigit(): try: user = get_user_model().objects.get(mobile=username) if user.check_password(password): return user except User.DoesNotExist: return None else: return None def get_user(self, user_id): try: return get_user_model().objects.get(pk=user_id) except User.DoesNotExist: return None And have added in the settings.py: AUTHENTICATION_BACKENDS = ('accounts.email_mobile_auth_backend.EmailOrMobileAuthBackend',) While to log in to django admin site, both the email and mobile number works fine in authenticating the user. However, when I try get the token for the user using django rest framework jwt, I get an error: curl -X POST -d "email=admin@gmail.com&password=123123" http://localhost/api-token-auth/ "non_field_errors": [ "Unable to log in with provided credentials." ] What am I missing? Why is it that its working while loggin to the django admin site, but get error when getting token with …