Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django GenericForeignKey group by
I have a model X with a GenericForeignKey. model Y and model Z instance attached in model X GenericForeignKey. y1 = Y.objects.create(name=y1) y2 = Y.objects.create(name=y2) z1 = Z.objects.create(name=z1) x1 = X.objects.create(content_object=y1) x2 = X.objects.create(content_object=y1) x3 = X.objects.create(content_object=z1) I want to a query that queryset result it x1 and x3(means group by content_object instance) Is there a way? -
How to schedule job fortnightly crontab
I am relatively new to Django. I want to do email notification for user. How do i send email notification to user fortnightly using crontab in django ? -
Print Search results to Web page
I'm trying to run a search on a local PC log file. The function below works fine if I run it from the CLI of my local pc. Basically the function does a search on all files in a directory. If a line in one of the files has the word "bee" in it, then that line will be printed out. What im trying to do is run the script and print out every line that has the word "bee" to the index.html file page. I would imagine the below would work, but I guess im missing something. Advice is welcomed. urls.py urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py import re import os def index(request): log_location = "C:\\folder1" for dirpath, dirnames, log_file in os.walk(log_location): for file in log_file: file = os.path.join(dirpath, file) with open(file) as open_directory: for line in open_directory: if 'bee' in line: context = line print(line) return render(request, 'testapp/index.html', context) index.html <html></html> <h1>{{line}}</h1> </html> -
Serving static files Django 1.4.22 and Apache 2.2
I've been programming a Django/Apache web server and can't figure out some things with serving static files. In my /etc/apache2/sites-available/default file, I've got the static Alias set to a directory on the computer that's not a part of the app (needing to load static images from this spot). I had all my .css files and other images in my /var/www/mysite/myapp/static directory, but relocated them to the foreign directory so the Alias call would find them. I rewrote the line to include the .css file in the HTML doc to reflect the directory's new location, and refreshing the page reflected this. However, the images in the static directory no longer display on the webpage. I still have them in the images folder, next to the .css files in the static/myapp directory, and just moved the static folder into a new location. Does anyone have any ideas why this might be? The Alias for the /static works for all the other images located in the external directory as well. I just can't get the copied images in the static directory to load now (in HTML or CSS files. This was working before the relocation.) For code snippets, I've tried (in HTML referencing … -
Django Admin No Style
I've found some extremely out-dated answers to this so I am going to ask the 2017 version. After starting a project on my server I've found that the django admin pages have no style at all. The main page (of course debug) shows style. I've checked file permissions, but it's all good. I haven't ran into this before on previous builds. Using python 3.6.1 on Ubuntu Server LTS 16.04. Any help is appreciated! -
django - limit the number of users
(sorry for my english) Only a question, exist any way to limit the number of users that can be created in a Django App? I search in a lot of places and i only find this, but i see in the repo that the last update was 3 years ago https://github.com/1stvamp/django-limit-users I don't know if exist any way in the core of django or if i have to override something! Thanks very much! -
Socket.io client continuously sends connect/disconnect events
I am trying to implement gevent-socketio into my Django app. It seems a client keeps sending connect/disconnect after accessing the page and the number of sessions keeps growing, and it finally starts raising geventwebsocket.exceptions.WebSocketError with reasons "Connection is already closed" or "socket is dead". I'm not an expert of socket.io but I feel like the client should send only one connect event per each page load. Can anyone advise me how to solve this issue? socket.io: 0.9.17 gevent-socketio: 0.3.6 django: 1.11.1 Client code <script type="text/javascript"> var socket = io.connect('/test'); socket.on('connect', function() { socket.emit('message', {data: 'connected'}); }); socket.on('disconnect', function() { socket.emit('message', {data: 'disconnected'}); }); </script> Server code(sockets.py) import logging from socketio.namespace import BaseNamespace from socketio.sdjango import namespace logger = logging.getLogger(__name__) @namespace('/test') class TestNamespace(BaseNamespace): def recv_connect(self): logger.info("### received CONNECT ###") def recv_disconnect(self): logger.info("### received DISCONNECT ###") self.disconnect(silent=False) def on_message(self, msg): logger.info(msg) Snipped logs from sockets.py 2017-05-30 23:21:29,444 [INFO] ### received CONNECT ### 2017-05-30 23:21:29,445 [INFO] {'data': 'connected'} 2017-05-30 23:21:32,965 [INFO] {'data': 'disconnected'} 2017-05-30 23:21:32,966 [INFO] ### received CONNECT ### 2017-05-30 23:21:32,967 [INFO] {'data': 'connected'} 2017-05-30 23:21:36,486 [INFO] {'data': 'disconnected'} 2017-05-30 23:21:36,486 [INFO] ### received CONNECT ### 2017-05-30 23:21:36,487 [INFO] {'data': 'connected'} 2017-05-30 23:21:40,003 [INFO] {'data': 'disconnected'} 2017-05-30 23:21:40,004 [INFO] ### received CONNECT … -
how to change scrapy user agent without settings file
I have implemented my spider via a script just like the main example: import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://blog.scrapinghub.com'] def parse(self, response): for title in response.css('h2.entry-title'): yield {'title': title.css('a ::text').extract_first()} next_page = response.css('div.prev-post > a ::attr(href)').extract_first() if next_page: yield scrapy.Request(response.urljoin(next_page), callback=self.parse) I run with: scrapy runspider myspider.py How do I change the user agent if I don't have a setting or have create from startproject? As specified here: https://doc.scrapy.org/en/latest/topics/settings.html -
Django: Sending a JavaScript variable to a view
I would like to use a JavaScript variable within my Django view and then use AJAX to handle it. Currently, my views.py is: @login_required(login_url='users/login') def coin_decrease(request): """ Function based view for decreasing a user's coin balance """ if request.is_ajax(): try: user = request.user except User.DoesNotExist: raise Http404("No user matches the given query.") cost = request.POST.get('cost') **<-- not sure what to do here** user.profile.coins -= cost user.save() return JsonResponse({'coins': user.profile.coins}) else: raise Http404 and my AJAX looks like this: function spend_coins() { $.ajax({ method: "POST", url: "/purchase", data: {}, success: function(data) { $( ".status" ).contents()[0].textContent = "Balance: " + data.coins } }) }; I have a variable entitled currentCost which I need to pass to the view. -
How can I include a conditional order_by in django?
I need to sort two parts of a queryset differently based on a boolean field. - Rows that have bool_val == True should come first, and be sorted by date_a, ascending. - Rows that have bool_val == False should come second, and be sorted by date_b, descending. The closest I've gotten is MyModel.objects.all().annotate( sort_order=Case( When(bool_val=True, then=('date_a')), default='date_b') ).order_by('-bool_val', 'sort_order') But that sorts them all in the same order. If the value I needed to sort by were numerical, then I would multiply one set by -1 in my annotation, but they're date values, so that won't work. I've also looked into creating two separate querysets and combining them, but union() isn't available until 1.11 and I have to support 1.10, and other methods of combining querysets that I've found either don't preserve order or don't result in a queryset (or both). (I'm not clear on whether union() preserves order or not, but it's moot, so I didn't dig into it much, either.) This has to be a django QuerySet object at the end. -
Changing Cloud SQL block_encryption_mode in a GAE app
I'm running a GAE app in the Standard environment (thus, little control over things). It's using Cloud SQL for its backend (MySQL). How can I change the default block_encryption_mode on the database permanently to aes256? By default it's set to aes-128-ecb, which isn't good enough for our needs. -
Django get_or_create manytomany relation add
I want to get or create relation in my model: Model: class Test(models.Model): users = models.ManyToManyField(User) created_at = models.DateTimeField(auto_now_add=True) View: @login_required def test_detail(request, username): recipient = User.objects.get(username=username) conversation, created = Test.objects.get_or_create( users__in=[request.user, recipient] return render(request, 'conversations/detail.html', { 'conversation': conversation }) How to put keys data to get_or_create function? Now this code alway insert new items to Test model only with data.. -
how to add time to html from python method
this is part of a flask application. I would like to get the current time to output anywhere in the form of the html file. I would like to add the method current_time() in flaskr.py to the anywhere in the from in the attached html file. Thanks! flaskr.py import os import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash from datetime import date import time app = Flask(__name__) app.config.from_object(__name__) app.config.update(dict( DATABASE = os.path.join(app.root_path, 'flaskr.db'), ##in real world apps use instance folders for databases instead SECRET_KEY = 'development key', USERNAME = 'admin', PASSWORD = 'default' )) app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db @app.teardown_appcontext def close_db(error): if hasattr(g, 'sqlite_db'): g.sqlite_db.close() def init_db(): db = get_db() with app.open_resource('schema.sql', mode = 'r') as f: db.cursor().executescript(f.read()) db.commit() @app.cli.command('initdb') def initdb_command(): init_db() print('initialized the database.') @app.route('/') def show_entries(): db = get_db() cur = db.execute('select title, text from entries order by id desc') entries = cur.fetchall() return render_template('show_entries.html', entries=entries) @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) db = get_db() db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) db.commit() flash('New entry was … -
Using Jinja2 with Django, load keyword does not work
I'm building a Django app and chose to use Jinja2 for my templating engine. I noticed after I switched from Django's built in templating engine to Jinja2 the load keyword would not work, ex: {% load static %}. This is used to load static files like CSS. Is there a Jinja workaround for this in Django? Django: 1.11 Jinja2: 2.9.6 -
django formsets split one field into multiple forms
One of the fields in my django formset has multiple values separated by comma. "a,c,v,b,n" is an example. I want to display them in separate fields or forms in the formset. For example, "a" in one field, "c" in another field and so on. Can you please let me know what is the best way to do that? -
Django + Vagrant VM suddenly says Errno 111: connection refused
I'm sure this is my fault, but my system has been working for months and now does not work. I've looked in Django docs and here on stackoverflow, and I understand the issue that 'connection refused' means nobody is listening on the socket; but I don't understand why, and don't know how to go forward. I use Vagrant + VirtualBox on a MacPro, and for six months I have been able to create virtual machines and run my app with no problems. I have some VM's where everything works as expected. On my newly-created Vagrant VM's, I install and configure my django apps and run them using 'python manage.py runserver --settings=mumble.settings.py 0.0.0.0:8000'. Note that this is Django 1.8.3, but again,it works fine on some VM's. For mysterious reasons, when I create a new vagrant VM and install my django payload (using deploy scripts that haven't changed), and connect to the django server, I get Errno 111 Connection refused: Performing system checks... System check identified no issues (0 silenced). May 30, 2017 - 15:56:30 Django version 1.8.3, using settings 'something.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. <stack trace truncated ...> File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket return … -
Django: Get pk/id for each object while using values in query
The following lines in my views.py allow me to display a table which groups objects by their similar fields ('brand__name', 'name', 'capacity', 'vintage') and displays brand counts. (screenshot) user = request.user object = Bottle.objects.filter(brand__business__owner_id=user.id).all(). \ values('brand__name', 'name', 'capacity', 'vintage').annotate(Count('brand')).\ order_by('brand__count').reverse() args['object'] = object Recently, I discovered that for each line, I also need to pass one of the object IDs/PKs for each distinct Bottle kind (so each line). This allows me to create bottles by quantity by creating new instances of the same Bottle, by doing this in my views.py: elif 'add_quant' in request.POST: num_of_bottles = int(request.POST['num_of_bottles']) brand_details = request.POST.get('brand_details', None) print("bottle id:", brand_details) model_to_create_by = Bottle.objects.get(id=brand_details) for number in range(num_of_bottles): new_bottle = Bottle.objects.create(name=model_to_create_by.name, brand=model_to_create_by.brand, capacity=model_to_create_by.capacity, vintage= model_to_create_by.vintage) new_bottle.save() Now, if I add id to values, obviously I lose the grouping, because each bottle ID is different, and thus each bottle object will get its own line in the table (which I don't want). EDIT: Thinking about it, I also need the id to trigger modals. Currently I'm using the bottle's name to build a modal for each kind, but if the bottle's name has spaces, then the modal won't get triggered (the HTML attribute id cannot contain spaces). How … -
Upload image file using django rest framework in a single page application
I am trying to upload image using Vuejs and Django, but I can't figure out how to solve it. This is the django side: class UserDetail(models.Model): user = models.OneToOneField(User) profile_picture = models.ImageField(upload_to=create_file_path) class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = UserDetail fields = '__all__' class UserDetailViewSet(viewsets.ModelViewSet): queryset = UserDetail.objects.all() serializer_class = UserDetailSerializer permission_classes = [AllowAny] @detail_route(permission_classes=[AllowAny], methods=['POST'], parser_classes=[FormParser, MultiPartParser]) def create_or_update_profile_picture(self, request): user = request.user # # how to create or update user detail profile picture ? # I am posting the data this way from Vuejs: changeProfilePicture() { const file_input = document.getElementById('display_profile_image'); const img = file_input.files[0]; let formData = new FormData(); formData.append("profile_picture", img); const url = this.$store.state.website + '/api/accounts/user-detail/none/create_or_update_profile_picture/'; this.$http.post(url, formData) .then(function (response) { this.$store.dispatch('getUserDetail'); }) .catch(function (response) { console.log(response); }); } How can I use the post data to create or update the request.user's profile_picture in Django? -
Django Model Form not appearing in admin
I've got a feedback app in django and it all seems to work fine, no errors i can submit the form and it all seems to work, however i have my model registered into my admin however when i submit the form i doesn't appear in my admin. Sorry if this is very basic i just cant get my head around it please help. in my models.py class Feedback(models.Model): email = models.CharField(max_length=100) message = models.CharField(max_length=1000) def __unicode__(self): return self.title which i then pass through to forms.py class FeedbackModelForm(forms.ModelForm): class Meta: model = Feedback fields = ["email", "message"] and my view is def feedbackform(request): form = FeedbackModelForm(request.Post or None) if form.is_valid(): form.save() return render(request, "feedback.html", {"form": form}) now in my html looks like this {% block content %} <div id="feedback"> <div id="feedback-form" style='display:none;' class="col-xs-4 col-md-4 panel panel-default"> <form method="POST" action="{{ form }}" class="form panel-body" role="form">{% csrf_token %} <div class="form-group"> <input class="form-control" name="email" autofocus placeholder="Your e-mail" type="email" /> </div> <div class="form-group"> <textarea class="form-control" name="message" required placeholder="Please write your feedback here..." rows="5"></textarea> </div> <button class="btn btn-primary pull-right" type="submit">Send</button> </form> </div> <div id="feedback-tab">Feedback</div> </div> {% endblock %} -
How to serve Django for an Electron app
I'm trying to create an Electron desktop app which has a Django application at its backend. There are several tutorials and blogs which mention how this can be achieved. I've tried those and it seems to be working, however there are some issues. One of them for me is how to server Django in this case? For me the current way of doing it creates some unwanted delay making the app slow to start... Generally, what needs to be done to create an Django/Electron app is to package (I'm using pyInstaller)the Django app into an stand-alone executable and then bundle that into an Electron app. The question is which server should be used for this case to server Django before packaging it with pyInstaller? At the moment I'm using cherryPy as a WSGI web server to serve Django. However - is there a better alternative knowing that this will be used in an Electron desktop app? Maybe something faster, or more suitable for this task? What is the typical way of handling Django in this case? -
How to render new variations for StdImageField - Django
I created a standard image field for one of my Django models, and at the time of creating it, only had one variation, named 'large'. I have since added another variation named 'thumbnail' that is smaller. The application has been on a production server for a while, and many images have already been uploaded. I am using the thumbnail version in my template, but unless I go into the admin, to the model, re-upload the file, and save, their is no thumbnail variation. Since there are already hundreds of photos, it would be very tedious to have to re-upload every single one. I also tried creating a static method on my model that would go through every object, and re-save the files, but it does not have the same effect as manually going into the admin. Model def process_photo_image(file_name, variations, storage): render_variations(file_name, variations, replace=True, storage=storage) obj = get_model('inventory', 'Inventory_Image').objects.get(image=file_name) obj.processed = True obj.save() def image_processor(file_name, variations, storage): process_photo_image.delay(file_name, variations, storage) return False class Inventory_Image(models.Model): inventory_item = models.ForeignKey(Inventory, related_name='images') image = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True, variations={'large': (600, 600, True), 'thumbnail': (250, 150, True)}, render_variations=image_processor) create_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Image" verbose_name_plural = "Images" ordering = ('id',) @staticmethod … -
there is no installed modules in web server nginx+uwsgi+python3
I have run empty django project by nginx+uwsgi+python3 and everything was ok. But when i am trying to run with my installed app by uwsgi and nginx (after seccessful prerun by python manage.py runserver 0:80), Django says that no module named (the name of module which myapp need). ImportError... Myvenv have all installed modules. Python3.5, ubuntu16 Please help me. -
If / Elif/ Else Are All Being Run Even When Conditions Not Met
I current have a function to return an error message depending on the error code given (an int). The issue is that I have everything within a Try/Except, and everything is getting run... I put some prints so they get printed to the console so I can see where this function stops... But it goes all the way to the end and the message ends up being the final definition on the function.. Code: # function for processing declined card errors def declined_card(code): """ Take in the processor_response_code and return the proper error. - processor_response_code supplied by Braintree on declined card """ try: # codes falling outside of the dictionary print "testing 1: " + code if 2092 <= code <= 2999: message = "Your payment method has been declined. Please contact your bank " \ "for more information." elif code >= 3000: print "testing 2: " + code message = "There was an issue with the back-end processing network. Please try " \ "your transaction again. If this issue persists, please contact " \ "us using the help page." # codes within the dictionary print "testing 3: " + code if error_codes[code]: message = error_codes[code] return message except KeyError: … -
Dynamically choice field select
Problem in select dynamic choices. My class like below: class Booking(models.Model): MEDIA_CHOICES = ( ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ) name = models.CharField(max_length=100) choice= models.CharField(max_length=20,choices=MEDIA_CHOICES,) def __str__(self): return self.name Can choices be select dynamically i.e Only Audio or Only Video. -
Django FileField - missed upload_to while save()
I have a model with field class ExampleObject(model.Model): logo = models.FileField(upload_to="topics/") When I want to save a file by Command using ExampleObject's save() method: topic.logo.save( "filename.svg", File(open(path_to_file)) ) it saves files in topics/ folder, but when I want to open it I have error: No such file or directory: /path/to/file/without/upload_to/filename.svg What may be a problem?