Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get form validation error in Django view (not template)
How does one get the error string in a view() in cases when the form is invalid? form['field'].errors gives an html formatted string of the error. dict(form.errors) returns a nice dictionary, but dict(form.errors)['field'] still returns an html formatted string. One needs to parse the string to extract the error. Is there an inbuilt way to just get the error string? -
Django views.py invalid syntax
I want to send email to multiple recipients in Django, using SendGrid. In my views.py file I have this and it works: data = { "personalizations": [ { "to": [ {"email": "address@example.com"}, {"email": "address2@example.com"}, ], "subject": "New message } ], "from": { "email": email }, "content": [ { "type": "text/plain", "value": message } ] } But I want to add addresses from loop. So, I use: "to": [ for address in addresses: {"email": address}, ], and I get the following error: for address in addresses: ^ SyntaxError: invalid syntax What is the correct syntax? -
Django: Set initial Value with a Passed Variable
I am using Django and want to pass a variable from a view to set an initial value within a form. I have the following view: def change_chosenCharity(request): charityid=12 form = updateCharity(charityid) return render(request, 'meta/changechosencharity.html', {'form': form}) With the following form: class updateCharity(BootstrapForm): currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None,widget=forms.Select(attrs={"class": "select-format"})) currentCharities.label = "Charity Options" currentCharities.intial = charityid Which produces the following error: name 'charityid' is not defined. I get that it is not defined within the form but I have tried various options to define it all without success. Any help is appreciated. -
Tastypie: Is there a way to invalidate Cache after resource Update?
I have a Django (1.8.17) app, and I am using Tastypie (0.13.3) as REST API Framework. I have some very simple resources, and I use SimpleCache to cache them for 15 minutes. from tastypie.resources import ModelResource from my_app.models import MyModel from tastypie.cache import SimpleCache class MyModelResource(ModelResource): cache = SimpleCache(timeout=900) class Meta: queryset = MyModel.objects.all() allowed_methods = ['get'] The problem: When I update the Resource by a PUT request, the resource gets updates in DataBase, but doesn't get invalidated from cache, so I continue to get the old data for 15 minutes, which is inconvenient, I would like that when the resource get updated, it will be fetched from DB and cached again. Is there someone who faced the same issue ? -
File "retrain.py", line 68, in <module> import tensorflow as tf ImportError: No module named tensorflow
I am a beginner in tensorflow and i have a problem I install ubuntu 16.4, tensorflow 0.9, python 3.5 I want to train an Image Classifier with TensorFlow but i get this error please any one can help me. $ python retrain.py \ --bottleneck_dir=tf_files/bottlenecks \ --model_dir=tf_files/inception \ --output_graph=tf_files/retrained_graph.pb \ --output_labels=tf_files/retrained_labels.txt \ --image_dir tf_files/blood_cells Traceback (most recent call last): File "retrain.py", line 68, in import tensorflow as tf ImportError: No module named tensorflow -
Django Channels or Tornado for a socket based connection
I am working on a project where I have a list of Petrol stations viewable via the Django Rest API showing Station data i.e. the availability of Fuel and Capacity. I have also developed a microcontroller to detect fuel levels. Now the issue is that this data will be sent to my web backend every 10mins (could be reduced to 1min in future), updating the station model via the rest api. I'm not sure how to handle this. Would something like Django channels be useful in this case? The server uses a mixture of C and Java to send data. I need it to be a scalable solution as there is a potential of many stations being created. -
How to insert and position images in a PagedownWidget
I'm implementing a blog. To make it more user friendly I'm using the django-pagedown library and, in particular, the PagedownWidget() for inserting the content of a posts by using graphical control elements. forms.py class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget(show_preview=False)) publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "title", "content", "image", "draft", "publish" ] My problem is that the PagedownWidget() allows to insert and position images in the text only if already hosted online. Is there a way to add the functionality to choose images directly from user local drive? If not, could you suggest the easiest way to do it? Thank you all in advance. -
Django UpdateView: Object to update has no values
I'd like to update an object with generic view updateview. The problem arises when I edit an object. Instead of reaching a prefilled form, I reach a blank form. My template for this: {% extends 'base.html' %} {% block content %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-danger" type="submit" value="Update" /> <a href="{% url 'display_targetbehavior' %}" class="btn btn-default">Take me back</a> </form> </div> {% endblock %} In my views.py class HabitUpdate(UpdateView): model = Habit form_class = HabitForm #fields = ('title', 'trigger', 'existingroutine', 'targetbehavior', 'image') success_url = reverse_lazy('display_habits') template_name = 'habits/update_habit.html' my model: class Habit(models.Model): AFTER = 'After I' WHEN = 'When I' WHENEVER = 'Whenever I' BEFORE = 'Before I' MEANWHILE = 'Meanwhile I' TRIGGER_CHOICES = ( (AFTER, 'After I'), (WHEN, 'When I'), (WHENEVER, 'Whenever I'), (BEFORE, 'Before I'), (MEANWHILE, 'Meanwhile I'), ) title = models.CharField(max_length=200) trigger = models.CharField(max_length=15, choices=TRIGGER_CHOICES, default=AFTER) existingroutine = models.ForeignKey( 'Existingroutine', on_delete=models.SET_NULL, blank=True, null = True, ) targetbehavior = models.ForeignKey( 'Targetbehavior', on_delete=models.SET_NULL, blank=True, null = True, ) image = models.ImageField(upload_to='habit_image', blank=True) created_by = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): habitpresentation = self.title# + '\n ' + self.trigger + '\n ' + str(self.existingroutine) + '\n ' + str(self.targetbehavior) return … -
Electron needs page reload to show content
I'm new to Electron, my goal is to run a Django app within. The Django app has been compiled using PyInstaller and placed correctly within my electron project structure. My problem is that when I start electron (electron .) its blank window opens. I need to hit refresh to show to right content. I cannot get this to work such that the page is reloaded to show content during electron opening. I tried the reload() and reloadIgnoringCache() option but it doesn't help... Analysing my window webContents parameters I can see that my window initially gets currentIndex: -1 and after manually reloading currentIndex: 0 (not sure if that is relevant...). Here is the relevant part of my main.js file: app.on('ready', function() { log.info('App is ready?!....'); var openWindow = function(mainAddr){ mainWindow = new BrowserWindow({width: 1200, height: 800, backgroundColor: '#eeeeee', show:false}); mainWindow.loadURL(mainAddr); mainWindow.webContents.on('did-finish-load', function() { mainWindow.show(); }); mainWindow.webContents.session.clearCache(function() { console.log("Cache has been cleared."); }); mainWindow.webContents.reloadIgnoringCache(); mainWindow.webContents.openDevTools(); mainWindow.on('closed', function() { mainWindow = null; subpy.kill('SIGINT'); }); }; -
django blog next/previous entries
here is my code class Post_detail_View(View): def get(self,request,post_id): try: post = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost', 'videopost').get(pk=post_id) previous = self.get_previous(post_id) next_post = self.get_next(post_id) if post.type == 'standard': content = markdown.markdown(post.standardpost.content, extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) return render_to_response('post-detail.html', locals()) elif post.type == 'audio': content = markdown.markdown(post.audiopost.content, extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) return render_to_response('post-detail.html', locals()) elif post.type == 'video': content = markdown.markdown(post.videopost.content, extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) return render_to_response('post-detail.html', locals()) except: raise Http404 def get_previous(self,post_id): post_id = int(post_id) if post_id > 1: try: previous = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost','videopost').get(pk=str(post_id - 1)) if previous.type == 'quote' or previous.type == 'link': if post_id - 1 > 1: self.get_previous(str(post_id - 1)) else: return 0 else: return previous except: return 0 else: return 0 def get_next(self,post_id): post_id = int(post_id) try: next_post = Post.objects.select_related('standardpost', 'quotepost', 'linkpost', 'audiopost','videopost').get(pk=str(post_id + 1)) if next_post.type == 'quote' or next_post.type == 'link': self.get_next(str(post_id + 1)) else: return next_post except: return 0 when I debug this previous = self.get_previous(post_id) next_post = self.get_next(post_id) after one or more recursion,before return,they both have objects to return,but they will become None after return,if directly return with no recursion ,it will be ok. before return: after return: -
How to decide dynamic work flow for a set of model?
Let consider we have 3 roles, Manager, Admin, Superadmin. Sequence of transactions should happen like t1->t2->t3->t4. If any employee belongs to Manager role , his transaction should happen t1->t3->t2 If any employee belongs to Admin role , his transaction should happen t1->t2->t4 If any employee belongs to Supreadmin role , his transaction should happen t1->t2 In django how to define this dynamic workflow? So on request of employee this process should follow based on there Role. Thank you in advance. -
DRF Serializers for Models with OneToOne relationship
Given Django Models that have a OneToOne relationship, how does one setup the Django Rest Framework Serializers & Views so that to the API consumer the end-point for paying in cash and paying in cheque include the payment model and allow for all CRUD functionality? I've tried following this SO Question here but I can't seem to replicate the functionality. Models class Payment(models.Model): """ Payment Log """ merchant = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_merchant") customer = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_customer") payment_method = models.ForeignKey(PaymentMethod, on_delete=models.CASCADE) trx_amount = models.DecimalField(max_digits=10, decimal_places=3) class PaymentCash(models.Model): """ Cash payments """ payment = models.OneToOneField(Payment, on_delete=models.CASCADE, primary_key=True) date_paid = models.DateField() # Other fields class PaymentCheque(models.Model): """ Cheque deposits """ payment = models.OneToOneField(Payment, on_delete=models.CASCADE, primary_key=True) cheque_number = models.CharField(max_length=50) # Other fields Sample View class PaymentCashViewSet(ListCreateRetrieveUpdateViewSet): """ Cash payment view """ queryset = PaymentCash.objects.all() serializer_class = PaymentCashSerializer permission_classes = (IsAuthenticated, HasPermission) Using: Django==1.10.2 & djangorestframework==3.5.1 -
Django template does not exist error
I am new to django and I am working on a new application. I have started using templates just now. When i load the web page it shows template does not exist error even though the template exists at the path specified in the TEMPLATE_DIRS -
Django: Cannot create User inside ipython shell
I am trying to import Django User model in ipython inside virtual environment. I have tried the following code from django.contrib.auth.models import User It resulted in the following error AppRegistryNotReady: Apps aren't loaded yet. Then from this answer, I have setup inside the shell and tried the following code. from django.conf import settings User = settings.AUTH_USER_MODEL User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') This resulted in AttributeError: 'str' object has no attribute 'objects' . How can I create a user inside ipython shell? I am using Django 1.10.6, ipython 6.0.0 and djangorestframework 3.6.2 -
Django 1.9.0:Page not found 404 Django media files
I am getting the error code 404 for the django media files. My setting,py is as follows: MEDIA_ROOT = os.path.join(SETTINGS_PATH, 'templates') MEDIA_URL = '/media/' urs.py is as follows: from django.conf.urls import patterns,include, url from django.views.static import serve from django.contrib import admin #import settings from django.conf.urls.static import static from django.conf import settings admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'timesheet_tool.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^welcome_page/', include('welcome_page.urls')), url(r'^add_status/', include('add_status.urls')), url(r'^view_status/', include('view_status.urls')), ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have also gone through other thread "Page not found 404 Django media files" but it did not help me. -
Executing Function in Django Template with button OnClick
This is a filter in my Django Templates tag. @register.filter('saving_bookmarks_db') def saving_bookmarks_db(news_data,news_source,): #this will save the data in db In my Django Template, i have one button like this <button data-toggle="modal" id="myClickButton" href="#dbModal" class="btn btn-info pull-right custom" >Bookmark</button> this is my include command, which will include modal html and save the also save the data using tag {% include "db_saving.html" with source=source data=data %} All i want to do is that, this include command execute only when the button is click but in django whenever the page is refresh, it save all the data in the DB and not the one when i click the button. -
Get string between two strings
<p>I'd like to find the string between the two paragraph tags.</p><br><p>And also this string</p> How would I get the string between the first two paragraph tags? And then, how would I get the string between the 2nd paragraph tags? -
Django: use _set for objects of model
I search and get the result: Create a list of Ids and use id__in = ids objects = Model.objects.filter(id__in=object_ids) Refer: this topic Step by step and query colors = Color.objects.filter(item__favorite__user=request.user).distinct() Refer: this topic But i want to ask about: use < _set > Ex: p = Project.Objects.filter (pk = 1) pro_app = p.Project_Application_set.all() ~> Get the list pro_app But how about: p = Project.Objects.all() pro_app = p.Project_Application_set.all() can i use _set for a list of objects? Thank you. -
How to configure Elastic IP with django app in aws?
I am building an app using django in EC2-ubuntu and i have associated Elastic ip with my instance. i have done following steps : 1. first created instance of ubuntu in ec2 free tier. 2. installed python. 3. installed pip. 4. installed django. 5. create a django project using django-admin startproject. 6. run server using these commads python manage.py runserver 0.0.0.0:80 7. created an elastic ip and associated to the instance. 8. configure security inbound settings with http 0.0.0.0:80 address. 9. able to ping my project using any browser. But the problem is when i am closing my putty session where i supplied runserver command, django project is also stopped. i did not stop it manually. Please, help me to keep on running after closing putty session as well. Thanks, Kripa Sharma -
Django server side caching of uploaded file
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using from django.shortcuts import redirect file_path = '/upload/directory/filename' return redirect(file_path) However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ? This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else). If I open the file before returning it (i.e. I do with open(absolute_file_path) as file: file.read() then the issue appears to go away! -
Template django issues
Hello i don't know what is the problem with my template. My template is decomposed into 3 types of radio buttons : Long, short, long and short When i click on each radio button a form appears. Till now everything is okay. But i want to put in the form of radio button "long and short", two accordions one is called long and the other is short. I don't know what is the problem with the code it didn't work. The code of the template: <div id="tab3" class="tab"> <nav class="accordion arrows"> <input type="radio" name="accordion" id="cb1" /> <section class="box"> <label class="box-title" for="cb1">Long</label> <label class="box-close" for="acc-close"></label> <div class="box-content"> <form action="{% url "backtest" %}" method='POST' role='form' id='form'> {% csrf_token %} {% include 'tags/parameters_form.html' %} <br /> {% include 'tags/parameters_backtest_form.html' %} <br/> {% include 'tags/parameters_filters_form.html' %} <br/> {% if user.is_authenticated %} <input type='submit' id='run' value='Run' class='btn btn-default'> {% if user.profile.is_active %} Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'> {% else %} <p>Expired account! you need to reactivate in order to save parameters.</p> {% endif %} </form> </div> </section> <input type="radio" name="accordion" id="acc-close" /> </nav> {% else %} Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting! </br> Our system … -
Django Custom User migrate on heroku
I have created a custom User model in Django. Now, I want to run my application on heroku. But I can't run migrate, code error: ValueError: Dependency on app with no migrations How can I solve this problem? Full message error File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/loader.py", line 223, in build_graph self.add_external_dependencies(key, migration) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/loader.py", line 188, in add_external_dependencies parent = self.check_key(parent, key[0]) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/migrations/loader.py", line 169, in check_key raise ValueError("Dependency on app with no migrations: %s" % key[0]) ValueError: Dependency on app with no migrations: main_site -
Run Django Server - OSError: [Errno 5] Input/output error
When I'm trying to launch the Django server with the command python3 manage.py runserver 172.16.4.89:8000 To explain quickly, I have a Raspberry Pi 3 and I'm using a IO Pi and an ADC Pi. For these, I need to use SMBus et I2C libraries. The goal of this is to control a coffee machine and I have a website to distribute a coffee and change some parameters. But I didn't change nothing and I have this error which have no sense for me : Error code I'm sorry I don't know how to indent all this code so I prefer upload the picture of the code. Thanks for your help -
Set a model field to a search result
I have a model of Teacher that creates classes. I have another model of students who take the classes but do not create them. I also have the classes model. What I a trying to do is have the student search for classes and click on a result and add it to classes they are a part in. I have the search working, but I cant get the second part working. I have my student model as a ManyToManyField because I figured a Classe should have more than one student, and the student can take part in more than one Classe. For some reason in admin, as soon as a student is added, it has them automatically taking part in all the classes created. I am trying to get the student to take part in only classes they choose, after searching for such classes. My student model: class Student(User): classe = models.ManyToManyField(Classe) school_name = models.CharField(max_length=250) My view: def add_course(request, classe_id): #c = Classe.objects.get(pk=classe_id) request.user.classe = classe_id request.user.save() return Should I have the Classe as the one defining the ManyToMany relationship with the student? Also, since I have the ManyToMany relationship with the student, I can filter course objects based on … -
Can't install Django Osx
this appears when i try to install it: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/init.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django'