Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize all fields of django model, but validate only particular one?
Imagine I have model and in my API method I want behaviour like "return all model fields if instance exists else return some message". So I want my serializer to validate only by id (not all fields, because I have only id parameter in my method), but return all fields of the model. How can I implement this? Should I have 2 separate serializers for validation and for serialization? -
Output the values of the variables of django rest framework
hello i have project on django rest framework and angularjs often need for debugging output some variable of backend, Is there simple a way output the values of the variables ? -
How to append link to <a> element using Javascript
I want to add href to an a html element from class of another element. It might also be good to know that i am using Django.As well i dont want the second url to be visible, when the character is not selected yet. Firstly i have this list: <ul> <a class="1" id="tablink">A</a> <a class="2" id="tablink">B</a> ... </ul> if list from the first ul is selected, i want the class of the list (example: A) to add to href element to all links in another ul: <ul> <a href="{% url id=id character= <!--here i want the number selected to be inserted--> %}">One</a> <a href="{% url id=id character= <!--here i want the number selected to be inserted--> %}">Two</a> ... </ul> Thank you! -
Django 1.11 download file chunk by chunk
In my case I have the Django 1.11 server acting as a proxy. When you click "download" from the browser, it sends a request to the django proxy that downloads files from another server and processes them, after which they must "send" them to the browser to allow the user to download them. My proxy downloads and processes the files chunks by chunks. How can I send chunks to the browser as they are ready so that the user finally downloads a single file? In practice I have to let you download a file that is not yet ready, like a stream. def my_download(self, res) # some code file_handle = open(local_path, 'wb', self.chunk_size) for chunk in res.iter_content(self.chunk_size): i = i+1 print("index: ", i, "/", chunks) if i > chunks-1: is_last = True # some code on chunk # Here, instead of saving the chunk locally, I would like to allow it to download it directly. file_handle.write(chunk) file_handle.close() return True Thank you in advance, greetings. -
Django 1.10 UUIDField returns either string or UUID
While upgrading from Django 1.9.13 to Django 1.10.7 I encountered a weird issue with Django's native UUIDField. We use this UUIDField on our custom User model like: username = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) In 1.9 this always returns a UUID instance. In 1.10 this returns a string when creating a new model instance. Compare the following test examples: 1.9.13 >>> u = User.objects.last() >>> u2 = UserFactory() >>> u3 = User.objects.create() >>> u.pk UUID('e7e0f87d-1ed4-4293-829f-b0b745ccd676') >>> u2.pk UUID('f8e9a4a9-2265-4cd7-9813-00ffe7fd922a') >>> u3.pk UUID('0cb736d7-f8a0-4057-9c89-44fa114f4f82') 1.10.7 >>> u = User.objects.last() >>> u2 = UserFactory() >>> u3 = User.objects.create() >>> u.pk UUID('e7e0f87d-1ed4-4293-829f-b0b745ccd676') >>> u2.pk 'f8e9a4a9-2265-4cd7-9813-00ffe7fd922a' >>> u3.pk '0cb736d7-f8a0-4057-9c89-44fa114f4f82' This difference gives issues with various unittests. I can work around it by forcing both to string, but I wish to understand why UUIDField behaves the way it does as it feels inconsistent. -
Django object manager 'lower' parameter
I am trying to filter out a queryset based on if one of its field names is in a list of lower case values. The trouble is that some of these field values have capital letters, so I can't do all_listings = all_listings.objects.filter(make__name__in=makes) Is there a possible way to say something along the lines of all_listings = all_listings.objects.filter(make__name__lower__in=makes) -
What is better Django channel or RabbitMQ web mqtt plugin?
I've one web application listening on particular channel using websocket.I've used Django web channel for live notifications. RabbitMQ provides web mqtt plugin for socket communication. My question is what to use ? Which is better ? Pros and Cons of both.Any help would be great. -
MultipleChoiceField create multiple objects
I use MultipleChoiceField in my form. I want to add all selected values to database, but next code which I use add only last value which user select. I tried in my view create multiple number objects. Where I did mistake? models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: class AddForm(forms.ModelForm): symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) views.py: def requirement_add(request): data = dict() if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'} symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C'] requirement = form.save(commit=False) for symbol in symbols: requirement.symbol = symbol requirement.name = group_requirement_list[symbol] requirement.save() data['form_is_valid'] = True requirements = Requirement.objects.filter() context = {requirement': requirement, 'requirements': requirements} data['html_requirement'] = render_to_string('project/requirement_list.html', context) else: data['form_is_valid'] = False else: form = AddForm() context = {'form': form} data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request) return JsonResponse(data) -
Stripe Connect with Python Django
I'm trying to set up stripe connect in a Python/Django application so that I can have a number of contractors taking work from a site and being paid directly. I'm trying to get authorisation by getting a token for a new contractor. I've got the following view: def authorise(request): site = 'https://connect.stripe.com' + '/oauth/authorize' params = { "response_type": "code", "scope": "read_write", "client_id": STRIPE_CLIENT_ID } # Redirect to Stripe /oauth/authorize endpoint url = site + '?' + urllib.urlencode(params) return redirect(url) This will take me into Stripe to setup a connection but when I select the stripe connect button on the Stripe site I get: 127.0.0.1 refused to connect. My callback URL is 127.0.0.1/contractor/stripe_contractor_callback and the url call is: http://127.0.0.1/contractor/stripe_contractor_callback?scope=read_write&code=my_text_code What am I missing? -
Customize context data
I have three class. The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant context["state"] = Perception.state #This has not solved my problem return context Actually, the context of CustomerPerceptionIndexView did not contain the attribute state. I would like to get access state attribute from Perception class in the context of CustomerPerceptionIndexView class. How could I do such thing? Thanks in advance! P.S. To be clear, I want to fix the error AttributeError: 'str' object has no attribute 'state'. I don't think I have to add 'state' like context["state"] = Perception.state. Furthermore, please let me know if I have to add something in the question. I don't have a lot of experience with Django, and your … -
django-rest-auth: what is access_token and what code
For someone this can be trivial question but for me is not because i am beginer with django. I am using django-rest-auth to make restful registration of users. I succeed with standard (email, password) authentication and email confirmation (verification). But problem is in social login because i want to allow users to login with facebook (google+) account. I know how to make facebook App and get its SOCIAL_AUTH_FACEBOOK_KEY and SOCIAL_AUTH_FACEBOOK_SECRET. What i don't know is how to use api call to make login. By docs http://django-rest-auth.readthedocs.io/en/latest/api_endpoints.html it says url is /rest-auth/facebook/ and also i need to provide access_token and code. My question is what is access_token and what is code parameter and how to get them so i can try example with curl. Thank you. -
Django rest framework, set the api response Content-Encoding to gzip
Am working on django project, that act as a distribution server to other server when they request for some certain data through and api call, this data is in form of JSON and is very large. So i was thinking is there any way i can set my DRF APIView response to serves the outputted JSON response with gzip set for the Content-Encoding so as to reduce the size of the content, when consuming by the other servers. Currently my application is running on gunicorn with nginx on the front as a proxy. -
How to use django admin display some specific order data
I have model below class SynonymQuery(models.Model): original_query = models.CharField(max_length=30,verbose_name = "query") insert_time = models.DateField(auto_now_add=True) admin below class synonym_queryAdmin(admin.ModelAdmin): ordering = ('update_time','original_query') data 1.bcd time 2.abc time 3.bcd time if No.1 data is insert last time, I want to show data all the same original_query as No.1 in the header lines. I try to use ordering function, but result are incorrect. -
How to customize Django messages?
I'm trying to integrate this snippet into our Django project: It's just custom HTML and CSS for messages. The html looks like this: <div class="bs-calltoaction bs-calltoaction-success"> <div class="row"> <div class="col-md-9 cta-contents"> <h1 class="cta-title">Its a Call To Action</h1> <div class="cta-desc"> <p>Describe the action here.</p> <p>Describe the action here.</p> <p>Describe the action here.</p> </div> </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> So if I want to integrate it with messages framework, I can do: {% for message in messages %} <div class="bs-calltoaction bs-calltoaction-{{ message.tags }}"> <div class="row"> <div class="col-md-9 cta-contents"> {{ message }} </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> {% endfor %} But I would like to specify header <h1> and list of sub-messages <p> so it would be: {% for message in messages %} <div class="bs-calltoaction bs-calltoaction-{{ message.tags }}"> <div class="row"> <div class="col-md-9 cta-contents"> <h1 class="cta-title">{{ message.title }}</h1> <div class="cta-desc"> <p>{{ message.submessages.0 }}</p> <p>{{ message.submessages.1 }}</p> </div> </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> {% endfor %} Is it possible using Django messages? -
Receiving users of a group on Django
I want to collect all users of all groups of a spesific user in an object. How can I do this: from django.contrib.auth.models import User, Group user = request.user groups = user.groups.all() # ???? # #friendgroups = [] #for group in groups: # friendgroups =+ User.objects.filter(groups=group) # ???? # -
Customize context data
I have three class. The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant context["state"] = Perception.state #This has not solved my problem return context Actually, the context of CustomerPerceptionIndexView did not contain the attribute state. I would like to get access state attribute from Perception class in the context of CustomerPerceptionIndexView class. How could I do such thing? Thanks in advance! P.S. To be clear, I want to fix the error AttributeError: 'str' object has no attribute 'state'. I don't think I have to add 'state' like context["state"] = Perception.state. Furthermore, please let me know if I have to add something in the question. I don't have a lot of experience with Django, and your … -
subsequent ajax responses are very slow
In the all apps ajax are generally very fast,in one particular app(newly developed) for the first time also ajax response is fast but on the subsequent calls ajax response is very slow thereafter in the rest of the app's ajax responses also very slow, Is there any way to debug the issue? im saving few values in session also in the new app. any help is highly appreciated. -
How to setup 1.1 version of django?
I wanna read a book in django caled "Practical Django projects second edition", but it is outdated as the version of django used in the book was 1.1. I really wanna read this book because it really fits my needs as i working on a project with the same theme, but i have no idea how to run the examples or use django 1.1. Any suggestions? -
Django template table
I have 3 dictionaries data['d1'], data['d2'] and data['d3']. What i want is the table to look like this, getting the keys from each dictionary and presenting them like: Team 1 | Team 2 | Team 3 key 1 from d1 | key 1 from d2 | key 1 from d3 key 2 from d1 | key 2 from d2 | key 2 from d3 key 3 from d1 | key 3 from d2 | key 3 from d3 key 4 from d1 | key 4 from d2 | key 4 from d3 What i have tryed <thead> <tr> <th>Team 1</th> <th>Team 2</th> <th>Team 3</th> </tr> </thead> <tbody> <tr> {% for key, value in d1.items %} <td>{{ key }}</td> {% endfor %} </tr> <tr> {% for key, value in d2.items %} <td>{{ key }}</td> {% endfor %} </tr> <tr> {% for key, value in d3.items %} <td>{{ key }}</td> {% endfor %} </tr> </tbody> or <thead> <tr> <th>Team 1</th> <th>Team 2</th> <th>Team 3</th> </tr> </thead> <tbody> {% for key, value in d1.items %} <tr> <td>{{ key }}</td> </tr> {% endfor %} {% for key, value in d2.items %} <tr> <td>{{ key }}</td> </tr> {% endfor %} {% for key, value in … -
Send Email via AjaxCreateView with SparkPost/Gmail in Django
I tried to save a custom Form in my Django CMS Database. I need to send a Email confirmation in the Ajax Created form via SMTP / SparkPost. I am using Djano-FM to create the Ajaxviews A Custom Form works and the email is bein sent. The problem is now that i need to send a Email via Ajaxcreatview and thats how my created view looks like. class Probefahrtcreate(AjaxCreateView): form_class = ProbefahrtForm To send a email i need the function send_mail. that would look like send_mail('Using SparkPost with Django', 'This is a message from Django using SparkPost!', 'django-sparkpost@sparkpostbox.com', ['to@example.com'], fail_silently=False) When i try to add the send mail function in the AjaxCreateview the ajaxview is not being loaded anymore and i cant add the send_mail function. How Can i add the send mail function to validate the form and send it in the needed Ajaxview? Thanks in advance -
While I running my django project I am getting "ImportError: Module "logging.config" does not define a "dictConfig" attribute/class" error
I am running my Django project using manage.py runserver but it fails to start n giving following error C:\Users\Indrajit\Desktop\Mhakave\APp\src>manage.py runserver Unhandled exception in thread started by <function wrapper at 0x039466F0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\log.py", line 69, in configure_logging logging_config_func = import_string(logging_config) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\module_loading.py", line 27, in import_string six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) File "C:\Python27\lib\site-packages\django-1.10-py2.7.egg\django\utils\module_loading.py", line 23, in import_string return getattr(module, class_name) ImportError: Module "logging.config" does not define a "dictConfig" attribute/class what should I do -
How to call django decorator only once per session?
i want to call custom decorator only once per session def cust_decorator(function): def wrapper(request,*args, **kwargs): ........ ....... wrapper.__doc__ = function.__doc__ wrapper.__name__ = function.__name__ return wrapper i want to call cust_decorator decorator only once per session for a particular user -
Reverse Count of ManytoManyField with a condition
I have a usecase where I have to count occurences of a ManyToManyField but its getting more complex than I'd think. models.py: class Tag(models.Model): name = models.CharField(max_length=100, unique=True) class People(models.Model): tag = models.ManyToManyField(Tag, blank=True) Here I have to come up with a list of Tags and the number of times they appear overall but only for those People who have >0 and <6 tags. Something like: tag1 - 265338 tag2 - 4649303 tag3 - 36636 ... This is how I came up with the count initially: q = People.objects.annotate(tag_count=Count('tag')).filter(tag_count__lte=6, tag_count__gt=0) for tag in Tag.objects.all(): cnt = q.filter(tag__name=tag.name).count() # doing something with the cnt But I later realised that this may be inefficient since I am probably going through People's table many times (Records in People are way larger than those in Tag). Intuitively I think I should be able to do one iteration of Tag's table without any iteration of People's table. So then I came up with this: for tag in Tag.objects.all(): cnt = tag.people_set.annotate(tag_count=Count('tag')).filter(tag_count__lte=6).count() # doing something with the cnt But, first, this is not producing the right results. Second, I am thinking this has become more complex that it seemed to be, so perhaps I am complicating … -
__str__ method not being invoked in this django application when calling from foreignkey field
I have this model: class Country(models.Model): name=models.CharField(max_length=100,unique=True) createdon=models.DateTimeField(auto_now_add=True) updatedon=models.DateTimeField(auto_now=True) def __str__(self): return self.name class Guest(models.model): nationality=models.ForeignKey(Country,related_name='guest-nation') in my views.py, I do this: guest=Guest.objects.all().values('nationality') In my template: {% for info in guest %} {{ info.nationality }} {% endfor %} Now, I am hoping the nationality field to return name of the country but it returns id of the country (as stored in nationality_id) field. From the documentation, I understood it is supposed to return the value specified in the str method. I can access the name if i the values is nationality__name. It looks uglier than I thought and I am somehow convinced it is supposed to call the str method. Am I wrong? -
Django Like count is not incrementing
I added a like button to my site and it gets highlighted when clicked on it but does not increment the number of likes or shows the count in the admin. I am not understanding what is the mistake I have done. Please help me to solve this. My code is as follows. models.py class Post(models.Model): post = models.TextField() user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likes = models.IntegerField(default=0) def __str__(self): return self.post views.py @login_required def about(request,pk): context = {} template = 'about.html' return render(request, template, context) post = get_object_or_404(Post, pk=pk) Post.objects.get(pk=pk) post_id = post.pk liked = False if request.session.get('has_liked_' + str(post_id), liked): liked = True print("liked {}_{}".format(liked, post_id)) context = {'post': post, 'liked': liked} return render(request, 'imagec/about.html', {'post': post}) @login_required() def like_post(request): liked = False if request.method == 'GET': post_id = request.GET['post_id'] post = Post.objects.get(id=int(post_id)) if request.session.get('has_liked_'+post_id, liked): print("unlike") if post.likes > 0: likes = post.likes - 1 try: del request.session['has_liked_'+post_id] except KeyError: print("keyerror") else: print("like") request.session['has_liked_'+post_id] = True likes = post.likes + 1 post.likes = likes post.save() return HttpResponse(likes, liked) urls.py url(r'like_post/$', imagec_views.like_post, name='like_post'), about.html <p> <strong id="like_count">{{ post.likes }}</strong> people like this category {% if user.is_authenticated %} <input type="button" onclick="jQuery(this).toggleClass('active')" data-post_id="{{post.id}}" id="likes" value ='Like'> {% …