Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call a SOAP web service by suds
I have a web service developed by soaplib and it's work fine, but I need to call his functions. I now the solution is Suds, but when I added this code on my project or how it's working ? SUDS Calling this service >>>from suds.client import Client >>> hello_client = Client('http://localhost:7789/?wsdl') >>> result = hello_client.service.say_hello("Dave", 5) >>> print result -
TypeError: isinstance() arg 2 must be a type or tuple of types
I was trying to change the name of Group model auth_group to Association and makemigrations but i got this error so i reversed it back to models.Model with Association. Still the same error and i wonder what the reason could be. All of this happend after i dropped the database to start with new tables. Hope someone else have encountered this kind of problem and solved it. Still a newbie so appreciate your help! Here is the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 353, in execute self.check() File "C:\Python36\lib\site-packages\django\core\management\base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "C:\Python36\lib\site-packages\django\core\management\base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "C:\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python36\lib\site-packages\django\contrib\auth\checks.py", line 77, in check_user_model if isinstance(cls().is_anonymous, six.types.MethodType): File "C:\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 68, in __init__ super(AbstractBaseUser, self).__init__(*args, **kwargs) File "C:\Python36\lib\site-packages\django\db\models\base.py", line 529, in __init__ val = field.get_default() File "C:\Python36\lib\site-packages\django\db\models\fields\related.py", line 899, in get_default if isinstance(field_default, self.remote_field.model): TypeError: isinstance() arg 2 must be a type or tuple of types -
Forms Instead of Long Admins?
My Post model is getting quite extensive and long in admin. I'm wondering at what point I should use forms, instead? Is there a way to break admin entry into multiple pages, or tabs? -
Mezzanine error
When I try to build a Django Blog with Mezzanine it gives me an error while trying to execute "$ python manage.py createdb" in command line in Mac. Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mezzanine/conf/models.py", line 7, in <module> from mezzanine.core.models import SiteRelated File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mezzanine/core/models.py", line 24, in <module> from mezzanine.core.fields import RichTextField, OrderField File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mezzanine/core/fields.py", line 14, in <module> from mezzanine.utils.html import escape File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mezzanine/utils/html.py", line 36, in <module> if "tel" not in sanitizer.BleachSanitizer.allowed_protocols: AttributeError: 'module' object has no attribute 'BleachSanitizer' What is the problem? -
How to send the user to from one app to another of same project in django using <a> tag?
The First url pattern is urlpatterns=[ url(r'^$',views.EventInitiationView,name='eventsini'), url(r'^(?P<event_id>[0-9]+)/$',views.EventsDetailView,name='eventinfo'),] The Second url pattern is url(r'^events/(?P<event_id>[0-9]+)/$',views.EventBooking,name='eventbooking') -
send http request using django and get results
this might seem like an extremely simple and stupid question yet i can't find a convenient answer. i'm trying to use google's reverse geocodding api with django, as the website explains (at https://developers.google.com/maps/documentation/geocoding/start?csw=1#ReverseGeocoding) i'm supposed to send a request to the url : https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=<_api_key> but i can't find an appropriate way to send this request using django to google api. to me it seems something so simple will be doable by some method built-in django but all i could find was modules to install. if there's no way but installing other python modules which one's the best? -
How to store multipe queryset results in a list, then display values in template
Id like to store a filtered queryset in a list and then iterate over the list in my template. I have a list of tenants in my model stored like so: class Tenant(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) telephone = models.CharField(max_length=30) email = models.CharField(max_length=30) contract_end = models.DateField(blank=False) def __str__(self): return u'%s %s' % (self.first_name, self.last_name) View like so: def expiry(request): now = datetime.datetime.now() tenant_queryset = Tenant.objects.all() expired_list = [] for x in range(0, 12): date = now + relativedelta(months=x) expired = tenant_queryset.filter( contract_end__year=date.year, contract_end__month=date.month ) expired_list.append(expired) context = {"expired_list": expired_list} return render(request, "expired_template.html", context) Template: {% for tenant in expired_list %} {{ tenant.first_name }}<br> {{ tenant.telephone }}<br> {{ tenant.contract_end }}<br> {% endfor %} Im using a for loop in my view to go through the months of the year, then storing those results in a list. I cant seem to get tenant.first_name, tenant.last_name, tenant.telephone and tenant.contract_end values to display in my template. Im guessing this is because Im already outputting the results of my filtered queryset to a list and its displaying those results rather than a 'reference', if that makes sense. How can I go about this? Thanks for the help. -
Double template inheritace in Django
Can a Django template extend another template that extended another template? In other words can c.html do the below? It appears it can't. Any solution? a.html b.htnl {% extends 'a.html' %} c.htnl {% extends 'b.html' %} -
TypeError: unhashable type: 'dict' Django
I have a very simple dictionary with some data on it: some_data= {'totalsForAllResults': {'ga:sessions': '11'}, 'profileInfo': {'internalWebPropertyId': '104132673', 'accountId': '67836206', 'profileName': 'My New Cool Site', 'webPropertyId': 'UA-677293506-1', 'profileId': '108628346', 'tableId': 'ga:108372846'}, on my views I have: sessions = some_data['totalsForAllResults']['ga:sessions'] account_id = some_data['profileInfo']['accountId'] property_id = some_data['profileInfo']['internalWebPropertyId'] property_name = some_data['profileInfo']['profileName'] print(sessions,account_id,property_id,property_name) return render(request, 'ga_app/report.html', {'sessions':sessions}, {'account_id':account_id}, {'property_id':property_id}, {'property_name':property_name},) The variables get printed perfectly on my shell, however django doesn't want to pass them to the templates, I keep getting TypeError: unhashable type: 'dict' but I'm sending variables to the template not a dictionary. Why this happens? -
Django making querys inside template
i have the following problem. I need to get the information of the question based on the questionitem.question_id I have the following files. models.py class Question(models.Model): qtype_id = models.ForeignKey(QuestionType, on_delete=models.CASCADE ) q_discription = models.CharField(max_length=150) def __iter__(self): return self.pk class QuestionItem(models.Model): exam_id = models.ForeignKey(Exam, on_delete=models.CASCADE) question_id = models.ForeignKey(Question, on_delete=models.CASCADE) question_pontuation = models.FloatField(default=0.0) def __iter__(self): return self.pk views.py def ExamDetail(request, exam_id): exam = get_object_or_404(Exam, pk=exam_id) questionitems = QuestionItem.objects.filter(exam_id= exam_id).values_list('id', flat=True) questions = Question.objects.filter(pk__in=questionitems) context = { 'exam': exam, 'questions': questions, 'questionitem': questionitems, } return render(request, 'evaluation/exam_detail.html' , context) And now on exam_detail.html i have something like this: {% for questionitem in exam.questionitem_set.all %} Question {{questionitem.id}}</a>: {{question.q_discription}} {% endfor%} but nothing shows, and i need to show the description of the question in questionitem.question_id, and i cant change the models.py. -
How to remove trailing slash in Django template?
I have a model City with image: card_image = models.ImageField(upload_to=cityCardImagePath, blank=True) When I call in template: {{city.card_image.url}} I get the path with trailing slash at the end: https://mybucket.s3.amazonaws.com:443/media/media/project/images/cities/card/city1.png/ I have read this question and understand that slash is required in cases when additional parameters are followed. In my case I am using AWS_QUERYSTRING_AUTH = False and need to remove this slash. How can I do it? -
Can't load image in my django template
My project folders is : mrdoorbeen manage.py mr_doorbeen setting.py mrdoorbeen migrations templates index.html profile profile.html I want to include a image in my profile.html file. i use {% load staticfiles %} in top of the profile.htmland use this code at image source : <img src="{% static "image/example.jpg" %}" alt="cant'load"/> and i make a folder in a 'mr_doorbeen' and call it static and in static folder make a image folder and image i put a example.jpg but it doesn't work . my static folder path is wrong or what? where should i put my static folder in this project -
Add a bit of text before and after crispy_forms InlineRadios?
Is there a way to add a bit of text before and after crispy_forms InlineRadios? If I have a ChoiceInput with choices that all have an empty label, (don't worry, I'll take care of making it accessible), it should look like this: Completely disagree&nbsp; <input type="radio" name="question"/> <input type="radio" name="question"/> <input type="radio" name="question"/> <input type="radio" name="question"/> <input type="radio" name="question"/> &nbsp;Completely agree I'm using the bootstrap template pack. -
Error during template rendering
i am trying to render the details page of the product by giving the url www.example.com/product_name/product_id. But i am getting this error. Reverse for 'product_details' with arguments '(u'lehnga choli', 43)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P[a-zA-Z]*)/(?P[0-9]+)/$'] here is my urls.py url(r'^(?P<product_name>[a-zA-Z]*)/(?P<product_id>[0-9]+)/$', 'designer.views.product_details', name='product_details'), and here is my urls in html template {% url 'product_details' designs.name designs.id %} and this is my views.py def product_details(request, product_name, product_id): design = Design.objects.get(id=product_id) return render_to_response("designer/product_detail.html", { "design":design, "current": "product_detail", }, context_instance=RequestContext(request)) -
General IDE / VC
I'm developing a django site using pycharm (Windows desktop) & a github repo for a site on a remote Linux box with an SSH connection. It's a fairly small, one person project (at present). It's all working, but I don't think I'm working very efficiently. Every change & test seems laborious. I don't want to be making commits every time I make a small change but I'm still new enough that I need to be making lots of tests as I go along. So what would people's general workflow be? Have a local test install with a copy of the django site and work directly on that? What's the best way to update the live site (from github). If there's any standard best practice docs out there that you can point to would be great too. -
NoReverseMatch when redirecting after a DeleteView that passes one parameter
I'm getting the following error: NoReverseMatch at /lists/someusername/delete_list/17 Reverse for 'listview' with arguments '()' and keyword arguments '{'username': <SimpleLazyObject: <User: someusername>>}' not found. 0 pattern(s) tried: [] I'm using a DeleteView to delete an object and then I want to redirect to another view (function based view). Here are my URLS for both views: url(r'^(?P<username>[a-zA-Z0-0_.-]+)/delete_list/(?P<pk>\d+)$', views.DeleteListView.as_view(), name='deletelist'), url(r'^(?P<username>[a-zA-Z0-0_.-]+)/$', views.lists, name='listgroup'), Here is my DeleteView: class DeleteListView(LoggedInMixin, DeleteView): model = List def get_success_url(self): return reverse_lazy( 'lists:listview', kwargs = {'username': self.request.user},) The list is being deleted successfully, I just can't work out how to correctly pass the username parameter. All help greatly appreciated. -
Edit view saving twice
def edit(request, id): post = get_object_or_404(Post, id=id) edit_form = EditPostForm(request.POST or None, instance=post) if edit_form.is_valid(): instance = edit_form.save(commit=False) instance.save(update_fields=['content']) This is my edit view to update a Post (it only updates the content field). However what happens is the Post saves twice and therefore it shows up twice in my queryset. I have 2 saves in the view code which is the problem, but how else would I perform the edit here? -
AttributeError on dnango rest framework QuerySet' object has no attribute 'users
my model class Karfarma(models.Model): user = models.OneToOneField(User, related_name='karfarma', on_delete=models.CASCADE) mobile = models.TextField(max_length=11) validation_number = models.TextField(max_length=5, blank=True, default=None) phone_number = models.TextField(max_length=10, blank=True, default=None) datetime_join_persian = models.DateTimeField(default=None, null=True) def __unicode__(self): return "%s %s" % (self.user.first_name, self.user.last_name) my serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' but i got this error AttributeError at /api/members/ 'QuerySet' object has no attribute 'users' Request Method: GET Request URL: http://127.0.0.1:8000/api/members/ Django Version: 1.8 Exception Type: AttributeError -
proper way of handling multiple user type in django 1.10
I have researched a bit in the google and found out many different solutions for handling multiple user type. To make my question more clear, here is the requirement 1) There is two type of user - (one is general and another is developer) 2) Both user type will have same form field - (username, email, password, password(confirm)) The below is what i have tried. class customUser(AbstractBaseUser): user_choice = ( ('G', 'General'), ('D', 'Developer'), ) user_type = models.charField(choices=user_choices, max_length=2, default='G') class mainUser(customUser): type = models.OneToOneField('customUser') Do i have to handle explicitly for username, email, password and re-password field? I am using django allauth for single user registration and login. Do i have to now work it differently? -
Django limit prefetch_related
I want to limit prefetch_related in Django ORM to make it only load 5 comments. I tried the followings, both of them are not working: answers = Post.objects.filter( question_id__exact=pk, is_question=0, is_published=1 ).prefetch_related( Prefetch('comment_set', to_attr='comments')[:5] ).select_related() And: answers = Post.objects.filter( question_id__exact=pk, is_question=0, is_published=1 ).prefetch_related( Prefetch('comment_set', to_attr='comments', limit=5) ).select_related() I tried to search for it on stack but could not find solution. -
How to add Python data to HTML table
I need to have following table format in HTML: <table> <thead> <tr> <th>Version1</th> <th>Version2</th> <th>Version3</th> <th>Version4</th> </tr> </thead> <tbody> <tr> <td>image</td> <td>image</td> <td>image</td> <td>None</td> </tr> <tr> <td>image</td> <td>image</td> <td>image</td> <td>None</td> </tr> <tr> <td>image</td> <td>image</td> <td>None</td> <td>None</td> </tr> </tbody> </table> And as expected, it should render following table structure: My question is, how I should organize my Python data correctly so that I can implement this following table format in a clean, Pythonic way. All images belong to certain version, thus it's important that image is in right column (order matters). And some versions don't have all (or any) images so in that case I'll check if "image == None" and show "?" etc. instead of image. Thus, also 'empty' slots should be saved to data. Note: I'm doing this with Django and I use Django templates to render this. Ideally, I could do something like following in template: <table> <thead> <tr> {% for version in data.versions %} <th>{{ version }}</th> {% endfor %} </tr> </thead> <tbody> {% for image in data.images %} <tr> {% for file in image.files %} {% if file == None %} <td>No image</td> {% else %} <td>{{ file }}</td> {% endif %} {% endfor %} </tr> … -
HTML - Change text color based on value with JS
I'm creating a table displayed in HTML with Django. I want to change the number's color to red when the number is negative, and to green when the number is positive. I know I need to use JS for this but I could not make it work. Any help will be greatly appreciated !! Here is my Django HTML template (linked to my view) : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'WalletJournal/style.css' %}" /> <div id="container"> <h1>Transaction Journal</h1> </div> <div id="container"> {% if latest_transaction_list %} <table> <tr> <th>From</th> <th>To</th> <th>Amount</th> <th>Balance</th> <th>Date/Time</th> <th>Comment</th> </tr> {% for transaction in latest_transaction_list %} <tr> <td style="color:white">{{ transaction.TransactionFrom }}</td> <td style="color:white">{{ transaction.TransactionTo }}</td> <td style="font-family:'Arial',serif;font-size:10pt"><div class="TransactionAmount">{{ transaction.TransactionAmount }}</div></td> <td style="font-family:'Arial',serif;font-size:10pt">{{ transaction.BalanceAfterTransaction }}</td> <td style="font-size:6pt"><a href="{% url 'WalletJournal:detail' transaction.id %}">{{ transaction.TransactionDateTime }}...</a></td> <td style="color:white">{{ transaction.TransactionComment }}</td> </tr> {% endfor %} </table> {% else %} <p>No transactions are available.</p> {% endif %} </div> <script> var els = document.getElementsByClassName('TransactionAmount'); for (var i = 0; i < els.length; i++) { var cell = els[i]; if (cell.textContent < 0) { cell.classList.remove('green') } else { cell.classList.add('green'); } } </script> I know the JS code actually works since I got it from my previous question and I tested … -
How to properly append django csrf_token to form in inline javascript?
I have created form element dynamically in javascript: var selectform = document.createElement("form") I have added other input elements and these attributes to selectform: submitnselection.setAttribute('type',"submit"); submitnselection.setAttribute('value',"Submit"); submitnselection.setAttribute("name","submitnpage"); selectform.setAttribute("method", "post") selectform.setAttribute = ("action", "/test") "{% csrf_token %}"; In HTML, adding {% csrf_token %} template tag would work, but in this case of javascript i got 403 forbidden error: CSRF token missing or incorrect. I have found some solutions but nothing was working for me, is there any way to add {% csrf_token %} to form with only using Django, Javascript and plain Jquery? Also note that this script is inside html, so i think {% csrf_token %} template tag will work. -
Django Unique model for every user
How do I create a new model for every user in django. Like a new list of items for every new user -
django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image ERROR WITH IMAGE FIELD
I wanna add imagefield to my models.py and upload in my media_cdn directory but when i migrate to base my model.py he give this error error django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image ERROR WITH IMAGE FIELD Output from cmd operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field self._remake_table(model, create_fields=[field]) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\schema.py", line 199, in _remake_table self.quote_name(model._meta.db_table), File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute cursor.execute(sql, params) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=40) description = models.TextField(max_length=220, blank=True, default=None) image = models.ImageField(upload_to="/products_images/", null=True, blank=True, width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) is_active = models.BooleanField(default=True) publish = models.DateField(auto_now=False, auto_now_add=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return "%s" % self.id class Meta: ordering = ["-timestamp"] verbose_name = 'Product' verbose_name_plural = 'Products'