Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: Object is not iterable (Error)
Can anyone explain why this is iterable: User.objects.all() this is valid and gives me a value (The current user's alias. session is storing the user id): User.objects.get(id = request.session['currentuser']).alias) But this is giving me the error saying it is 'not iterable?': Poke.objects.get(user = User.objects.get(id = request.session['currentuser']).alias) (This code is supposed to get a list of Poke entries where the user column matches the current user's alias.) Here is the Poke model. It does not use ForeignKeys, as I was having trouble setting two of them without errors. class Poke(models.Model): id = models.IntegerField(primary_key=True) user = models.CharField(max_length=100) poker = models.CharField(max_length=100) pokes = models.IntegerField() class Meta: app_label = "poke_app" -
jquery elements with django forms
I am using jquery elements that a user can drag and drop. I post the order of the elements to django using ajax. Inside the django view I am able to work with the data that is posted from ajax. Django views: #this is the view where the jquery elements are being ordered by the user def inside_exam(request): if request.method=='POST': form = MyForm(request.POST) if form.is_valid(): #here I am able to retrieve the data from ajax and save it to a django model, code not shown here return redirect('exam_results') #the view redirected to from the inside_exam view def exam_results(request): #here I set the score for the exam and set the context, code not shown here print(“all is set”) return render(request, 'quizresults.html', context) The print(“all is set”) is executed and I am able to print the html for quizresults.html in the browser. No errors are in the terminal window and this is shown in the terminal: "GET /exam_results/ HTTP/1.1" 200 8981. But the same template is still shown, it is not showing the quizresults.html template. Any idea why the render(request, 'quizresults.html', context) is not working as expected? By the way: when I use a django form without the jquery, everything works fine … -
Exctract value from querydict
I need to extract the value '180' as an integer from this output < QueryDict: {'tz_data': ['180']} > the output is an ajax POST request please help, ty -
How to design my models?
I have an issue. I don't know how to build my model according to the fair way of Django. I have 3 models : Team, Plateform and Games. class Team(models.Model): name = models.CharField(max_length=15, null=False) tag = models.CharField(max_length=4, null=False) description = HTMLField(blank=True, null=True) logo = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension], blank=True, null=True) games = models.ManyToManyField(Games, verbose_name="Jeu") owner = models.ForeignKey(User, verbose_name="Créateur") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") class Plateform(models.Model): name = models.CharField(max_length=100, unique=True, null=False, verbose_name="Plateforme") guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="Abréviation") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") class Games(models.Model): guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID") title = models.CharField(max_length=100, null=False, verbose_name="Titre") logo = models.FileField(upload_to='media/games/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Logo du jeu") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") plateform = models.ManyToManyField(Plateform, verbose_name="Plateforme") So : Games own to many Plateforms Teams play many Games My question is, how to determine which Games on which Plateforms a Team is currently playing ? Because I have to know if a team is playing a Game on a particular Plateform or several. I think I need a new class like : class Relation(models.Model): team = models.ForeignKey(Team) plateform = models.ForeignKey(Plateform) game = models.ForeignKey(Games) But isn't … -
Open text file stored as record in Database [Django]
I need to process .txt file which has .csv structure and is stored as field in database. Main functionality of app is processing this files and generating an output. Every once in a while I need to upload new version but keep the record of old one. Those are tiny files, rarely exceeding 300kb. I also need additional fields with uploader's name, date, version etc, that's why I'm keeping it as record in DB rather than in local files. A file record is stored in DB with type models.FileField() How can I access this record not as a field but as a file object and open it like a usual .txt? What I've tried but it didn't work: listofschedules = ScheduleFile.objects.all file = listofschedules[0].csvSchedule with open(file, 'rt', encoding='windows 1250') as csv_input: reader = csv.reader(csv_input, delimiter=';') print(reader) ... -
Normalizing JSON response from server before updating Redux state
It's my preferred paradigm (and probably everyone's) that the server remains unopinionated about serializing its JSON response as it doesn't care which client is consuming it. Said another way, my django JSON payload is written in snake case as per standards. Before this can update the state in my Redux store the keys should be mapped to camel case as per Javascript standards. The python developers don't believe this is worth the effort, which he has a fair point but it just feels wrong not following convention. How should this be handled?? -
Django FileResponse not working with uwsgi
I have the following code which takes in an arbitrary audio stream and converts it to mp3 on the fly using ffmpeg. The code works fine when run using python manage.py runserver but is not working when run using uwsgi server. from django.http import FileResponse def mp3(request): audiourl = request.session['audiourl'] title = request.session['title'] process = Popen('ffmpeg -i "{}" -f mp3 -'.format(audiourl), shell=True, stdout=PIPE) response = FileResponse(process.stdout) fname = title + '.mp3' response['Content-Disposition'] = content_disposition(fname) return response It might work with gunicorn but I prefer to use uwsgi if possible. Kindly post your valuable suggestions. -
Adding more time options to TimeField admin pull down?
I am wondering if it is relatively easy to customize the TimeField pull down menu in django. In older versions the TimeField would show selections for every 30 minutes: Django 1.11 only shows a few options: -
Html django update variable without refreshing the whole page
Whenever a page is refreshed, the scroll reset to the initial position and so it's uncomfortable for the user to go back at the position he was looking at. So I would like to change the value of the variable qdelete whenever the delete button is clicked without refreshing the whole page: My html file: {% for q in questions %} <tr> <td> <div align= Center> {% if qdelete == forloop.counter %} <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qyesbtn" name="qyesbtn" value="qyesbtn_{{q.id}}">Yes &raquo;</button> </div> <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qnobtn" name="qnobtn" value="qnobtn">No &raquo;</button> </div> {% else %} <button type="button" class="btn btn-primary btn-large" name="qid" onclick="qdelete=forloop.counter" value="{{forloop.counter}}">Delete &raquo;</button> {% endif %} </div> </td> </tr> {% endfor %} <script> function SetDelete(num){ qdelete = num } </script> I'm trying to call the SetDelete() javascript function but it doesn't work. Any advice it's appreciated. -
django_cron run only once django
Sorry for my english. I new in django, i want send email every 1 min. I found this solution i follow it. But my django_cron run only one. i installed django_cron like this: pip install django_cron then i added app to INSTALLED_APPS INSTALLED_APPS = [ .. 'django_cron', 'accounts', ... ] and add to settings: CRON_CLASSES = [ "accounts.cron.MyCronJob", ] then run python manage.py migrate django_cron in app accounts i create file cron and add this code: from django.core.mail import EmailMessage from django.template.loader import render_to_string from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'accounts.cron.MyCronJob' # a unique code def do(self): print("send message") message = render_to_string('cron_file.html', { 'name': '111' }) mail_subject = 'Congratulations' to_email = 'test@gmail.com' email = EmailMessage(mail_subject, message, to=[to_email]) email.send() then run python manage.py runcrons but message send only once when i call command python manage.py runcrons -
Logout on the site does not work
I have recently updated django from 1.6 to 1.11. Among many other problems (already solved) I have problem with logging out. Steps: 1. I log in on the site (standard django auth protocol used). I perform some actions on the site as logged user. I log out. I see "logout compleated" (standard django function), looks like I am not logged in. I click somewhere on the site and I am logged in again. When I click log out, session is delated, but after another action it shows up again. I have no idea how to give you more details, does anyone had any similar problem? -
Python and Django - How to use in memory and temporary files
I need some examples with file operations using in memory and temporary files. I searched a lot for a good example /tutorial and I found just basic read/write/append operations. I need to understand how can I read in Django a file that is uploaded(an image) before the save(post) is finished. Because Django is Python, I think is better to understand first in python. I checked the Django documentation/examples about, but it is not very clear so I need to understand first in phyton than in Django how the operations are working. -
Testing file import
I am trying to test my file imports for files with a .xlsx extension. I have the creation of the imported table working but I can't get the assertions to work. Here is my current test: class testImport(TestCase): def setUp(self): self.client = Client() @classmethod def setUpTestData(cls): user = get_user_model().objects.create(username='xlsx_importer') table_name = "Test Import" version_name = "Master" publish = False cls.user = user cls.table_name = table_name cls.version_name = version_name cls.publish = publish def test_xlsx_import(self): tmp = tempfile.NamedTemporaryFile(suffix='.xlsx') workbook = xlsxwriter.Workbook(tmp) worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 20) worksheet.write('A1', 'Hello') worksheet.write('A2', '1') worksheet.write('B1', 'World') worksheet.write('B2', '2') tmp.seek(0) workbook.close() table = s.create_table_from_file( file=tmp, table_name=self.table_name, version_name=self.version_name, publish=self.publish, created_by=self.user, ) What I want to do is go through the columns attached to that table (through the ORM) and make a data structure that maps from friendly name to id (and therefore dictionary key). I can currently get: <QuerySet [{'name': 'World', 'content_type_id': 49, 'id': 44, 'order': 1, 'commit_id': 14}, {'name': 'Hello', 'content_type_id': 49, 'id': 43, 'order': 0, 'commit_id': 14}]> By using table.commit_set.all()[0].column_set.all().values() The Queryset I am testing against is: <QuerySet [{'id': 1, '43': '1', '44': '2'}]> where '43' equates to Hello and '44' equates to World from the first Queryset. The assertion I want to make is to … -
Graph results not being rendered in APIview
I have two templates that are working OK because the results are being displayed in console and one template renders the results as an APIView. However, I want the results of this last template to be rendered with the Charts.js library that I have included. This is the code I have so far. urls.py url(r'^tickets_per_day_no_results/$', ChartData8.as_view(), name="tickets_per_day_no_results"), url(r'^tickets_per_day_results/$', ChartData8.as_view(), name="tickets_per_day_results"), Views.py class ChartData8(APIView): def get(self,request): template_name = 'personal_website/tickets_per_day_no_results.html' form = DropDownMenuForm() return render(request, template_name, {'form': form}) def post(self, request): year = request.POST.get('select_year', None) week = request.POST.get('select_week', None) # ....do stuff... data = { "label_number_days": label_number_days, "days_of_data": count_of_days,} return Response(data) Templates: tickets_per_day_no_results.html and tickets_per_day_results.html tickets_per_days_no_results.html: it just contains two drop-down menus to select year and week and a submit button with a post request. This template works fine. <h3>Please, select the year and week number to retrieve the data.</h3> <form id="search_dates" method="POST" action="/tickets_per_day_results/"> {% csrf_token %} <h6>Select year</h6> <div class="row"> <div class="col-sm-8"> <select name="select_year"> <option value = {{form.year}}></option> </select> </div> <div class="col-sm-8"> <h6>Select week</h6> <select name="select_week"> <option value= {{form.week}}></option> </select> <button type="submit">Search</button> </div> </div> </div> tickets_per_days_results.html: it contains the Charts.js libraries to render the results as graphs. Currently, this template display the results as an APIView. <script> {% block jquery %} … -
user follower systen in django
I am creating a follower system and an unfollow system using django. I have implemented every code and there seems to be no error except from the fact that instead of the initial button to be follow it is actually unfollow and if I click on unfollow nothing happens. below is my code details.html {% extends 'base.html' %} {% load staticfiles %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> <div class="profile-info"> {% thumbnail user.profile.photo "180x180" crop="100%" as im %} <img src="{{ im.url }}" class="user-detail"> {% endthumbnail %} </div> {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> <div id="post-list" class="image-container"> {% include "axle.html" with objects=user.posts_created.all %} </div> {% endwith %} {% endblock %} {% block domready %} $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.follow').data('action'); // toggle data-action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle … -
Is it possible to change HTML "value" for a django rendered form field?
Basically, I have a form with a radio select widget for a field called Queue. Queue has 4 choices, which are coming from a model, accessed and set via views.py. I am rendering this form on my template by doing {{form.queue.0}}, {{form.queue.1}} and so on. For example, {{form.queue.3}} gives me: <input id="id_queue_3" name="queue" value="2" type="radio"> As you can see, there is a value and field index mismatch - queue.3 is showing up as value="2" and this is messing with some JS that uses the value to open the right subset of menus under each radio button. Is it possible for me to render the radio field on the template by manually specifying the value? My forms.py: class PublicTicketForm(): queue = forms.ChoiceField( widget=forms.RadioSelect(), label=_('What do you need help with?'), required=True, choices=() ) My views.py for this form: form = PublicTicketForm(initial=initial_data) form.fields['queue'].choices = [('', 'Other')] + [ (q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] -
Prevent model from creation/modification/deletion
I have a model which needs complex logic for update, creation and deletion. I would like to have only one custom manager method to handle creation (let's call it new), one model method to handle deletion and prevent all the others. Is there other methods that can modify models besides the ones below? Here is what I came up with: class MyModelQuerySet(models.QuerySet): def update(self, *args, **kwargs): raise ValueError("Use 'new' method from manager instead.") def delete(self): raise ValueError("Use 'delete' method from model instead.") class MyModelManager(models.Manager): def get_queryset(self): return MyModelQuerySet(self.model, using=self._db) def create(self, *args, **kwargs): raise ValueError("Use 'new' method from manager instead.") def get_or_create(self, *args, **kwargs): raise ValueError("Use 'new' method from manager instead.") def update_or_create(self, *args, **kwargs): raise ValueError("Use 'new' method from manager instead.") def new(self, *args, **kwargs): obj = self.model() # Insert complex logic here super(MyModel, obj).save() class MyModel(models.Model): def save(self, *args, **kwargs): raise ValueError("Use 'new' method from manager instead.") def delete(self, *args, **kwargs): # Insert another complex logic here super().delete(*args, **kwargs) -
ImageField Django template
I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand how I should do to make this. Can someone show me with all step please? model.py: class Post(models.Model): title=models.CharField(max_lengt=50) img=models.ImageField(upload_to = 'images') template: {% for post in posts %} <h1> {{post.title}} </h1> <img src="{{post.img}}"> setting.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' If I access to admin page how i can upload the image? In template I cant see image!! Sorry for my bad English. Help me please -
Why is username not included in the credentials of a logout event triggered by a session expiration in Django?
I've implemented a model that uses django.contrib.auth.singals to record user login/logout events. The model originates from an answer given here: How can I log both successful and failed login and logout attempts in Django? from django.db import models from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.dispatch import receiver from __future__ import unicode_literals class AuditEntry(models.Model): action = models.CharField(max_length=64, editable=False) username = models.CharField(max_length=256, null=True, editable=False) ip = models.GenericIPAddressField(null = True, editable=False) added = models.DateTimeField(auto_now_add=True, editable=False) def __unicode__(self): return '{0} - {1} - {2}'.format(self.action, self.username, self.ip) class Meta: db_table = "db_audit_entry" verbose_name = "Audit Entry" verbose_name_plural = "Audit Entries" @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') AuditEntry.objects.create(action='user_logged_in', ip=ip, username=user) @receiver(user_logged_out) def user_logged_out_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') AuditEntry.objects.create(action='user_logged_out', ip=ip, username=user) @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs): AuditEntry.objects.create(action='user_login_failed', username=credentials.get('username', None)) I also have SESSION_EXPIRE_AT_BROWSER_CLOSE set to True in settings.py. When a user closes their web browser before logging out, a logout AuditEntry object is created with the correct action, ip address, and date. However, the username is not recorded. I don't understand why credentials does not include username when a logout event occurs due to a session expiration. According to the Django docs for login/logout signals, username is None when a user … -
Django SMTPAuthenticationError (535, '5.7.0 authentication failed')
There are a bunch of questions on the SMTPAuthenticationError in Django, to name a few: Django SMTPAuthenticationError send_email not working in django? Django SMTPAuthenticationError How to send email via Django? Django - SMTPAuthenticationError django sending email: SMTPAuthenticationError Most of these questions arose from using Gmail's or some other "remote" SMTP service. My setup will use the "localhost" as the SMTP server. My Django 1.8.x project is running on a Ubuntu 16.04.2 LTS. The sendmail package was installed by following this guide. If sendmail isn't installed, install it: sudo apt-get install sendmail Configure /etc/hosts file: nano /etc/hosts Make sure the line looks like this: 127.0.0.1 localhost yourhostname Run Sendmail's config and answer 'Y' to everything: sudo sendmailconfig Restart apache sudo service apache2 restart My settings.py has these email related lines: EMAIL_HOST = 'example.com' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'web@example.com' EMAIL_HOST_USER = DEFAULT_FROM_EMAIL EMAIL_HOST_PASSWORD = 'WebmasterUbuntuUserPassword' I tried using smtplib from Python standard lib but got the same error. import smtplib s = smtplib.SMTP('localhost', 587) s.login('web@example.com', 'WebmasterUbuntuUserPassword') I sudo service apache2 restart each time I change the settings.py. I have another old CentOS 5.11 box, which works without any explicit *EMAIL* settings in the settings.py; the defaults just work. Any suggestions will … -
How to disable verification step for all-auth? (sending verification email )
I'm using all-auth (all-auth-rest) for basic authoriztion / authentication. By default, when user register, django all-auth is trying to send a verification email. How can I disable it to prevent it from sending a verification email? -
django docker exited with code 0 in request GET or POST
Good friends, I am developing an application in django 1.11 with docker on windows, recently update the git repository of the project and also made some changes with docker containers. The problem is that when entering the main page and some other URLS nothing happens, but when I try to login to the administrator, the django container is closed and I do not even get any error by the browser, console or log . Example: When I come in here they are fine GET / 200 OK POST / 403 Forbidden GET / api / auth / 405 Method not allowed But when I enter these, without showing any message, close the docker container (proyect_django_1 exited with code 0) GET / admin No answer POST / api / auth / No answer -
manage.py: error: unrecognized arguments: migrate
I've been trying to install some modules in Django and for some reason after doing it i got this error when trying to migrate my models to database: manage.py: error: unrecognized arguments: migrate I don't know what's wrong, It happened after trying to install modules from pip, Maybe Django was downgraded or upgraded? Thanks! -
How can I add data to PostgreSQL in real-time chatbot based on Django websockets?
I am trying to create real-time chat using Django backend and Angular 4 frontend with PostgreSQL database. Let's assume that I would like to create chat robot for instance like A.L.I.C.E. It seems to me that the most optimal solution would be to use websockets? I create channel layer using Redis. Now, I would like to save all messages to my PostgreSQL database. I wonder how it should be done. Should I create models and use them in consumers.py or maybe there is an another more optimal way? In the future I would like to analyze data from database and return the answer. consumers.py: # In consumers.py from channels import Group # Connected to websocket.connect def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_receive(message): Group("chat").send({ "text": message.content['text'], }) print(message.content['text']) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) routing.py: from channels.routing import route from backend.consumers import ws_connect, ws_receive, ws_disconnect channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] settings.py: CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "backend.routing.channel_routing", }, } -
Partial matching search in Wagtail with Postgres
I've got a wagtail site powered by Postgres and would like to implement a fuzzy search on all documents. However, according to wagtail docs "SearchField(partial_match=True) is not handled." Does anyone know of a way I can implement my own partial matching search? I'm leaving this question intentionally open-ended because I'm open to pretty much any solution that works well and is fairly scalable.