Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError out of the blue (import_export app)
I made literally no change and suddenly I am getting an ImportError out of the blue in this import line: from import_export.admin import ImportExportMixin The error is the following: ImportError: No module named admin Just to be clear: this wasn't happening ten minutes ago and I did nothing. Also, everything looks as it should: The app in present in INSTALLED_APPS: INSTALLED_APPS = ( # ... 'import_export', # ... ) The requirement is present in requirements.txt: django-import-export==0.5.1 And it is installed: (django18) C:\Users\dabadaba\PycharmProjects\dogpatchsports_com\mysite>pip install django-import-export==0.5.1 Requirement already satisfied: django-import-export==0.5.1 in c:\users\dabadaba\envs\django18\lib\site-packages Requirement already satisfied: tablib in c:\users\dabadaba\envs\django18\lib\site-packages (from django-import-export==0.5.1) Requirement already satisfied: diff-match-patch in c:\users\dabadaba\envs\django18\lib\site-packages (from django-import-export==0.5.1) And the import_export\admin.py module does indeed exist and the class ImportExportMixin is defined in it. -
Django file upload FilerFileField
I'm trying to use django FilerFileField as explained in the doc http://django-filer.readthedocs.io/en/latest/usage.html. It renders well with a field and a hyperlink inviting to select the file like http://localhost:8000/fr/admin/filer/folder/?_pick=file. This opens the filer admin page where I can navigate. After file selection, how can I go back to my form page with the appropriate file selected? I never get back such example as explained in the doc Here is what I have in my main url pattern urlpatterns = [ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^filer/', include('filer.urls')), url(r'^filebrowser_filer/', include('ckeditor_filebrowser_filer.urls')), ] I'm not using models.FileField() because I want to be able to point to my admin Filer images and files located in media/filer_public -
Displaying object in chunks across html table in django
I have list of over 100 categories I want to display across html table where(category data is from django model) class Category(): name = models.Charfield(max=200) like <table> <tr><td>cat 1</td><td>cat 2</td><td>cat 3</td><td>cat 4</td></tr> <tr><td>cat 5</td><td>cat 6</td><td>cat 7</td><td>cat 8</td></tr> <tr>......</tr> </table> here cat = category name please note each table row is holding 4 table data(where each td is in turns hold a category name) I know i could output them singly but it's not what I want. -
Django should I use an optional related field or get_or_create?
I have the a ForeignKey field on the User model. company = models.ForeignKey('crm.Company') So every user needs to have a company. The problem is the create_super_user method does not have a company at the start of a project and I get the following error: django.db.utils.OperationalError: (1054, "Unknown column 'users_user.company_id' in 'field list'") So would it be best to just create a default Company and assign it with get_or_create like: def create_superuser(self, email, password, **kwargs): company, created = Company.objects.get_or_create( name='Default Company', ) kwargs.setdefault('company', company) kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have staff=True') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self.create_user(email, password, **kwargs) The problem may arise when I create a new superuser from command line and the Default company has changed. Now a new Default Company will be created. On the other hand I can make the company field optional with null=True but now that breaks the system rules that each user is associated to a company. How else can I ensure a company has been created already? -
Prepopulate Django Form with Class Based View
As I'm learning Django Class Based View (CBV) in order to handle my script developed in Function Based View (FBV), I would like to make the following process. I would like to prepopulate one Django form field based on self.request.GET. This is my class : class IdentitySocieteFormView(LoginRequiredMixin, CreateView) : form_class = SocieteFormulaire template_name = 'Identity_Societe_Form.html' model = Societe def get_context_data(self, **kwargs) : data = super(IdentitySocieteFormView, self).get_context_data(**kwargs) if 'recherche' in self.request.GET : query_Responsable = self.request.GET.get('Responsable') Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable) data['responsable'] = Responsable return data def form_valid(self, form) : form.instance.Reponsable = responsable form.instance.Utilisateur = self.request.user.last_name + " " + self.request.user.first_name return super(IdentitySocieteFormView, self).form_valid(form) But I'm not sure about this line : form.instance.Reponsable = responsable which let to repopulate my field. Previously, my script looked like this : @login_required def IdentitySocieteForm(request) : query_Responsable = request.GET.get('Responsable') success = False if request.method == 'POST': form = SocieteFormulaire(request.POST or None) if form.is_valid() : # Vérification sur la validité des données post = form.save() messages.success(request, 'Le formulaire a été enregistré !') return HttpResponseRedirect(reverse('SocieteResume', kwargs={'id': post.id})) else: messages.error(request, "Le formulaire est invalide !") else: form = SocieteFormulaire() Responsable = Individu.objects.filter(NumeroIdentification=query_Responsable) form.fields['Responsable'].queryset = Responsable form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name return render(request, 'Identity_Societe_Form.html', {"form" : form, "query_Responsable" : … -
UnicodeDecodeError using Django and format-strings
I wrote a small example of the issue for everybody to see what's going on using Python 2.7 and Django 1.10.8 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function import time from django import setup setup() from django.contrib.auth.models import Group group = Group(name='schön') print(type(repr(group))) print(type(str(group))) print(type(unicode(group))) print(group) print(repr(group)) print(str(group)) print(unicode(group)) time.sleep(0.1) print('Repr: %s' % [group]) # fails print('Repr: %r' % [group]) # fails Exits with the following output + traceback $ python .PyCharmCE2017.2/config/scratches/scratch.py <type 'str'> <type 'str'> <type 'unicode'> schön <Group: schön> schön schön Traceback (most recent call last): File "/home/srkunze/.PyCharmCE2017.2/config/scratches/scratch.py", line 17, in <module> print('Repr: %s' % [group]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128) Has somebody an idea what's going on here? -
Django - passing variable to 'get_success_url'
I have an app where two different views are using the same objects / deleteview. Both are generic listviews displaying a list of the 'Invite' model. One filters a queryset where 'Invite.org = user.profile.org', the other excludes them. Since the views are so simular and the models are the same, I thought I could use a single (generic) deleteview to manage deleting invites. class InviteDelete(SecCheck, TenantRootedMixin, DeleteView): model = Purchases menu_id = 'invites' template_name = 'tenants/invite_delete.html' def get_success_url(self, **kwargs): return reverse('invite_list_own', args=[self.request.tenant.slug]) def form_valid(self, *args, **kwargs): from django.contrib import messages messages.success(self.request, '{} Invite deleted'.format(self.get_object().name)) return super(InviteDelete, self).form_valid(*args, **kwargs) def get_context_data(self, **kwargs): #Make sure that the user if returned to the correct 'tab' in the event of a cancel. data = super(InviteDelete, self).get_context_data(**kwargs) data['return_page'] = self.request.META.get('HTTP_REFERER') return data The 'delete' form has a confirmation page with a 'cancel' and a 'confirm delete' button. Pretty standard stuff. However, the problem is that I want the user to return to the previous page after a delete. This could either be View/Template A (Invite.org == user.profile.org) or View/Template B (Invite.org != user.profile.org) I'm trying to solve the problem with the self.request.META.get(HTTP_REFERER') method. THe 'get_context_data' pases the 'return_page' value to the template, which than uses … -
There comes a more `/` in the front of `??` when I request the url
I have a url in urls.py: urlpatterns = [ ... url(r'^delete_server_snapshot??(?P<snapshot_server_id>\[0-9a-z\-]+)/', app_admin_views.delete_server_snapshot), # here ... And when I request it, there is in template: <td><a href="/app_admin/delete_server_snapshot??{{ snapshot_server.id }}/" type="button" class="btn-de">Delete</a></td> But when I click the <a> tag, there comes error, there comes a more / in the front of ??: The request url: Request URL: http://localhost:8001/app_admin/delete_server_snapshot/??70e6e179-6269-445c-bd6a-cd98e55b1bdb/ -
Using django-jenkins with jenkins and docker
I try to present test results in Jenkins on build. My stack is, that I put Django application inside Docker image, and deploy it with Jenkins. Inside yaml file, where I have run docker container functionality I put running script. - name: Run unit test script command: docker exec -i my_container /bin/bash -c './manage.py jenkins --enable-coverage' Build went well, and if I ssh (in terminal) to this machine, and look inside docker container, I can see reports folder with reports. My problem is that inside Jenkins, under Workspace I can see all files but not reports folder. Because of that (I think) if I add Post-build Action -> Publish JUnit test result report I can't select folder with reports inside. My guess: My guess is that Jenkins can't see inside docker image, and somehow copy all files before yaml command is triggered. But I don't know how to solve this. -
Send templates emails Django 1.11 error
try to send template emails. Code: def send_admin_notification(ticket): subject = "Notification: NEW TICKET." to = [DEFAULT_ADMIN_EMAIL] from_email = settings.DEFAULT_FROM_EMAIL template = 'emails/admin.html' ctx = { "ticket_id": ticket.id, "subject": ticket.subject, "text": ticket.support_text, "email": ticket.email, } message = render_to_string(template, ctx) msg = EmailMessage(subject, message, to=to, from_email=from_email) msg.send() But i received error getaddrinfo() argument 1 must be string or None In Django 1.10 it work but i use template("").render(Context(ctx)) but in Django 1.11 it doesn't work and render_to_string doesn't work too. Anyone may help. Thank you for help. -
Count total Comments of every Author in Django
I know there are several posts about this, but none of them statify and work for me. Basically, I made very simple forum app, and I just want to count total Comments of every Author below their username. models.py import datetime from django.db import models from django.db.models import Count from autoslug import AutoSlugField from app_author.models import Profile class Forum(models.Model): """ Thread Model """ forum_author = models.ForeignKey( Profile, related_name='user_forums', null=True, blank=True, on_delete=models.CASCADE ) forum_title = models.CharField( max_length=225, verbose_name=u'Title', blank=False, null=False ) ... def __str__(self): return str(self.forum_title) def latest_comment_author(self): return self.forum_comments.latest('is_created').comment_author def latest_comment_date(self): return self.forum_comments.latest('is_created').is_created class Comment(models.Model): """ Comment Model """ forum = models.ForeignKey( 'Forum', related_name='forum_comments' ) comment_author = models.ForeignKey( Profile, related_name='user_comments', null=True, blank=True, on_delete=models.CASCADE ) comment_content = MarkdownxField( verbose_name=u'Markdown', ) is_created = models.DateTimeField( auto_now_add=True, ) is_modified = models.DateTimeField( auto_now=True, null=True, blank=True ) def __str__(self): return self.comment_content Views.py def forum_single_view(request, pk): """ Render Single Thread, Comments and Comment Form :param request: :param pk: :return: """ forum = get_object_or_404(Forum, pk=pk) forum_comments = Comment.objects.filter(forum=forum.id) template = 'app_forum/main/forum_single.html' context = {'forum': forum, 'forum_comments': forum_comments} return render(request, template, context) Template {% for comment in forum_comments %} ... {% endfor % I'm using something like this {{ comment.comment_author.count }}, but it shows nothing. I'm aware of Aggregation/Annotate, … -
Django 1.8 test issue: ProgrammingError: relation "auth_user" does not exist
I recently upgraded Django to 1.8 and set up a new development database for a fresh start. Migrations and dependencies went well, safe the usual errors you get and you end up solving. The app is working locally now just fine. However, I am getting an error when trying to run tests: python manage.py test This is the error I am getting: django.db.utils.ProgrammingError: relation "auth_user" does not exist Needless to say, Django's auth module is indeed installed and migrated in the app, so I am not sure what is going on. Here is the full stacktrace in case you need to peek at it, but it does't say anything even remotely helpful to me to figure out the cause of this error: Traceback (most recent call last): File "C:/Users/dabadaba/PycharmProjects/dogpatchsports_com/mysite/manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\commands\test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\commands\test.py", line 74, in execute super(Command, self).execute(*args, **options) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\core\management\commands\test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\dabadaba\Envs\django18\lib\site-packages\django\test\runner.py", line 210, in run_tests old_config = … -
Not transferring project to server when git push
I have a django project under development on my windows computer (dev-machine). I am using pyCharm for development. I have set up a server (server-machine) running ubuntu. And now want to push my project to the server. So in my project folder on the dev-machine I have done the git init: $ git init $ git add . $ git commit -m"Init of Git" And on the server-machine I have made a project folder: /home/username/projects In this folder I init git as well $ git init --bare Back on my dev-machine, I set the connection to the server-machine by doing this $ git remote add origin username@11.22.33.44:/home/username/projects And finally pushing my project to server-machine by typing this command on my dev-machine $ git push origin master It starts to do ome transfer. And here's the problem. On the server-machine when I check what's been transferred, it's only stuff like this ~/projects$ ls branches config description HEAD hooks info objects refs Not a single file from the project is transferred. This looks much like what the .git folder contains on the dev-machine. What am I doing wrong? -
How to make token based api with tastypie
I need to implement using api such behavior: App opening without registration If it's new user, then send signup request, and get new session If there is a session, then check it. So I think I need /signup method which creates session and returns a session token. And /check method which gets a token and returns check result. So, how to make token based api with django and tastypie? -
Change to django's urls.py not reflected online
I haven't touched my Django application in quite some time. Long enough to have forgotten these simple things. I'm running my Django application using nginx and uwsgi. I made some changes in my urls.py, adding one new line: url(r'^collections/',views.collections), When I navigate to the correct URL, it shows me the Django 404 page with attempted URL patterns, which doesn't show the newly added line. Previous related questions told me to restart NGINX and UWSGI,which I've done. The problem continues however. -
Why I m unable to create project in Django in Ubuntu 17.04
Why Django is not working I installed python 3 ,pip and virtualenr successfully but still I m unable to run Django app.what should I do. Where is the problem plz help. -
Organizing safety of uploaded files
Django==1.11.6 models.py class ItemFile(models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) In my project files is the most valuable information. Files will be uploaded only through Django admin. But files are provided by different people. Therefore filenames may really be unpredictable. What I'd like to do: Rename the file just to be on the safe side. Save original file name in the database. Calculate hash of the file with md5. Reason: files may be damaged in course of time (reasons may be various). Before backing up the database, I'll run a script to check the files. It is early detection of problems with files. If at point 1 a new filename will be the same hexdigest as in point 3, that would be great. Could you help me understand whether this idea with checksums of file is Ok or garbage. If it is, I'm planning to organize this all in the handler of post_save signal. Anything else seems impossible before the file is really saved. -
Continuous updating image - django
What I am looking to achieve is to have a page hosted by django. One part of this page will be an svg image which I retrieve as a parameter from within one of my programs objects. Basically what I want is to be able to update the svg image without having to refresh the page. Im also going to have a second html element that I want to update in a similar method. -
Django: Widget that queries database based on current text in text field?
I'm creating a workout calendar where users, among other things, can add workouts to their own calendar. To let users add a workout, I want to create an addworkout view that contains a form. Of course, an important part of a workout is the lifts it entails, such as benchpress, deadlift, etc. The names of the lifts will be entered in a text field. Now, since the users will often be typing in names of lifts that are well known, I intend to keep a bunch of lists stored in a model: from mongoengine import * class Lift(EmbeddedDocument): lift_id = IntField(unique=True) name = StringField(max_length=200) #e.g. bench press, etc sets = ListField(IntField()) # No of reps in each set def __str__(self): return self.name Then, when a user enters some text in a text field, I want the browser to query the database based on the text in the text field, and display all the matching lifts in a rolldown as suggestions. For example, if a user types "Dumbbell" into the text field, I want him/her to see a rolldown bar (is that what it's called?) with the suggestions "Dumbbell press", "Dumbbell row", etc. It's similar in functionality to how Google suggests … -
@transaction.atomic not working on signals.py
This is my signals.py file @transaction.atomic def post_save_transaction(sender, instance, created, **kwargs): """ adjusts the patient or organization account balance on transaction """ if created: instance.paid_by.balance -= instance.amount instance.accounts.balance += instance.amount instance.accounts.save(update_fields=['balance']) instance.paid_by.save(update_fields=['balance']) for multiple objects creation at a time this transaction work but use the previous balance again. -
Download intraday historical data of all Dow Jones stocks and put in a dataframe with one timestamp and index
I want to download all DJI stocks intraday historical data and assign one timestamp and index for all with stock ticker used as the name of each column. Here is my code but it not working. I know a little tweak would make it work. def High_Frequency_data(symbol, period, window): x = pd.DataFrame(parsed_data) for i in symbol: url_root = 'http://www.google.com/finance/getprices?i=' url_root += str(period) + '&p=' + str(window) url_root += 'd&f=d,o,h,l,c,v&df=cpct&q=' + symbol response = urllib2.urlopen(url_root) data = response.read().split('\n') #actual data starts at index = 7 #first line contains full timestamp, #every other line is offset of period from timestamp parsed_data = [] anchor_stamp = '' end = len(data) for i in range(7, end): cdata = data[i].split(',') if 'a' in cdata[0]: #first one record anchor timestamp anchor_stamp = cdata[0].replace('a', '') cts = int(anchor_stamp) else: try: coffset = int(cdata[0]) cts = int(anchor_stamp) + (coffset * period) parsed_data.append((dt.datetime.fromtimestamp(float(cts)), float(cdata[1]), float(cdata[2]), float(cdata[3]), float(cdata[4]), float(cdata[5]))) except: pass # for time zone offsets thrown into data x = x.append(parsed_data) x = pd.DataFrame(parsed_data) x.columns = ['ts', 'Open', 'High', 'Low', 'Close', 'Volume'] x.index = x.ts del x['ts'] return x print x symbol = ['AAPL','AXP','BA','CAT','CSCO','CVX','KO','DD','XOM','GE', 'GS','HD','IBM','INTC','JNJ','JPM','MCD','MMM','MRK','MSFT', 'NKE','PFE','PG','TRV','UNH','UTX','VZ','WMT','DIS'] High_Frequency_data(symbol,7200,252) -
My template do not shows the context_processors's data
In the blog/context_processors.py, I have a custom function: def custom_proc(request): user = {'name': 'allen', 'sex': 'man'} return user And I also add to the context processors in settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.i18n", "testMulToM.context_processors.custom_proc", # add there ) But when I run my server, and request the url to template, it do not fill the data to template: my app04/index.html template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> User: {{ name }} : {{ sex }} </body> </html> My app04/views.py: def index(request): return render(request, 'app04/index.html') -
Custom JSON Structure in Django for Highcharts
I am currently using Django 1.11 and Highcharts to accomplish a project of mine. I am finding utility quite useful and it's easy integration is especially cool! I am stuck with a problem : I need to show column chart with DrillDown : [e.g : https://www.highcharts.com/demo/column-drilldown ] And I need the "data" part from my Django Model for both Drilldown and Accumulated data shown in the data section at the top. : // Chart data : data: [{ name: 'Microsoft Internet Explorer', y: 56.33, drilldown: 'Microsoft Internet Explorer' }, { name: 'Chrome', y: 24.03, drilldown: 'Chrome' }, { name: 'Firefox', y: 10.38, drilldown: 'Firefox' }, { name: 'Safari', y: 4.77, drilldown: 'Safari' }, { name: 'Opera', y: 0.91, drilldown: 'Opera' }, { name: 'Proprietary or Undetectable', y: 0.2, drilldown: null }] drilldown: { series: [{ name: 'Microsoft Internet Explorer', id: 'Microsoft Internet Explorer', data: [ [ 'v11.0', 24.13 ], [ 'v8.0', 17.2 ], [ 'v9.0', 8.11 ], [ 'v10.0', 5.33 ], [ 'v6.0', 1.06 ], [ 'v7.0', 0.5 ] ] }, { name: 'Chrome', id: 'Chrome', data: [ [ 'v40.0', 5 ], [ 'v41.0', 4.32 ], [ 'v42.0', 3.68 ], [ 'v39.0', 2.96 ], [ 'v36.0', 2.53 ], [ 'v43.0', … -
Dynamically split a dictionary into multiple dictionaries in python3.6 depending on input provided
I am using Python 3.6 with Django Framework. I am getting input from the user & that input comes in the form of dictionary in my views.py. Lets say, the user enter 3 values than my dictionary will hold value like my_dict = {'name1': abc, 'job1': xyz, 'pos1':tak, 'phone1': 12345, 'name2': pqr, 'job2': ftr, 'pos2': lkj, 'phone2': 27654, 'name3': swq, 'job3': nme, 'pos3': mnb, 'phone3': 98421} I am looking to create sub dictionaries depending on the user input, in above case 3. Expected output is dict1 = {'name1': abc, 'job1': xyz, 'pos1': tak, 'phone1': 12345} dict2 = {'name2': pqr, 'job2': ftr, 'pos2': lkj, 'phone2': 27654} dict3 = {'name3': swq, 'job3': nme, 'pos3': mnb, 'phone3': 98421} Now, the catch here is we don't know what number of records we get from user, so sub dictionaries also need to be created dynamically. "dict1" to "dictn" where "n" is number given by user. Please suggest! -
show distance of restaurant from user
show distance of restaurant from user location I have implemented the feature of showing nearby restaurant from the given coordinates using postgis and geodjango. I am showing the list of restaurant so I could not show something like '5km' away. Here is what I have done to show the list of restaurant nearby url(r'^nearby_restaurant/(?P<current_lat>-?\d*.\d*)/(?P<current_long>-?\d*.\d*)/$', views.nearby_restaurant_finder, name="nearby-restaurant"), class Restaurant(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='restaurant' ) name = models.CharField(max_length=500) restaurant_slug = models.SlugField(max_length=250, unique=True) location = gis_models.PointField(blank=True, null=True, geography=True) gis = gis_models.GeoManager() objects = models.Manager() def nearby_restaurant_finder(request, current_lat, current_long): from django.contrib.gis.geos import Point from django.contrib.gis.measure import D user_location = Point(float(current_long), float(current_lat)) distance_from_point = {'km': 50} restaurants = Restaurant.gis.filter( location__distance_lte=(user_location, D(**distance_from_point))) restaurants = restaurants.distance(user_location).order_by('distance') context = { 'restaurants': restaurants } return render(request, 'restaurant/nearby_restaurant.html', context) What else should I consider for showing the distance of that restaurant from user?