Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
duplicate events action in django admin
I have a duplicate records function in my django admin.py, and in someway it works, but the weird things is that i have must duplicate this function outside and inside the modelAdmin... def duplicate_event(ModelAdmin, request, queryset): for object in queryset: object.id = None object.save() duplicate_event.short_description = "Duplicate selected record" class ProductAdmin(ImageCroppingMixin, admin.ModelAdmin): model = Product inlines = [CompositionAssociactionAdmin] list_display = ("image_img", "code", "name", "price", "discount", "price_offer", "prompt_delivery", "delivery", "promo", "active") list_editable = ('active',) fields = ( ("name", "code"), ("price", "discount", "price_offer"), ("color", "material"), ("scarpemisura", "cintureLunghezza"), "size", ("width", "lenght", "depth", "height"), "volume", "descrizione", "album", "image", "slider", "thumb", "thumbdue", "croplibero", ("prompt_delivery", "delivery"), ("slide", "promo"), "tags", "active", "pub_date" ) def duplicate_event(ModelAdmin, request, queryset): for object in queryset: object.id = None object.save() duplicate_event.short_description = "Duplica Record Selezionati" actions = ['duplicate_event'] before I has try simply so: def duplicate_event(ModelAdmin, request, queryset): for object in queryset: object.id = None object.save() duplicate_event.short_description = "Duplicate selected record" class ProductAdmin(ImageCroppingMixin, admin.ModelAdmin): model = Product inlines = [CompositionAssociactionAdmin] list_display = ("image_img", "code", "name", "price", "discount", "price_offer", "prompt_delivery", "delivery", "promo", "active") list_editable = ('active',) fields = ( ("name", "code"), ("price", "discount", "price_offer"), ("color", "material"), ("scarpemisura", "cintureLunghezza"), "size", ("width", "lenght", "depth", "height"), "volume", "descrizione", "album", "image", "slider", "thumb", "thumbdue", "croplibero", ("prompt_delivery", "delivery"), … -
Django interpreting dict values ambiguously
Python interpreting QueryDict ambiguously. When I print request.POST values, I see the values I'm expecting i.e 1 and 3. However when I print the list, I see only 3 being printed. (Pdb) request.POST <QueryDict: {u'subjob_ids[]': [u' 1 ', u' 3 '], u'updated': [u''], u'created': [u''], u'job_name': [u'Job11'], u'jobtype_id': [u'1'], u'no_of_subjobs': [u'2'], u'operation': [u'addjobwithexistingsubjobs'], u'id': [u'-1']}> (Pdb) request.POST['subjob_ids[]'] u' 3 ' Checked if this is problem with uunicode, but it's not. When I convert unicode to str , I see only 3. (Pdb) str(request.POST['subjob_ids[]']) ' 3 ' So is there a problem with the data present in QueryDict? I tried taking this value into python interpreter instead of pdb, it just works perfectly. >>> dict = {u'subjob_ids[]': [u' 1 ', u' 3 '], u'updated': [u''], u'created': [u''], u'job_name': [u'Job11'], u'jobtype_id': [u'1'], u'no_of_subjobs': [u'2'], u'operation': [u'addjobwithexistingsubjobs'], u'id': [u'-1']} >>> dict {u'subjob_ids[]': [u' 1 ', u' 3 '], u'jobtype_id': [u'1'], u'updated': [u''], u'no_of_subjobs': [u'2'], u'created': [u''], u'operation': [u'addjobwithexistingsubjobs'], u'job_name': [u'Job11'], u'id': [u'-1']} >>> dict['subjob_ids[]'] [u' 1 ', u' 3 '] >>> dict['subjob_ids[]'][0] u' 1 ' >>> dict['subjob_ids[]'][1] u' 3 ' Is there something wrong with how django is treating the data? -
Phaser games database access
How do you access database records from Django to be used by a Javascript game development framework like Phaser? I am thinking to serialize into JSON? -
Django reverse is giving me some trouble
My problem is that when reverse is called it throws the following exception Reverse for '/documentation/' with arguments '(3,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Here is my urls.py url(r'^documentation/([0-9])/$', views.documents, name='documentation'), here my views.py def view1(request): if request.method == 'POST': profe = request.POST.get('value') a = value.encode('ascii', 'ignore') b = int(a) return HttpResponseRedirect(reverse('documentation', args=(b,))) else: return render(request, "documentation.html", info) def documents(request,valor): ...something... return render(request, "anotherdoc.html", ..something..) and here is my template (documentation.html) ... <form method="POST" action=""> {% csrf_token %} {% for p in ps %} <tr> <td><button id="boton1" button type="submit" name = "valor" value ="{{p.idp}}" class="btn btn-success btn-sm">{{p.nombre}} {{p.apellido}}</button> </td> <td>algo</a> </td> </tr> {%endfor%} </form> I want 127.0.0.1:8000/documentation/1 from reverse() but I´m having a hard time trying that Thanks -
django: saving a query set to session
I am trying to save query result obtained in one view to session, and retrieve it in another view, so I tried something like below: def default (request): equipment_list = Equipment.objects.all() request.session['export_querset'] = equipment_list However, this gives me TypeError at /calbase/ <QuerySet [<Equipment: A>, <Equipment: B>, <Equipment: C>]> is not JSON serializable I am wondering what does this mean exactly and how should I go about it? Or maybe there is alternative way of doing what I want besides using session? -
Django Syntax Highlighting within POST form
In Django 1.8, I have enabled prism syntax highlighting[1] css / js within head section of my base.html template <link rel="stylesheet" href="{% static 'css/prism.css' %}"> <script src="{% static 'js/prism.js' %}"></script> I have proved this works ok, by pasting in the code tags (below) directly into my html, and it shows up as expected: <pre> <code class="language-markup"> code line text here </code> </pre> The problem that I have, is I wish to add these tags directly into a PostForm (like a user making a blog post, where they want to highlight code examples) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_ossn', pk=post.pk) else: form = PostForm() return render(request, 'website/post_edit.html', {'form': form}) When I do this, it seems the render is messing up the tags and breaking prisms ability to parse the tags out. This is what I see for view source: pre&gt;<br />&lt;code class=&quot;language-markup&quot;&gt;<br /><br /> code line text here<br /><br />&lt;/code&gt;<br />&lt;/pre&gt;</p> So I maybe wrong here, as I only started learning django since last week, but I have a suspicion the form render / post is breaking the code tags? Is there any was … -
Scrollable table with fixed header loses feature when Chrome window is full screen
I have a Django website where the CSS shown below modifies my tables to have a fixed header and a scrollable body. .table-fixed > tbody { display:block; max-height:600px; overflow-y: auto; } .table-fixed > thead { display:table; width:100%; table-layout:fixed; } .table-fixed > tbody > tr { display:table; width:100%; table-layout:fixed; } .table-fixed > thead { width: calc( 100% - 1em ) } I call table-fixed as such: <div class = "col-xs-12"> <table class = "table table-hover table-striped table-condensed table-fixed"> <thead> <tr> <th>Head</th> </tr> </thead> <tbody> <tr> <td> {% body %} </td> </tr> </tbody> </table> </div> The tables work and do what they are meant to do. The issue occurs when I am on Chrome and make the window full screen. The scroll bar goes away. On the other hand, if I do this in IE nothing changes. I can make the window full screen, and the tables still have scrolls. Any ideas what is causing this issue in Chrome? -
Django query difference in group
suppose I have a Model A with a one-to-many relationship with Model B which has a one-to-one relationship with Model C. Model C has attribute X which hold a numeric value. This is illustrated below: What is the best way to express a query where I would want all instances of model A where the attribute X on its related model C's (through model B) have a certain percentage difference among them? for example: I want all A's where any of the related model C's X attributes have a difference of 20% or more: modelA[id=1] model Bs [A1:B1 ,A1:B2, A1:B3] model Cs attr x values [A1:B1:C:attrX=> 10, A1:B2:C:attrX=> 14, A1:B3:C:attrX=> 13] This example would qualify because A1:B1:C:attrX has a 20% or higher difference with at least one other attrX -
Is it possible to use matplotlib's interactive plotting features within Django?
I know Matplotlib can be used in Django, based on the documentation. However, I'd like to be able to create interactive graphs within a webpage (i.e clickable points). In order to display a graph created in a Python script, Django spits out a png image. I haven't tested it out myself, but the fact that Django only spits out a png is worrisome. Is what I'm trying to do possible? http://scipy-cookbook.readthedocs.io/items/Matplotlib_Django.html http://scipy-cookbook.readthedocs.io/items/Matplotlib_Interactive_Plotting.html -
Submitting a form fails, but because views.auth_login (not related to my form) didn't return an HttpResponse object
OK, so I have a functional auth_login setup. But it's unrelated to my Articles model, and ArticleForm ModelForm. However, when I try to create a new article on the local website, I get an error related to views.auth_login even though auth_login isn't referenced anywhere (to my knowledge) in my Article stuff: The view home.views.auth_login didn't return an HttpResponse object. It returned None instead. Usually, an error like that means that you're not returning an actual response in a view definition, but I do. The real question is why home.views.auth_login is being called instead of home.views.add_article. Here's my code: home/models.py class Article(models.Model): headline = models.CharField(max_length=50) content = models.CharField(max_length=1024) def __str__(self): return self.headline home/forms.py from django.contrib.auth.models import User from .models import Article class LoginForm(forms.ModelForm): class Meta: model = User fields = ["username", "password"] class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['headline', 'content'] home/views.py def auth_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. return HttpResponseRedirect('/home/') else: # Return an 'invalid login' error message. return HttpResponse('Invalid username / password. :( Try again? <3') else: loginform = LoginForm() context = { 'loginform': loginform … -
django: is it possible to change widget of a form field according to content in another form field?
Sorry for this poorly-worded title. What I really would like to know is for a form like the following: <form id="searchform" action="/calbase" method="get" accept-charset="utf-8"> <select name="search_type"> <option value="asset_number">Asset #</option> <option value="calibrated_by">Calibrated by</option> <option value="department">Department</option> <option value="description">Description</option> <option value="expiring_soon">Expiring soon</option> <option value="flagged">Flagged</option> <option value="manufacturer">Manufacturer</option> <option value="model">Model</option> <option value="serial #">Serial #</option> <option value="test">Test</option> </select> <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search"> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> I have a select widget for search_type and searchfield for search_content(q). For some of the search_type, like department and test, I would like search_content be using drop down select widget and the user can just choose which department(from a list) to search by. And for expiring soon, the search_content should be uneditable. Is there a easy way of achieving this? -
How can I solve this: <class 'website.admin.UserProfileInline'>: (admin.E202) 'website.Profile' has no ForeignKey to 'website.Doctor'?
I do not really know whatI'm doing wrong> I have some ForeignKeys relatinships in my models which I would like to display in the admin site on my forms. I'm trying to display my ForeignKeys and display in the django admin site but I'm receiving the following error: <class 'website.admin.UserProfileInline'>: (admin.E202) 'website.Profile' has no ForeignKey to 'website.Doctor'. Here're my models: class Profile(models.Model): SEX_CHOICE_MALE = 'M' SEX_CHOICE_FEMALE = 'F' SEX_CHOICES = ( (SEX_CHOICE_MALE, "Male"), (SEX_CHOICE_FEMALE, "Female") ) user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) initial = models.CharField(max_length=2) dob = models.CharField(max_length=8) gender = models.CharField(max_length=1, choices=SEX_CHOICES, default='N/A') contact_number = models.CharField(max_length=14) address = models.CharField(max_length=20) suburb = models.CharField(max_length=12) postcode = models.IntegerField(default=0000) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Patient(models.Model): user = models.ForeignKey(Profile) health_history = models.TextField() def __str__(self): return self.user.username class Doctor(models.Model): user = models.ForeignKey(Profile) department = models.ForeignKey('Department') def __str__(self): return self.user.username class Department(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Appointment(models.Model): TIME_SLOT = ( (1, _("8h00 - 8h30")), (2, _("8h30 - 9h00")), (3, _("9h00 - 9h30")), (4, _("9h30 - 10h00")), (5, _("10h00 - 10h30")), (6, _("10h30 - 11h00")), (7, _("11h00 - 11h30")), (7, _("11h30 - 12h00")), ) STATUS_INACTIVE = 'I' STATUS_ACTIVE … -
Django model where field is based on another field unless specified otherwise
Say I have a django model called Car and another called UserCar which has a related car object. class Car(models.Model): name = models.CharField(max_length=100) mpg = models.DecimalField(max_digits=6, decimal_places=2, null=True) class UserCar(models.Model): car = models.ForeignKey('Car') mpg = models.DecimalField(max_digits=6, decimal_places=2, null=True) I would like to override the save function on UserCar such that if no value for mpg is specified, the model instance is pre-populated with the value of mpg on the related Car object. -
No module named account: Django importerror
I'm trying to get a server to run on my computer, but when I enter the command python manage.py runserver, I get this error message: File "manage.py", line 8, in startup.run() File "/Users/cbplusd/repos/wibo_master/wibo/startup.py", line 20, in run autoload(["receivers"]) File "/Users/cbplusd/repos/wibo_master/wibo/startup.py", line 10, in autoload mod = import_module(app) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module __import__(name) ImportError: No module named account I'm really confused, because the 'account' module is in installed_apps in my settings.py, but the error is still there. Has this happened to anyone else? Thanks! -
Django annotate on prefetched filtered related model
I have a User model, each User can have many Post, and each post can get some like, i want to get users (along their posts) that has more that n posts which is liked more that m times, i do: User.objects.prefetch_related(Prefetch('posts', queryset=Post.objects.filter(like_count__gte=m), to_attr='top_posts')).annotate(top_post_count=Count('top_posts')).filter(top_post_count__gte=n) but, i get: django.core.exceptions.FieldError: Cannot resolve keyword 'top_posts' into field. -
Django Database routing based on current user logged in
In a view class, you could call self.request.user and perform actions based on that. In my case, I would like to be able to switch databases depending on the current user logged in. Is there anyway to inject a self.request call into the db_for_read() and db_for_write() methods like in the following? class DataBaseRouter(object): def db_for_read(self, model, **hints): user = self.request.user if user.id == 1: return "master" return "default" def db_for_write(self, model, **hints): user = self.request.user if user.id == 1: return "master" return "default" -
Python mysqldb: Library not loaded: /usr/local/mysql/lib/libmysqlclient.20.dylib
There are a lot of responses for libmysqlclient.18.dylib, but I havent found anything for libmysqlclient.20.dylib. I can only assume that the same solutions for .18 would work for .20. I have tried to uninstall mysql python but get an egg error. For now, here is where I'm at: I run the django server and get this: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/mysql/lib/libmysqlclient.20.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: image not found I've located the file doing this: mdfind libmysqlclient | grep .20. and get this: /usr/local/Cellar/mysql/5.7.14/lib/libmysqlclient.20.dylib Then I try to create a symbolic link in /usr/lib, by: sudo ln -s /usr/local/Cellar/mysql/5.7.14/lib/libmysqlclient.20.dylib /usr/lib/libmysqlclient.20.dylib After I type in my password I get: ln: /usr/lib/libmysqlclient.20.dylib: Operation not permitted I've also tried: export DYLD_LIBRARY_PATH=/usr/local/mysql-5.7.14-osx10.11-x86/lib/:$DYLD_LIBRARY_PATH and get nothing. So to the question: How do I run my server when I get: ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/mysql/lib/libmysqlclient.20.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: image not found -
With jsonb in Postgres (used with Django's JSONField) what does a unique index actually do?
class JsonHavingModel(models.Model): the_field = JSONField(unique=True) This does something like: CREATE UNIQUE INDEX app_jsonhavingmodel_the_field_c1f3c983_uniq ON app_jsonhavingmodel (the_field); But what does that actually mean? Does it check just keys? Just values? Just the literal JSON text? Does is check the whole object hierarchy? Is this a stupid question? What is the meaning of life? -
Custom save method or custom method for adding model fields
I'm working with some models that has to return a sum of model fields. Is it better to override the save method on the model or just create a custom method that returns the sum. Is there any performance issues with either of the solutions? Example 1, overriding the save method. class SomeModel(models.Model): integer1 = models.IntegerField() integer2 = models.IntegerField() integer3 = models.IntegerField() sum_integers = models.IntegerField() def save(self, *args, **kwargs): self.sum_integers = sum( [self.integer1, self.integer2, self.integer3]) self.sum_integers.save() return super(SomeModel, self).save(*args, **kwargs) Example 2, custom method class SomeModel(models.Model): integer1 = models.IntegerField() integer2 = models.IntegerField() integer3 = models.IntegerField() @property def sum_integers(self): return sum([self.integer1, self.integer2, self.integer3]) -
django: link to detail page from list of returned results
I'm creating a page that returns a list of movies with basic details after a user search. After the search, I'd like the user to be able to click on a movie, and get more details about it. here's a link to the site: (be gentle, I only started learning this stuff 2 months ago! hah) http://moniblog.pythonanywhere.com/compare/ the data is coming from TMDB's api and the initial "generic" search JSON response doesn't have specific details that I'd display on the movie's detail page, but it has an ID that will be used for the specific movie's search. I'm only using views.py to grab/display the search results, and I'm not sure if this is the right way to go, or if I should use a model, but that's probably a different question. forms.py: from django import forms class MovieSearch(forms.Form): moviename = forms.CharField(label="Search", max_length=250) views.py: from django.shortcuts import render, get_object_or_404 from django.conf import settings from .forms import MovieSearch import tmdbsimple as tmdb tmdb.API_KEY = settings.TMDB_API_KEY def search_movie(request): parsed_data = {'results': []} if request.method == 'POST': form = MovieSearch(request.POST) if form.is_valid(): search = tmdb.Search() query = form.cleaned_data['moviename'] response = search.movie(query=query) for movie in response['results']: parsed_data['results'].append( { 'title': movie['title'], 'id': movie['id'], 'poster_path': movie['poster_path'], 'release_date': … -
Cannot install pip on Windows 8
I am currently trying to install pip in order to install Django on Windows 8. I've downloaded the latest version of Python and installed it successfully but I am having some trouble installing pip. I've read the previously asked questions regarding the same topic but I cannot seem to solve my problem. I have tried installing pip through the cmd which was ran under administrator and under normal mode. This is the output I receive in the command line: File "C:\Python27\lib\shutil.py", line 83 in copyfile with open(dst, 'wb') as fdst: I0Error: [Errno 13] Permission denied: 'C:\Pytho27\Lib\site-packages\pip\_vendor\distlib\t32.exe' I have configure Python's path from the advanced settings. ( just some additional information) How can I solve this problem? -
Deleting Object from QuerySet List in Django with ManyToMany relationship
I am having trouble deleting an object from a list of objects while using ForeignKey and ManyToMany relationships in Django. Here is the models I have set up for an Item, List, and the Order (an intermediary model). class Item(models.Model): title_english = models.CharField(max_length=250) url = models.CharField(max_length=250) img_url = models.CharField(max_length=250) def __unicode__(self): return self.title_english class List(models.Model): slides = models.ManyToManyField(Item, through='Order') size = models.PositiveIntegerField(default=0) def incrementSize(self): self.size = self.size+1 def __unicode__(self): return "List: " + str(self.slides.all()) class Order(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) list = models.ForeignKey(List, on_delete=models.CASCADE) index = models.PositiveIntegerField() def __unicode__(self): return str(index) + ": " + str(self.item) def appendItemToList(self, item, list): self.item = item self.list = list self.index = list.size list.incrementSize() I am adding objects to the list (created dynamically from existing objects), through the view like so: def AddItem(request, pk): sourceObj = SourceObject.objects.get(pk=pk) lst = List.objects.all() if not lst: lst = List() lst.save() else: lst = lst[0] item = Item(title_english=sourceObj.name_english, url=sourceObj.slug, img_url=sourceObj.media) item.save() order = Order() order.appendItemToList(item, lst) order.save() lst.save() return redirect("some_url") Now my issue is, deleting an item added to list. I am having trouble understanding how I can access the target object. def RemoveItem(request, pk): lst = List.objects.all() lst.delete() #deletes the entire list #how do I access the … -
Django template - database fields not being referenced by keys from different dict
In my view I have: def accounts(request): context = {} if request.user.employee.usertype == 'manager': fields = { 'email': 'Email', 'password': 'Password', 'number': 'Mobile', 'status': 'Status', 'paid': 'Paid', 'ip_address': 'IP Address', 'timestamp': 'Timestamp' } elif request.user.employee.usertype == 'managed': fields = { 'number': 'Mobile', 'status': 'Status', 'paid': 'Paid', 'timestamp': 'Timestamp' } accounts = Accounts.objects.all().values(*fields.keys()) context['fields'] = fields context['accounts'] = accounts return render(request, 'accounts.html', context) Now In my accounts.html template I am trying to populate them as: {% if accounts %} <br> <div class="row"> <center> <div class="table-responsive"> <table class="table table-striped table-bordered"> <tr> <th>#</th> {% for field, title in fields.items %} <th>{{ title }}</th> {% endfor %} </tr> {% for account in accounts %} <tr> <td>{{ forloop.counter }}</td> {% for field, title in fields.items %} <td>{{ account.field }}</td> {% endfor %} </tr> {% endfor %} </table> </div> Current time - {{ current_time }} </center> </div> {% endif %} This only shows the table heading and number of rows as much as number of accounts but nothing in the table cells. When I try to display a cell like {{ account.email }} it does populate. And when I try to display {{ field }} in that for loop it shows the fields dictionary's keys properly … -
Custom permissions on viewset
Im trying to find a way to create custom permissions on a viewset. Im want to implement somthing like this : class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer if request.method == 'PUT': permission_classes = (permissions.IsOwner) elif request.method == 'LIST': permission_classes = (permissions.IsAdmin) else : permission_classes = (permissions.AllowAny) IE : sorting permissions by method. (the above code doesnt work cause "request" isnt recognized) Couldn't find any use in the "Custom permissions" section of the documentation, but maybe Im just blind. (overriding BasePermission? how? who? where?) Thanks :) -
CSS style present in html, not in developer tools view
I have a table with some specific styles that renders just fine by itself, but when displayed on the same page with a second table, does not. Taking one element in particular, I have a pair of label styles: .lb-lg { font-size: 16px; } .label { display: block; width: 50px; } These are properly rendered here: (it's the green box with the white 'P') You can see where the styles are in the inspector, and everything's great. When I render the page with a different view (adding another table on the page, but not changing this html), the label is small and .label and .lb-lg do not appear in the inspector. Half a dozen other styles that originally rendered are similarly broken. HTML (same in both cases, Django template tags in there): {% if abb %} <a href="link blah" class="label label-default lb-lg " style="background-color:{{clr}};">{{abb}}</a> {% else %} <span class="label label-default lb-lg" style="background-color:transparent; border: 1px solid #999; color:transparent;">f</span> {% endif %}