Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TemplateView vs DetailView
I'm working on an app that has multiple user profile models that OneToOne field to auth.User. For a specific type of profile's dashboard, say VendorSales, is it better practice to write a DetailView that takes the VendorSales ID in the url, or to just use a TemplateView with no url pk's and reference request.user.vendorsales in the template and self.request.user.vendorsales in the context data? -
foreign key only show owner field django
I have two Model class In django restful API: class Titles(models.Model): title_links=models.CharField(max_length=500) created_by=models.ForeignKey(User,null=True) def __str__(self): return '{}'.format(self.title_links) class All(models.Model): created_by=models.ForeignKey(User,null=True) title1=models.ForeignKey(Titles,related_name='title1',blank=True,null=True,limit_choices_to={'created_by': True},) Now in All class In title1 field I want only those titles who is created_by current logged in user . Kindly help . -
Can't launch django per script (CronJob)
I would like to start a script, which is using my Django project with a python script which first starts a virtual environment. FYI The settings file has the same name as the project folder proj. I wrote some kind of a script to start the script like this #!/usr/bin/python # -*- coding: utf-8 -*- activate_this = '/home/myname/virtualenvs/proj/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys import subprocess path = '/home/myname/proj' if path not in sys.path: sys.path.append(path) subprocess.Popen(['python', '/home/myname/proj/ext_scripts/my_django_script.py'] + sys.argv[1:]) The actual script imports like this ... import time import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") django.setup() ... Which returns ImportError: No module named 'proj' -
How to add variable from request.session to each model save() in django
I developed an app in which each user can start his own project and store data. Several users can join the same project. I have created a simple model that holds data for each of these projects. The pk of these projects is added via a middleware to the users request.session object (A user can be part of many projects, but just be logged into a project one at a time.) Now my code is becoming fairly large and complex and I am very often running into problems when saving objects. Either I forget to add the project, or when displaying things I forget to filter by project_id. What would be the best way to handle this when saving objects? I wanted to override the save() on a base class for each of my objects to add the project_id, but I do not have access to the request in my models.py. People discourage sending the request object to models.py. I am also not sure if pre_save can help in any way? Any suggestions on how to handle session variables when saving objects? views.py: obj = Model(project=Project.objects.get(id=self.request.session['authority']), name=obj_name) obj.save() models.py: class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Model(models.Model): name … -
Django and Python Script Integration :(
On my site I have some buttons that when clicked I want them to launch my python script which reaches out to some of my servers and writes to a file. I see plenty of posts online that say its easy but none actually give you steps as to what needs to be done I have a basic html page and the button section looks like the below <td><a href="javascript:alert('Working on it!');"<button type="button" id="myButton1" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">DO IT</button> If someone could tell me how I can get the DO IT button to launch my .py i would be forever grateful -
Passing a message from context processor to 400 error page
I have a couple of context processors which (for example) check in the admin section if the IP address of the user is allowed. If it's not, I want to raise a PermissionDenied (or SuspiciousOperation) exception. I have already set up basic templates under a template directory in the root of the project (at the same level as manage.py): 400.html, 403.html etc. Within these templates I am using the messages framework to capture any messages sent by the context processors when a user is denied access. Despite setting messages.error(request,'You are not allowed to view the admin for this site') The messages variable is not available to me in any of the error templates. However, if I change the code so my IP address is allowed in, and navigate the admin page, all of the messages are visible. What I really want to do is pass the message when I raise the exception raise PermissionDenied('some message here') But that doesn't work with the 400 templates either, so this is why I resorted to using the messages framework. Am I doing something wrong here? Many thanks -
Django get_or_create returns MultipleObjectsReturned
I am using a model which looks like this : class Box(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) item = models.ForeignKey(Item, related_name="item", null=True) @staticmethod def instance_from_data(data): if len(data) < 2: return None the_item, created = Item.objects.get_or_create(name=data[1]) new_box, created = Box.objects.get_or_create(name=data[0], item=the_item) return new_box Here's an example set of data I'm iterating over: [ [ "Blue box", "Keyboard" ], [ "Red box", "Bottle" ], [ "Yellow box", "Swatch" ], ... ] As the static method instance_from_data is the only place I am creating Boxes, I did not expect to have the error get() returned more than one Box -- it returned 2! Does anyone know how can this be possible ? -
Any one of the field should not be null in Django
I have a post model Which allows users to post Caption(text) image video gif audio or all of them My question is what if they want to post an audio clip without caption or video without a caption or a photo without a video how do I make them post at least one thing thing Because I can't make all fields null or not null -
Django: Implementation Advice: Categories and Product Specifications
I have Product and Categories. A product can be in multiple categories and off course a Category have multiple products. The Categories can have Subcategories’ which can have Subcategories. I used a Category Model with a circular Foreign Key. Each Product can have specifications/attributes based in which Categories is. So the specifications are of the products but depends on the Categories. I can’t add the specifications as Products attributes because they depend on categories, and the user can change categories. I can’t add them as attributes per Category because the value are/can be different for each product. Also an attribute/specification can appear in multiple Categories. I want also to search for a Product filtering by attributes. I think I need a separate Attribute Model that is linked (foreign key) to both Product and Category. Also a way of “protection” in case a Product change categories, a Product and/or a Category is deleted. What is the optimal approach as flexibility and performance ? -
Get query fields from ReadOnlyModelViewSet
Tell me, please, how you can access the fields that were sent in the GET request to the ViewSet of the following form: class MyViewSet(ReadOnlyModelViewSet): http_method_names = ['get'] queryset = User.objects.all() serializer_class = MySerializer permission_classes = (AllowAny,) def list(self, request, *args, **kwargs): request.data # < attempt to access this attribute will return an empty dictionary return super().list(request, args, kwargs) -
Python Heroku app deployment "App not compatible with buildpack" error
I am trying to deploy my app in heroku, but is failing with "App not compatible with buildpack" error. I have added requirement.txt and procfile in my project, yet it is failing. remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to xyz. Heroku build log is not providing much info either: -----> App not compatible with buildpack: https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection- failure ! Push failed Can someone tell me if I am missing anything? I am trying git push method. -
Django - saving a form strips values so only the first word is saved
I am currently working on a Django project and I have run into a problem when I save a form the values get stripped down so only the first word is saved. I am quite sure that the problem is somewhere in the request.POST.get but haven't figured out how to fix it. -
Why django do not display comments?
my model : class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts') updated_by = models.ForeignKey(User, null=True, related_name='+') class Comments(models.Model): creator = models.ForeignKey(User, related_name='comment') body = models.TextField(max_length=4000) post = models.ForeignKey(Post, related_name='comment', null=True) my view: def p(request, pk): topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) return render(request, 'post.html', {'post': post, 'topic': topic}) def comments(request, pk): comment = get_object_or_404(Comments, pk=pk) return render(request, 'post.html', {'comment': comment}) my urls: url(r'^boards/(\d+)/(?P<pk>\d+)$', views.p, name='p'), url(r'^boards/(\d+)/(\d+)/$', views.comments, name='comments'), as i can understand, the problem in using primary key, in case of posts all work good, but when i try to render different models in one page it looks like that django go not like it. I tryed a lot of combinations in url pattern, but nothing that solved my problem. On post.html page all info about posts redered as well, but comments is not work -
"Toggle" manytomanyfield in Django
I have two models which simplified look like this: class Tag(models.Model): name = models.CharField(max_length=8) class Person(models.Model): tags = models.ManyToManyField(Tag, related_name='tags') I want to easily be able to toggle these tags on and off for a person, what I've been doing so far is iterating some tags that are supposed to be toggled, like: for tag in selected_tags: if person.tags.filter(pk=tag.id).exists(): person.tags.remove(tag) else: person.tags.add(tag) This does however cause lots of db queries and I'd like to be able to do it in just one query. Is there a "correct" way to do this in Django? -
Ckeditor error django
Traceback (most recent call last): File "./manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/__init__.py", line 20, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/utils/log.py", line 87, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 568, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python2.7/logging/config.py", line 711, in configure_handler klass = self.resolve(cname) File "/usr/lib/python2.7/logging/config.py", line 394, in resolve self.importer(used) File "/home/sabo/projects/iDocs/web/django/api/utils/utils.py", line 23, in <module> from main.models import EnterpriseEntry, Permission File "/home/sabo/projects/iDocs/web/django/main/models.py", line 20, in <module> from moderators.models import HackerLogin, CompanyPayment File "/home/sabo/projects/iDocs/web/django/moderators/models.py", line 4, in <module> from ckeditor.fields import RichTextField File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/fields.py", line 6, in <module> from .widgets import CKEditorWidget File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 54, in <module> class CKEditorWidget(forms.Textarea): File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 59, in CKEditorWidget class Media: File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 68, in Media static('ckeditor/ckeditor/'), File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/js_asset/js.py", line 14, in static if apps.is_installed('django.contrib.staticfiles'): File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/apps/registry.py", line 231, in is_installed self.check_apps_ready() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I cant resolve this problem. I already installed django-ckeditor, added into installed_apps in settings.py like 'ckeditor', and now when I trying to run project I saw this error, It's happened when … -
How to set a default handler in django fobi
Did anyone managed to set a default handler in django-fobi? What was the approach? I'd like to set the db_store handler as a default for all of the forms. I've tried to set defaults in models but with no success. -
When I put "Logout" button,Page not found error happens
When I put "Logout" button,Page not found error happens. I wrote in views.py like @login_required def logout_view(request): logout(request) return render(request, 'registration/accounts/top.html') in index.html <div class="container"> <ul class="top-menu"> <form name="logout" method="post" action="{% url 'accounts:logout_view' %}"> <button type="submit" class="btn btn-primary btn-lg" style="color:white;background-color: #F62459;border-style: none;">Logout</button> <input name="next" type="hidden"/> </form> </ul> </div> But I put Logout button,Page not found (404) error happens.Traceback is Page not found (404) Request Method: POST Request URL: http://localhost:8000/static/accounts/logout_view My ideal system is when I put logout button, it sends top.html. Directory is What is wrong in my code?How should I fix this? -
form error using cleaned data
I am trying to modify an app that I have found on the net in order to create surveys but I am getting an error that I do not manage to solve form.py: def save(self, commit=True): import pdb; pdb.set_trace() """ Save the response object """ # Recover an existing response from the database if any # There is only one response by logged user. response = self._get_preexisting_response() if response is None: response = super(ResponseForm, self).save(commit=False) response.survey = self.survey response.interview_uuid = self.uuid if self.user.is_authenticated(): response.user = self.user response.save() # response "raw" data as dict (for signal) data = { 'survey_id': response.survey.id, 'interview_uuid': response.interview_uuid, 'responses': [] } # create an answer object for each question and associate it with this # response. for field_name, field_value in self.cleaned_data.items(): if field_name.startswith("question_"): # warning: this way of extracting the id is very fragile and # entirely dependent on the way the question_id is encoded in # the field name in the __init__ method of this form class. q_id = int(field_name.split("_")[1]) question = Question.objects.get(pk=q_id) answer = self._get_preexisting_answer(question) if answer is None: answer = Answer(question=question) if question.type == Question.SELECT_IMAGE: value, img_src = field_value.split(":", 1) # TODO answer.body = field_value data['responses'].append((answer.question.id, answer.body)) LOGGER.debug( "Creating answer for question %d … -
django import export raises error on foreignkey to `User`
Software: Python3.6.2 Django1.11 django-import-export==0.5.1 OSX10.12.6 INSTALLED_APPS: THIRD_PARTY_APPS = [ ..., 'reversion', # django-reversion 'import_export', # django-import-export ] Requirements: 1. Model has reversion 1. Model can be able to do import 1. Each imported role has uploader as created_user, and updated_user (However, just for now I let it read from the Excel file and here it is the problem) Attempts: 1. Since 2 of the requirements will hit hard with strict meta class. Then I apply reichert solution https://github.com/etianen/django-reversion/issues/323 1. Problem: Line number: 1 - get() keywords must be strings None, 696 02, Lane, Ronald Regan, Ratíškovice, n/a, Dolichitus patagonum, admin, admin Traceback (most recent call last): File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 434, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 258, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 252, in get_instance return instance_loader.get_instance(row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/instance_loaders.py", line 33, in get_instance return self.get_queryset().get(**params) TypeError: get() keywords must be strings Models: https://gist.github.com/elcolie/98e641d57c5de3394f816a5d9b80ef13 admin.py https://gist.github.com/elcolie/081017adc7b5e2fd7a3a38b0573597c6 References: Dealing with import of foreignKeys in django-import-export django-import-export to export User model Django Import/Export to multiple Models (foreignkey) -
if condition in urls.py - dajngo
I want to check if user not loged(don't have a session) he go to login.html file and if he loged(have a session) he go to profile.html , but i want to check it at urls.py My projects Tree : manage.py url ----setting.py mr_url -----templates ---------url ------------profile.html ------------login -----------------logon.html -----views.py -----models.py -----urls.py My urls.py : from django.conf.urls import url from . import views from django.views.generic import TemplateView urlpatterns =[ url(r'^$', views.profile, name='profile'), ] How i can check set session for user or not in urls.py ???? Note : i can do it in views.py but i don't want! -
django template print either "good morning or afternoon" depending on time of day
Morning, I'm trying to create a template for an email and I'm unsure on how to get the greeting to flip between "Morning, afternoon and evening" depending on time of day that it is selected to be sent. Any ideas current template code {% if hour < 12 %} morning {% elif hour > 12 %} afternoon {% endif %} -
Django models through many to many relations
I am building an open-hard/software home automation environment based on Django, python and Arduino devices. I just wanted a small app to start diving into python but the thing has gone away once I started because this is so amazingly powerful... My main doubt here is on Django... I have a Django model that describes the general things of each of the type of devices available. class DeviceTypeModel(models.Model): Code = models.CharField(help_text='Type of the device', max_length=10,primary_key=True) ... Each of this device-types will have some communication datagrams in which they will send information to the master when queried. class DatagramModel(models.Model): DeviceType = models.ForeignKey(DeviceTypeModel,on_delete=models.CASCADE) AnItems = models.ManyToManyField(AnalogItemModel, through='ItemOrdering',blank=True) DgItems = models.ManyToManyField(DigitalItemModel,through='ItemOrdering',blank=True) In each datagram, several analog and/or digital values can be defined and ordered through an auxiliary model 'ItemOrdering': class ItemOrdering(models.Model): datagram = models.ForeignKey(DatagramModel, on_delete=models.CASCADE) AnItem = models.ForeignKey(AnalogItemModel, on_delete=models.CASCADE,blank=True,null=True) DgItem = models.ForeignKey(DigitalItemModel, on_delete=models.CASCADE,blank=True,null=True) order = models.PositiveSmallIntegerField(help_text='Position in the dataframe 1-based') Each of the items in the datagram are based on a model (shown analog, digital are fairly the same) : class AnalogItemModel(models.Model): HumanTag = models.CharField(max_length=20,unique=True) Units = models.CharField(max_length=10) This model is supposed to keep the basic information about an item. The particular info (the one particular to a particular device) such as the … -
Run string command in pymongo
I have following string command query = "{}{'_id': False}" Now I want to run above command in following code client = MongoClient('mongodb://'+host+':'+port+'/') db_col = database.split(',') database, collection = db_col[0].strip(), db_col[1].strip() collection = client[database][collection] collection = collection.find(query).limit(10) Is there any solution for that -
Function that assign image from related model to parent model ImageField
Is it possible to write a function that assigns an image from another/related model to an models.ImageField? Sorry for the bad explanation, here is an example: models.py class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) class Image(models.Model): product = models.ForeignKey(Product, related_name='images') is_featured = models.BooleanFIeld(default=1) So my intention is to write/define a function above the Product model that assigns the image from Image that is set to is_featured = True. I've been playing around and no matter what I've tried cover_image remains blank or None. Currently the function looks like this: def get_cover_image(instance): cover_image = instance.architecture.is_featured == 1 return cover_image class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) Am I completely of base here? Is what I'm trying to achieve possible? -
Model Relationship Failing, Can't Get Data in Template
I have model Profile and another model called 'Nation', and this model will take Profile and User as ForeignKeys. It's like this, class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type=models.CharField(max_length=10, choices=M_CHOICES) class Nation(models.Model): user= models.ForeignKey(User, related_name='natuser') profile = models.ForeignKey(Profile, related_name='nat_hr') ref_number = models.CharField(max_length=20, default=pm_tag) The logic here is to check for the type of user and show fields 'values' related to the user model. For this, we believe the User belongs to the Nation model, so to get his ref number, In Views, I did @login_required def profile_detail(request, username): user= get_object_or_404(User, username=username) try: the_detail= user.profile except ObjectDoesNotExist: return None in Template, after checking that the user type belongs to the Nation model, I wrote the below code to get the user ref_number but it's failing. {{the_detail.nat_hr.ref_number}} {{the_detail.user.profile.nat_hr.ref_number}} What am I missing when it comes to using related_name to get data that belongs to a model via template?