Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the value of a variable in a view?
My queryset is currently the value of posts in my view. However I want to change my queryset to Post.objects.all().filter(category=category).order_by('-date') when the user navigates to the new url. Here's my code: urls url(r'^$', boxes_view, name='home'), url(r'^new/$', boxes_view, name='new'), views def boxes_view(request): ... posts = Post.objects.all().filter(category=category).annotate(score_diff=F('score__upvotes') - F('score__downvotes')).order_by('-score_diff') template ... <button id="sort_new"><a href="{% url 'new' %}">New</a></button> Is it possible to change the value of posts when going through the new URL? -
Save Dynamic Template as PDF to model in Django
I've tried quite a few options, but none seem to do what I need it to do, or at least I haven't figured it out. The ultimate goal of this project is to print a Django template to PDF (with dynamic fields and CSS), and then save that to a FileField in a model. I've tried weasyprint, django-easy-pdf, whtmltopdf (which isn't an option, I can't install whtmltopdf on the server), just xhtml2pdf, etc etc etc. My main source of ideas has been this post, but I still seem to be stuck. As of right now, the most success I've had was with djang-easy-pdf, where I got the view to return a PDF to the browser, but it didn't have any images or CSS on it. The work flow is as such: user fills out a form, the user hits "generate", the form data is grabbed from the form, and passed via a session to a PDFTemplateView (courtesy of easy-pdf), and the PDF is returned in the browser successfully, however, without pictures and CSS formatting. While this is progress, I would like the PDF to be saved to a FileFiled, and not returned to the browser (the user can download the … -
Nginx proxy_cache vs uwsgi_cache
We want to implement nginx caching for our Django app running via uwsgi. From resources online it seems that I can use either proxy_cache or uwsgi_cache configs in nginx. I could not find what is the difference between them as they seem to me identical. Only difference I can think of is that proxy_cache I can use with anything (should we decide to ditch uwsgi) while uwsgi_cache is specific to uwsgi. Would be great if anyone could explain what is the difference between them two. -
Django Bootstrap 4 unable to use scss
So I'm trying to set a 4 columns card view with the following: https://v4-alpha.getbootstrap.com/components/card/#card-columns Here is a successful online example: DEMO I followed this tutorial to setup django compressor: https://django-compressor.readthedocs.io/en/latest/quickstart/ I have following code in main.scss file: @import 'bootstrap'; .card-columns { @include media-breakpoint-only(lg) { column-count: 4; } @include media-breakpoint-only(xl) { column-count: 5; } } And I can't import bootstrap. I tried to put the bootstrap.css in the same folder, then system pops the error says: Error: no mixin named media-breakpoint-only I'm kind of new to this, how do I fix it ? Thanks -
Insert to mysql database through Rawsql
I want to perform custome sql query on mysql database table to store the record .What is the way to perform insert query through rawsql. -
ImportError: No module named misago
I get this error while installing Misago the forum. I don't know what's causing since I have Django installed. Please help me anyone. xxxxx@xxxxx:~/Desktop/newfeed/startupindia$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 23, in execute_from_command_line(sys.argv) File "/home/xxxxx/.local/lib/python2.7/site-packages/django/core/management/init.py", line 350, in execute_from_command_line utility.execute() File "/home/xxxxx/.local/lib/python2.7/site-packages/django/core/management/init.py", line 324, in execute django.setup() File "/home/xxxxx/.local/lib/python2.7/site-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/xxxxx/.local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/xxxxx/.local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named misago -
Pytest won't convert date field to datetime.date object in Django
I have this simple query written in Django and I want to run my tests with Pytest. results = (self.base_query .order_by('service_date') .extra({'sd': "date(service_date)"}) .values('sd') .annotate(created_count=Sum('pax_number'))) print 'RESULTS: ', results When I run my tests with Django's test runner: python manage.py test, I get expected result. RESULTS: <QuerySet [{'created_count': 14, 'sd': datetime.date(2017, 2, 24)}]> But when I do it with pytest: pytest -s I get RESULTS: <QuerySet [{'created_count': 14, 'sd': u'2017-02-24'}]> Why isn't my Pytest converting dates like Django's test runner? -
Django query set filtering, how to filter data on dynamic list
I am using django 1.10 and mongodb in backend. For mongodb I am using mongoengine 0.11. In mongodb, I have collection named "test_coll", which contains fields "name","dept" and "tag". Sample data from collection is as follow- name dept tag peter dev k1 mark tester k1 sachin dev k1 amit manager k1 I am providing list dept_list=['dev','tester'] This list is dynamic. Below is code from function from mongoengine import Q dept_list=['dev','tester'] output_list = [] query_dept objects = Q() for dl in dept_list: query_objects |= Q(dept__iexact=dl) for details in test_coll.objects.filter(((Q(tag__iexact='k1')) & query_objects )): output_list.append({'name':details.name,'dept':details.dept,'tag':details.tag}) return output_list As per list dept_list=['dev','tester'] and sample data provided above, I get details from collection where tag is 'k1' and dept are 'dev','tester'. So I am stuck at, if I provide, dept_list=[''] contains empty string then it should return all the data where tag='k1'. In my case it is not returning anything. Can anyone provide solution. Thanks in advance. -
Tech stack needed for mobile chat application
I am designing on a mobile based chat application which will feature group chat and personal chat. After searching on google, i found that there are more framework/db available than projects. Requesting code ninjas to help me deciding better tech stack. I am proficient in Python Django. Backend Framework : Django Questions Which db should i use to store chat?(SQL or NoSQL) How can i ensure fast delivery of messages like fb in group chat and in personal chat?(I am thinking about redis pubsub, but not sure) Will django be able to scale application? How could i ensure concurrency? Any help on architecture design(or any link) would be great. -
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:765) while sending FCM Push Notification
I am trying to send Push Notification using FCM. I have configure all stuff related to FCM. But while sending message I get "certificate verify failed" error. I want to bypass my SSL verification while sending FCM Push Notification. I refer this link to implement FCM : https://github.com/xtrinch/fcm-django Steps Followed: (After all settings and migrations) 1. from fcm_django.models import FCMDevice device = FCMDevice.objects.all() device.send_message("Title_Test", "Message_Test") After 3rd step I get following error: enter code here >>> from fcm_django.models import FCMDevice >>> device = FCMDevice.objects.all() >>> device.send_message("Title", "Message") Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/site-packages/fcm_django/models.py", line 52, in send_message **kwargs File "/usr/lib/python2.7/site-packages/fcm_django/fcm.py", line 47, in fcm_send_bulk_message **kwargs File "/usr/lib/python2.7/site-packages/pyfcm/fcm.py", line 190, in notify_multiple_devices return self.send_request([payload]) File "/usr/lib/python2.7/site-packages/pyfcm/baseapi.py", line 197, in send_request response = requests.post(self.FCM_END_POINT, headers=self.request_headers(), data=payload) File "/usr/lib/python2.7/site-packages/requests/api.py", line 108, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python2.7/site-packages/requests/api.py", line 50, in request response = session.request(method=method, url=url, **kwargs) File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 464, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 431, in send raise SSLError(e, request=request) SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:765) -
TypeError: 'float' object is not callable in a django code
@property def pmt_loaner_final(self): return float(self.pmt_loaner_new) + float(self.debit_fee) @property def pmt_broker_final(self): return float(self.pmt_broker_new) + float(self.debit_fee) @property def total_compounded_broker(self): return self.compounded_amount(self.brokerage_fees) @property def total_compounded_loaner(self): return self.compounded_amount(self.amount) def compounded_amount(self, amount): """ Return the amount of interest pad for a given days amount """ interests_amount = math.pow( (1 + self.daily_interest), self.padding_days) total_post_daily_extra_interest = float( amount) * float(interests_amount) return total_post_daily_extra_interest I have a function discount which give me the error : TypeError: 'float' object is not callable @property def discount(self): return self.final_credit_rate( self.pmt_loaner_final + self.pmt_broker_final, self.total_compounded_loaner + self.total_compounded_broker ) Could any be able to help me at this point? -
difficulty in viewing the changes in database(django) after changing html code
We created a database in django admin site for a website and when we first change or update the database by admin site and later when we made changes in its html code the change in the database is not reflected in the database its displaying the previous database. For hosting the website we used heroku platform after we make changes in html code we run the commands git add -A and git commit -m "changes" and git heroku master . after running this the database we changed in django admin site is not taking the previous database it is not updating. -
Implementing django remote code development in Pycharm
I am trying to replicate a remote lab server django project on my local machine in pycharm full-blown professional version. I have followed all the required steps, but somehow I get the error "No files or folders found to process" when I try to download files from remote path. Initially it was working, but then I was having issues setting up the django runserver in the lab server to work in my local project. I am not sure if Vagrant will work, because as far as I have read, it is for creating a new remote VM. Any help would be greatly beneficial. -
How to make a function inside a model act like a field?
I have a Post model that links wth PostScore through ForeignKey: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) ... class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) def trending(self): score = self.upvotes - self.downvotes return score So when I try to sort my Posts like this: posts = Post.objects.all().order_by('-score__upvotes') It works fine but how would I be able to sort by trending?: posts = Post.objects.all().order_by('-score__trending') the above code creates this error: FieldError at /news/ Cannot resolve keyword 'trending' into field. Choices are: downvotes, id, post, post_id, upvotes, user, user_id -
How to mark a field as validated (for accessing in validated_data) in validate(self)?
Let's say I have a field I want to validate/clean. I'd normally go about it like this for a field I know I will use. def validate_number(self, value): if value == 7: raise serializers.ValidationError('7 is bad!') if value == 5: return None # I want 5 to come back as None return value Let's say I'm not sure which fields I have on validation and I go through these fields in validate(), How would I achieve this same behavior? def validate(self, data): if data['number'] == 7: raise serializers.ValidationError('7 is bad!') if data['number'] == 5: data['number'] = None return data Would I be able to access this as validated_data in a .create/.update method? -
Django - ajax call for loading page not working
I need really help.. I'm not good at front-end and I'm very confused with Ajax. I'm trying to do an Ajax call for when I click on a button of my table so when I hit that button my ajax should show my animation .gif so the user should know that the page is loading. my template: <style> .ajaxProgress{ display:none; text-align: center; } </style> <div id="output"> <div class="ajaxProgress"> <h3>Please wait..</h3> <img src="{% static 'img/ajax.gif' %}" alt="loading"/> </div> </div> {% for item in qs %} <tr> <tbody> <td a id="mqtt" class="btn btn-xs btn-info" title="mqtt" href="javascript: startAjax(){% url 'start_mqtt' item.id %}"><span class="fa fa-signal"></span> </a> </td> </tbody> </tr> {% endfor %} </table> <script> function startAjax() { $('.ajaxProgress').show(); $.ajax({ type: "GET", dataType:"json", async: true, data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(json){ $('#output').html(json.message); $('.ajaxProgress').hide(); GetRating(json.message); } }) } </script> Basically what I need is when I hit on the button should start my .gif but nothing happens.... Could anyone help me? Thanks in advance!! -
How to send a message to a Channel from a Command
How do you send a message to a Django Consumer from a custom manage.py command from django.core.management.base import BaseCommand, CommandError from channels import Channel class Command(BaseCommand): help = 'Sends a message to a Django channel from the thing' def add_arguments(self, parser): parser.add_argument('json_object', nargs='+', type=str) def handle(self, *args, **options): self.stdout.write("TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") print Channel("test").channel_layer Channel("test").send({'op':options['json_object'][0]}) This is my consumer class MyConsumer(WebsocketConsumer): @classmethod def channel_names(self): return {"test"} def connection_groups(self): return ["test"] def dispatch(self, message, **kwargs): return self.get_handler(message, **kwargs)(message, **kwargs) def get_handler(self, message, **kwargs): channel_routing = [ consumers.MyConsumer.as_route(path=r"^/test/"), route("test.receive", consumers.chat_join), ] for _filter, value in kwargs.items(): filter_mapping = getattr(self, _filter + '_mapping', None) if not filter_mapping: continue consumer = getattr(self, filter_mapping.get(value), None) if consumer: return consumer raise ValueError('Message') def connect(self,message): self.message.reply_channel.send({"accept": True}) def receive(self,text=None, bytes= None): print text def disconnect(self,message): pass When I try to run the command however, I get this message 2017-03-08 03:45:33,839 - ERROR - worker - Could not find match for message on test! Check your routing. In case it is pertinent, here is my routing channel_routing = [ consumers.MyConsumer.as_route(path=r"^/test/"), ] -
Good way to create relationship between django users only if both parties agree to the relationship
I'm looking to create a one-to-one relationship between two types of Django users. I want one user to initiate a request for relationship creation and I want to create it only if the second user agrees to it. Is there a good way to remember the request to create the relationship but only actually create it once the second user agrees to it with Django? -
Django allauth Faceook authentication: Reverse for 'facebook_login_by_token' with arguments '()' and keyword arguments '{}' not found.
I have looked everywhere on the internet for an answer to this problem but cannot find anything. I run into this issue whenever I try to access /accounts/login/ I have added the ID and secret key to my django admins page and added localhost:8000 to my Sites model as well as my Facebook app. I do not only run into this problem when developing custom applications. I also run into this issue when I clone the allauth repo from github and follow the installation steps with the example application. Help would be much appreciated. -
How to use reverse an url with extra arguments in a django template tag?
I have created a template tag in django for forms that only require a submit button, without any other fields (except the hidden csrf field). It can be used as follows: {% button_only_form "button_text" "action/path" "optionally css classes. %} I'm currently mainly using this for delete buttons, because delete views require sending a post request, but don't need any other data. Now I'm finding myself in a situation where I need to dynamically create the action. I'm iterating over a list of items, and the action url for each item would be the result of calling reverse("items:delete", kwargs={"item_id": item.id}) How would I specify this for my template tag? Here's a hugely simplified version of my template: <ul> {% for item in items %} <li> {{item.title}} - {% button_only_form "Delete" Im_not_sure_how_to_pass_the_action %} </li> {% endfor %} </ul> -
can't view alternative languages when using django internationalization
I implememnting internationalization and localization in django I have as a first test for Spanish, some simple text in a template: {% load i18n %} <h2>{% trans 'How It Works' %}</h2> I have added the following to my settings: USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGE_CODE = 'es' from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('ca', _('Catalan')), ('es', _('Spanish')), ) I have generated the .po translation files with: django-admin makemessages I have created a sample translation with: #: templates/index.html:112 msgid "How It Works" msgstr "espanol test" I have changed my chrome browser to use spanish language like according to: https://developer.chrome.com/extensions/i18n#testing-mac I would figure that when I go to my page that the "how it works" text would say "espanol test" but it does not. Am I doing something wrong to not render the translation? -
Creating a url for an s3 photo without expiration?
I'm using a Django User models to store my users. My user will have the usual: name, username, password. Here's an example: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True) photo_url = models.CharField(max_length=200, blank=True, default='') # the url to fetch photo There will be one field that I will need to generate a url for and that is the url for the photo he uploaded to S3, that way my client can download it and display it. What's the best way to generate an indefinite url in boto3? -
Form validate like GenericView
When using Generic views, you get the neat feature of django posting the error messages in the template such as "This field is required!". From what I understand CreateView inherits a method called form_invalid which returns self.render_to_response(self.get_context_data(form=form)) And I'm just guessing that's what's doing the magic? Now I'm writing a form, and was wondering if it's possible to use that feature aswell? I have created a custom_user model, and trying to create a simple create functionality. So far I've got: Models.py class Custom_User(AbstractBaseUser): email = models.EmailField(max_length=250, unique=True) password = models.CharField(max_length=100) USERNAME_FIELD = 'email' forms.py class create_User_Form(forms.ModelForm): confirm_password = forms.CharField(widget = forms.PasswordInput(attrs={'class' :'form-control'})) class Meta: model = Custom_User fields = ['email', 'password'] widgets = { 'email' : forms.TextInput(attrs={'class' :'form-control'}), 'password' : forms.PasswordInput(attrs={'class' :'form-control'}), } def clean(self): cleaned_data = super(create_User_Form, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) return self.cleaned_data urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^create_user/$', views.create_user, name='create_user'), ] views.py def create_user(request): form = create_User_Form(request.POST) if form.is_valid(): print('valid') else: print('error') return redirect('Eapp:index') -
Django model foreignkey queries
So i have this two models in django: class Course(models.Model): def get_image_path(self, filename): return os.path.join('courses', str(self.slug), filename) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Course, self).save(*args, **kwargs) name = models.CharField(max_length=255, verbose_name="Nombre") description = models.CharField(max_length=255, verbose_name="Descripción") price = models.DecimalField(max_digits=12,decimal_places=2, verbose_name="Precio") slug = models.SlugField(blank=True, max_length=255) icon_img = models.ImageField(upload_to=get_image_path, blank=True, null=True, verbose_name="Imagen") background_color = ColorField(default="#026085") class Meta: verbose_name = "curso" verbose_name_plural = "cursos" class UserCourse(models.Model): user = models.ForeignKey(User) course = models.ForeignKey(Course) So whenever a user "buys" a course, it is stored in UserCourse. I have a view where the system shows a list of all the courses the user has bought. This is the view code: def user_course_list_view(request, username): context_dict = {} try: user_courses = UserCourse.objects.filter(user=request.user).course_set context_dict['courses'] = user_courses context_dict['heading'] = "Mis cursos" except: context_dict['courses'] = None context_dict['heading'] = "Mis cursos wey" return render(request, 'courses/course_list.html', context=context_dict) I dont know where is the error and I cant seem to catch the exception (im using django with docker) -
Accessing the Input Type from forms in Django
I am trying to access the Input Type to use in HTML but it appears to coming through as blank. According to: Django: How to access form field input_type in a template I should be using: {{field.field.widget.input_type}} But it seems to be returning blank. CODE: {% for field in form %} <div class="form-group"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> <input type="{{field.field.widget.input_type}}" class="form-control" name="{{ field.name }}" id="id_{{ field.name }}" value="{{ field.value }}" > </div> {% endfor %} Thanks very much in advance.