Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-RQ + Braintree: Submit for settlement
I have read this stackoverflow Q&A but it did not worked it my case. In my scenario I push a function (submit_transaction_for_settlement(transaction_id)) to the redis queue using the excellent package django-rq. The job of this function is to submit a transaction for settlement. In the sandbox, whenever this function is executed I keep getting the same error: AttributeError: type object 'Configuration' has no attribute 'environment'. I tried agf's proposal about instantiate a new gateway for each transaction inside my function, but it did not work! Maybe this has something to do with the environment of the redis queue or the worker environment? def submit_transaction_for_settlement(transaction_id): from braintree import Configuration, BraintreeGateway config = Configuration(environment=settings.BRAINTREE_ENVIRONMENT, merchant_id=settings.BRAINTREE_MERCHANT_ID, public_key=settings.BRAINTREE_PUBLIC_KEY, private_key=settings.BRAINTREE_PRIVATE_KEY) gateway = BraintreeGateway(config=config) result = gateway.transaction.submit_for_settlement(transaction_id) -
Django permissions - how do they work?
While experimenting with Django and database design I stumbled upon permissions. The question I have asked myself is, how do you make a Group or conversation, say on facebook, private? Particularly how do I do this, or how does a package like django-guardian do this from a technical standpoint? Couldn't I for example create a many-to-many relationship between the Groups and User models to track who gets to view what groups? I am completely clueless on this. I tried looking for sources online but I have trouble finding anything. Everything search engines show me, including the django manual, is to do with implementing permissions. As in myuser.user_permissions.add(permission, permission, ...) Perhaps I just don't know what I'm supposed to look for and I'm just not looking for the right terms. If someone could explain to me how permissions work, or if that's a long story, perhaps point me in a direction where I can find an explanation on this topic I'd be super happy. -
Django form undefined error?
I defined my forms.py with this but having a 'ModelForm has no model class specified.' error. Why? from django import forms class SearchForm(forms.ModelForm): search_query = forms.CharField(max_length=100) -
unresolved reference django in pycharm
so i'm trying to import from django.db import models but then pycharm would underline django.db and complain unresolved reference 'django' how do I get pycharm to recognize django -
Execute code after Django init
I have a bunch of apps, that may or may not contains a file called activity.py. This file basically registers model signals. It works well when I import this file in the ready method of the AppConfig class. The problem is I have a dozen app, so I don't want to have this same method in all my apps : def ready(self): # register signal for activity feed from . import activity I would like to run a script that will through the INSTALLED_APPS array, and if this app contains a file activity.py, import it. I can't find a way to run a function for when all the apps are ready, and before the server is listening. -
How do i upload image to database from djang form?
I have tried this but did not work. picture = models.ImageField(blank=False) I select the file using the form button but it says "the field is required". -
django: "virtual" field w/o table
I'm working on a scheduling-framework for django. For this purpose, I need recurring events. These will be saved to db only once and any recurrence will be a copy of this source-event, without saving it to the db. (Saves happen only if something is changed.) Now I want to be able to retrieve events via slug. Slugs are made up of the source-events pk and the date. The idea is that when I encounter a query for a slug, I instead query the db for an event with the pk, copy and change the date (after conformation it's a valid one), and return this event. I have several approaches to this, but only the last works so far and it's quite hacky: Create a class VirtualField(models.Field), which catches every query for "slug" and throws errors if the query wasn't an exact-query. I have no idea how to do this. Write a custom QuerySet, which bypasses the db-query whenever a SlugField is to be retrieved. Would still require a slug-field and without 1. would create an unnecessary SlugField-column in the db. This would probably be done by replacing the iterator-method. Write a custom QuerySet with custom get, filter and exclude methods. … -
required field validator does not work in Django on azure
I have a simple registration form. Where people can fill the information and when they submit the form, data should come in the DB. The application is working fine in my localhost. I have some required field in my form. When I run the application on my localhost and I try to submit form without filling required field then it shows a pop-up and says that ** The field can't be empty ** , but when I deploy it on my azure portal and try to save this without filling required field then it generates the error: ValueError at /register/ The UserInformation could not be created because the data didn't validate. Request Method: POST Request URL: http://pythonfabric.azurewebsites.net/register/ Django Version: 1.9.4 Exception Type: ValueError Exception Value: The UserInformation could not be created because the data didn't validate. Exception Location: D:\home\site\wwwroot\env\Lib\site- packages\django\forms\models.py in save, line 446 Python Executable: D:\Python27\python.exe Python Version: 2.7.8 Python Path: [u'D:\\home\\site\\wwwroot\\env\\Lib\\site-packages', '.', 'D:\\Windows\\SYSTEM32\\python27.zip', 'D:\\Python27\\DLLs', 'D:\\Python27\\lib', 'D:\\Python27\\lib\\plat-win', 'D:\\Python27\\lib\\lib-tk', 'D:\\Python27', 'D:\\Python27\\lib\\site-packages', 'D:\\home\\site\\wwwroot'] Server time: Thu, 9 Feb 2017 19:17:07 +0000 register.html from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from app.models import UserInformation from django.utils.translation import ugettext_lazy as _ class UserInformationForm(ModelForm): firstName = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': … -
Generating user profiles with request.user rather than id in url
I am creating user profiles using Django 1.8. The way I have currently got it is the 'my_profile' view will use request.user() at the top of the view and then generate the information required from there. My question is weather this is a bad practise for creating profiles. In the past I have passed the user ID into the URL to create a profile but as it stands I think the request.user() method seems more secure and easier. Are there any negative implications in creating it like this such as speed issues etc.? Thanks in advance -
Need help in developing a scalable auto complete feature
I am developing a web application. It's backend is supported by Django. It has an auto-complete functionality. On each key press, a DB query is made (Using Mongodb for the Database) and results are sent back to the user. It works fine for few users but I am afraid as the users grow in numbers it won't be able to scale. Can anyone tell me, how can I make this system scalable? Thanks. -
Django Test case Error
I have problem of testing my django code. here, you can see my codes passed 46 test case.enter image description here however, when i tried to test on GIT CMD, by typing like python run_tests.py -u "Your GitHub repository" -s "student name" -d "YYYY-MM-DD" all the test case got failed... additionally, the test case recently changed something. so i just updated , then tried to test. it just repeat and repeat to test, which means does not work. -
How can I verify the user passwords in Django
Here a method that written inside the class in Django for handiling the post requests. def post(self,request): form=self.form_class(request.POST) users=User.objects.all() if form.is_valid(): username =form.cleaned_data['username'] password =form.cleaned_data['password'] return render(request,"quiz/logged_view.html",{'users':users}) There is username and password coming throught the form. How can I verify the password for a user? Thank You -
Passing extra paramters to a view class in redirect()
Is it possible to pass the extra parameters of a view class (i.e. the ones passed to the view class in kwargs in urls.py) in a redirect() call? -
How can I remove an object from a many to many for a queryset without iteration?
In Django, I have a many to many relationship between two models. I want to remove an instance of model_one from several instances of model_two. I have: user = User.objects.get(id=user_id) conversations = Conversation.objects.filter(users=user) for conversation in conversations.iterator(): conversation.users.remove(user) This needs to evaluate every single instance of Conversation. Is there a way to do this without iteration? -
Django gallery with jquery
I want to create image gallery. I have only miniatur without bigImage I don't know what i do wrong. {% extends "shop/base.html" %} {% load static %} {% block title %}{{ product.name }}{% endblock %} {% block content %} <script language="JavaScript" type="text/javascript"> $(document).ready(function () { $('#ImageGallery img').click(function () { var bigImagePath = '{{image.image.url}}' + $(this).attr('alt'); $('#bigImage').attr('src', bigImagePath); }) }) </script> <div id="ImageGallery"> {% for image in images %} <img src="{{image.image_url}}" alt="test" style="width: 100px; cursor: pointer;"> <div> <img id="bigImage" alt=""> </div> {% endfor %} </div> {% endblock %} ImageGallery is show on site without BigImage. I think my mistake is on jq -
Django redirect doesn't append to previous pattern
So I have this urls.py: url(r'^reg/$', views.reg_view, name='reg'), url(r'^logout/$', views.logout_view, name="logout"), url(r'^search/$', views.search_redirect, name='search_redirect'), url(r'^search/(?P<keyword>.*?)/page/(?P<page>[0-9]+)/$', views.SearchView.as_view(), name='search'), url(r'^search/(?P<keyword>.*?)/$', views.SearchView.as_view(), name='search'), url(r'^t/create/$', views.create_topic, name='create_topic'), url(r'^notifications/$', views.NotificationView.as_view(), name='notifications'), url(r'^avatar/$', views.upload_avatar, name="upload_avatar"), Those are icluded in the main urls.py as this(the forum one): url(r'^accounts/', include('userena.urls')), url(r'^forum/', include(niji_urls, namespace="niji")), url(r'^$', index, name="index"), url(r'^despre-noi/$', despre_noi, name='desprenoi'), url(r'^(mugshots/.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), url(r'^messages/', include('userena.contrib.umessages.urls')), url(r'^magazin/', include(application.urls)), # url(r'^magazin/', include('magazin.urls', namespace="magazin")), url(r'^oferte/', include('oferte.urls', namespace="oferte")), And there is this form: <form class="navbar-form navbar-left" role="search" method="get" action="{% url 'niji:search_redirect' %}"> <div class="form-group"> <input type="text" id="keywordInput" name="keyword" class="form-control" placeholder="{% trans 'Search' %}"> </div> <button type="submit" id="navSearchBtn" class="btn btn-default">{% trans 'Search' %}</button> </form> Views.py: class SearchView(ListView): model = Topic paginate_by = 30 template_name = 'niji/search.html' context_object_name = 'topics' def get_queryset(self): keywords = self.kwargs.get('keyword') query = get_query(keywords, ['title']) return Topic.objects.visible().filter( query ).select_related( 'user', 'node' ).prefetch_related( 'user__forum_avatar' ).order_by( get_topic_ordering(self.request) ) def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) context['title'] = context['panel_title'] = _('Search: ') + self.kwargs.get('keyword') context['show_order'] = True return context def search_redirect(request): if request.method == 'GET': keyword = request.GET.get('keyword') return HttpResponseRedirect(reverse('niji:search', kwargs={'keyword': keyword})) else: return HttpResponseForbidden('Post you cannot') The problem is that, when the user uses the form to submit a search query, the url becomes example.com/search/... instead of example.com/forum/search/.. . If I … -
Django - get Foreign Key first object in template
I can't get the Foreign Key first object without looping all foreign keys. I'm using Django 1.10.5. I have these models: class Ticket(models.Model): ... class Message(models.Model): ticket = models.ForeignKey(Ticket, related_name='messages') ... def __str__(self): return self.id And then in the template I do: <p>{{ object.messages.all|first }}</p> <p>{{ object.messages.all.0 }}</p> <p>{{ object.messages.all.1}}</p> {% for message in object.messages.all %} <p>{{ message}}</p> {% endfor %} And this prints in the template: 2 2 2 1 2 What is happening? -
Django form to display user attributes
I'm having an odd problem that I can't remedy: Django is not displaying any of the user's attributes except for the username when using a form that includes a foreign key attribute between two models. The associated username is showing up correctly, but none of the other attributes are (first name, last name, email, etc). Similarly, the debugging print statement that I've placed in the views.py is correctly printing the user's attributes in the terminal output. Why aren't any of the user's attributes showing up in the html template? models.py class UnitGroup(models.Model): unit_name = models.CharField(max_length=150, verbose_name='Unit Name') class UnitUser(models.Model): user = models.OneToOneField(User) unit = models.ForeignKey(UnitGroup) ROLES = ((0, 'Admin'), (1, 'Member')) role = models.IntegerField(null=True, blank=True, verbose_name='Role', choices=ROLES) def __string__(self): return self.user.first_name forms.py class UserGroupForm(forms.ModelForm): class Meta: model = UnitUser fields = '__all__' views.py from units.forms import UnitForm, UnitDetailsForm, UserGroupForm from units.models import UnitGroup, UnitDetails, UnitUser from django.contrib.auth.models import User def edit_members(request): if request.user.is_authenticated() \ and request.method == 'GET' \ and 'unit' in request.GET: unit_group = request.GET['unit'] unit_users = UnitUser.objects.filter(unit=unit_group) unit_forms = [] for i in unit_users: # debug print(i.user.first_name) print(i.user.last_name) unit_forms.append(UserGroupForm(instance=i)) return render(request, 'units/edit-members.html', {'unit_forms': unit_forms}) edit-members.html {% for form in unit_forms %} user: {{ form.user }} <br> first name: … -
Get cookie and set context generiv view
I am implementing a duplicate vote checking. I set a cookie in the vote view: cookie = request.COOKIES.get('voted') half_year = timedelta(weeks=26) expires = datetime.utcnow() + half_year if cookie and re.match(cookie_pattern, cookie): redirect.set_cookie('voted', cookie + question_id + '-', expires=expires) else: redirect.set_cookie('voted', question_id + '-', expires=expires) Now I want to access the cookie and than set a context variable in a generic details view. Is this possible or do I have to write a not generic one? -
Disable/enable a button but applying permissions first
So I know how to disable/enable a button when inputs in the same form are empty/filled. But let's say I have applied backend permissions first and disabled some buttons. How do I make sure they are not re-enabled when someone with no permissions writes in the input ? I can in theory also disable all inputs based on permission but can you suggest a better solution? Example in django template: <button type="submit" class="btn btn-default" id="my_button" {% if not can_post %}disabled{% endif %}>Apply </button> -
Rewriting API call to return the right queryset (is this possible)
Little side-project to do translations of lyrics. There is a table of Songs, each with various Lines. Every Line can have a Translation in a different Language. For a given Song I am looking to return a queryset of Languages with full translations. Meaning that the number of Translations equals the number of Lines for that song in the given Language. Even simpler: if the song "Row your boat" has 20 lines, I want to see the languages that also have 20 translations for that song. Here is what I came up with: >>> s = Song.objects.get(pk=2) # Get Row your boat >>> languages = Translation.objects.filter(line__song=s).values('language').annotate(total=Count('language')).order_by('total').filter(total=s.line_set.count()) >>> languages[0] <QuerySet [{'language': 1, 'total': 20}]> Looks like it works! The point is that I would rather see a queryset of Languages rather than this annotated queryset. Something like: >>> Language.objects.all() <QuerySet [<Language: en-US>, <Language: nl-NL>] How do I go from the annotated queryset to a proper queryset for further use? -
Django-Easy-Select2 override on one item in admin
I have a Model with multiple foreign keys. one of these is a self reference and there are 12,000 items in this table making the site unresponsive when select2 loads. as this field does not need to be edited too often Select2 is overkill but I cannot find any way to override it on just that field. The field is called previous and here is the code that I am using. admin.py shiurForm = select2_modelform(Shiur, attrs={'width': '350px'}) class ShiurAdmin(admin.ModelAdmin): fields = ('dir', 'path', 'title', 'content', 'previous', 'priority', 'relevantMonth', 'relevantWeek', 'holiday') list_display = ('title', 'path', 'previous', 'get_next', 'dir', 'relevantMonth', 'relevantWeek', 'holiday', 'created', 'lastModified') search_fields = ('title', 'path', 'previous__path') # form = shiurForm formfield_overrides = { models.TextField: {'widget': TinyMCEWidget()}, } def get_next(self, obj): return obj.nextShiur.path get_next.short_description = "Next" TL;DR a model has three foreign key previous, dir, and holiday as well as two more choice fields in relevantMonth and relevantWeek. is there any way to have easy-select-2 only run on the latter 4 and not the first one? -
How I can delete all the instances of a annotated queryset
I have an annotated queryset as follows. qs = BuyStock.objects.values('stock__name').filter(user=request.user).annotate(stock_name=Upper('stock__name')).distinct() qs1 = BuyStock.objects.values('stock__name').filter(user=request.user).annotate(ave_price=Avg('stock__purchase_price')) qs2 = BuyStock.objects.values('stock__name').filter(user=request.user).annotate(total_sum=Sum('quantity')) This I am combined in template and using, now I want to delete all instances of stock__name by a single delete button, is it possible, Thank you in advance for your advice. -
Displaying columns form a table on a webapage in Djano
I need to display a table from my database using only certain columns. In my view I have this: def home_page(request): query_results = Model.objects.filter(open=True) return render(request, 'home.html') and my home.html page looks like this: <table> <tr> <th>Column1</th> <th>Column2</th> </tr> {% for each item in query_results %} <tr> <td>{{ item.col1 }}</td> <td>{{ item.col2 }}</td> <tr> {% endfor %} </table> However, when I go to the page, there isn't any data in the table. Am I going about this wrong? Thanks for your help. -
Django: how to convert into string?
How can I convert string into Form? in model you can just use this line. model = apps.get_model(app_label='app_label', model_name='str_model') I have 3 forms namely: Fund_customer Fund_employee Fund_supplier and would like to do this. type = "customer" form = "Fund_"+type #that would make "Fund_customer" form = apps.get_form(form) #I wonder if there's a function like this. I just dont want to do if condition to achieve this.