Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model forms fields template dry
We have a django application with tons of forms with generic template for rendering all form fields. Here is an example of one such form template. {% for field in form %} {% include "templates/_pratial/_field.html %} {% endfor %} _field.html <div class="form-group"> {{ field }} </div> forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield'].widget.attrs.update({'class' : 'form-control'}) Now we are updating our layout with new html , our form now should look like this <div class="form-group "> <label class="control-label" for="email"> {{ field.label }} </label> <div class="input-group"> <div class="input-group-addon"> <i class="{{ field.?? }}"></i> //fa fa-envelope-o </div> {{ field }} </div> </div> How can i dynamically insert fa fa-envelope-o, without breaking dry Some thing like self.fields['myfield'].icon = "fa fa-envelope-o" in form init and can be easily used in template like {{ field.icon }} -
Django multiple dynamic databases after server startup
I'm new to django and try to figure out what would be the best solution for me to use dynamically multiple databases in django. I know django is able to work with multiple databases registered in the settings.py file but In my case I have one main database (sqlite) which acts as my repository, I created all the models, the rest api viewsets for this one. The user can choose to connect to a database by entering the connection information and then I will need to gather data from this database and insert it to my repository. The user can register multiple databases through the app. How can django work with those dynamic databases? Should I register them in the settings.py? Each view in the frontend maps to a specific database and I will need to switch context between them. Any help or insight would be appreciated, I didn't find anything matching my use case on the internet. -
plain text code parameters VS environment variables for web applications?
When we define settings for web applications, we face the choice to use plain text information on code or to request environment variable. Examples : (Stripe_KEY, Database name, Database password, ALLOWED_HOSTS for CORS, etc.) Concrete example on django : ALLOWED_HOSTS = [os.getenv('ALLOWED_HOSTS', '*')] VS ALLOWED_HOSTS = ['localhost:8000'] -
Django pass variable to URL tag
I am using Django 1.11. I am trying to add a link to a DeleteView template from the UpdateView. There is probably a better way to acheive this than the way I am attempting but I am new to Django and so the way i'm trying is to use a URL to direct to myapp/<pk>/delete/ In my template I have {% url 'calendar_delete' pk=event_id %} In my model I have class Event(models.Model): event_id = models.AutoField(primary_key=True) In my URLs I have url(r'^calendar/(?P<pk>\d+)/delete/$',views.CalendarDelete.as_view(),name='calendar_delete'), With the code as above the template doesnt render due to NoReverseMatch exception. '{'pk': ''}' not found, so its obviously not picking up the event_id from the model. When I hardcode a number in there it will render and the URL will direct me to the DeleteView template. Can anyone advise how I can get the <pk>/event_id into the URL tag? The <pk> exists in the URL of the UpdateView template and I have also tried to extract it from the URL as a variable and pass to the URL tag. I can extract ok but not pass in the variable. Any help on this would be much appreciated, including advice on better methods to use for the desired … -
Elastic search TransportError(400, 'search_phase_execution_exception', 'No mapping found
I am working with elasticsearch-dsl-py and django, and trying to implement the sorting mechanism in Text() field. The query for elastic search is s = Search(using=client, index="pustakalaya", doc_type=DocumentDoc).query("match_all").sort( 'title.keyword', ) # This is throwing error. as shown below. response = s.execute() Even though there is a title field which is a Text() type. I don't know why this is throwing error. If I remove keyword from title.keyword the error will be. TransportError(400, 'search_phase_execution_exception', 'Fielddata is disabled on text fields by default. Set fielddata=true on [title] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.') My mapping in elastic search is { "_index" : "index", "_type" : "document", "_id" : "b7f029bf-196c-4819-a17f-c2bd424710d8", "_score" : 1.0, "_source" : { "keywords" : [ "science fiction" ], "communities" : [ "literatures and arts" ], "author_list" : [ null ], "publication_year" : "2017-10-30", "year_of_available" : "2017-10-30", "collections" : [ "English Literature" ], "thumbnail" : "uploads/thumbnails/document/2017/10/30/thumb.png", "license_type" : "copyright retained", "created_date" : "2017-10-30T04:56:09.122064+00:00", "abstract" : "as k", "type" : "document", "publisher" : "Shree ram publication", "document_type" : "book", "updated_date" : "2017-10-30T05:02:09.720040+00:00", "document_interactivity" : "yes", "title" : "Mero kabita", "document_total_page" : … -
how to set Session time out in django 1.11
I am trying to set session time_out for admin in my django==1.11 . but it did not work with any of the following i tried please help me for better solution thanks in advanced other then this option if any solution is welcome. SESSION_EXPIRE_AT_BROWSER_CLOSE= True SESSION_COOKIE_AGE = 10 SESSION_IDLE_TIMEOUT = 10 SESSION_SAVE_EVERY_REQUEST = True SESSION_INACTIVITY_TIMEOUT_IN_SECONDS = 10 AUTO_LOGOUT_DELAY = 10 -
Virtual Environment installation Error
When I try to install a virtual environment in my local system. I'm getting this error.Could you please help me out to fix this issue $ pip -V pip 9.0.1 from /home/sysadmin/.local/lib/python2.7/site-packages (python 2.7) $ sudo pip install virutalenv sudo: unable to resolve host sysadmin-Veriton-M200-H61 The directory '/home/sysadmin/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/sysadmin/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virutalenv Could not find a version that satisfies the requirement virutalenv (from versions: ) No matching distribution found for virutalenv -
DRF - Set max and min value of a Serializer field
I've a serializer where I need to set the min and max value. Currently, this is how I do. class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products extra_kwargs = { 'amount': {'min_value': 10000, 'max_value': 60000}, } This works fine, but I don't want to hardcode it, ie I want to fetch it from the DB, just in case the value changes. I've 2 models. 1) Category which has min & max value in it. 2) Products which has amount and category as a FK. The amount entered should be within the range of min-max. How can this be achieved? For eg:- Anything of this sort. extra_kwargs = { 'amount': {'min_value': Category.min, 'max_value': Category.max}, } -
Django compare queryset from different databases
I need to compare 2 querysets from the same model from 2 different databases. I switched db's on the fly, make 2 querysets and try to compare them (filter, or exclude) # copy connections connections.databases['tmp1'] = connections.databases['ukm'] connections.databases['tmp2'] = connections.databases['ukm'] # get dbs from form db1 = DB.objects.get(pk=form.cleaned_data['db1'].id) db2 = DB.objects.get(pk=form.cleaned_data['db2'].id) # left connection connections.databases['tmp1']['HOST'] = db1.host connections.databases['tmp1']['NAME'] = db1.name articles1 = list(Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ')) # right connection connections.databases['tmp2']['HOST'] = db2.host connections.databases['tmp2']['NAME'] = db2.name articles2 = list(Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ')) # okay to chain Smdocuments objects all = list(chain(articles1, articles2)) # not okay to diff sets of objects diff_set = set(articles1) - set(articles2) # not okay to exclude sets from different db articles_exclude = Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ') len(articles1) diff_ex = Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ').exclude(id__in=articles_exclude) len(diff4) So, "Model objects" not so easy to manipulate, and querysets between difference databases as well. I see, thats not a good db scheme, but it's another application with distributed db, and I need to compare them. It's would be enough to compare by one column, but probably compare full queryset will work for future. Or, should I convert queryset to list and compare raw data? -
what are sockets - uwsgi / nginx - django
I am going through this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html but i don't know what is the socket file, mysite.sock in this case. Could you tell me what is this file and what should be inside ? thanks -
Django migrate command fails with change in foreign key related name
I have a model with a foreign key field. I want to give the foreign key a related name. However, migration fails because of the following error: IndexError: list index out of range I'm using Django==1.10.5 Database backend is PostgreSQL models.py Before/After migrations Before: class Contest_participants(models.Model): contest = models.ForeignKey(Contest) After: class Contest_participants(models.Model): contest = models.ForeignKey(Contest, related_name='contests') The makemigrations command works fine, but the migrate command fails with the above noted error. Complete Traceback Error: Running migrations: Applying teams.0013_auto_20171031_1225...Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 204, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 495, in alter_field old_db_params, new_db_params, strict) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 117, in _alter_field new_db_params, strict, File … -
FB.ui with method 'send' do not take the website image while opening a send box
I am trying to invite the friends using Facebook FB.UI. I have successfully added the link of the website. but I could see the application image on the invite box. I have tried something like this: document.getElementById('invite').onclick = function() { FB.ui({ method: 'send', link: 'http://WebsiteURL:PORT', picture: '{{picture.url}}', }); } I get the following output on the windows with no image: Do let me know what to improve. -
Passing user instance from one view to another in django
I am new to django and i am trying to pass user instance from one view to another and then save data in model Category but i get this error: ValueError at /bookmark/category/ Cannot assign "45": "Category.user" must be a "User" instance. bookmark is the name of my application. After registering a new user, he is redirected to another page where he selects category from a dropdown list. I wish to add this selected category in Category model with the same userid. This is my views.py code: def register(request): if request.method == 'POST': form = signUpForm(request.POST) if form.is_valid(): user = form.save() request.session['user'] = user.pk return render(request,'category.html') def get_category(request): cname = request.POST.get("dropdown1") user = request.session.get('user') obj=Category(user=user,category=cname) obj.save() This is models.py file from future import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) Can someone please guide if this is the right approach or something else is to be done?Thanks! -
Display images in matrix format in Django
I am trying to display the friend's image from Facebook in a matrix format but getting failed to do so as there are number of responsiveness issues. What I have tried is something like this: <div> {% for friend in fb_friends %} <figure> <img src="{{friend.pic}}" height="auto" style="max-height: 50px" width="30%" > </figure> {% endfor %} <!-- other anchors here ... --> </div> This results in the following: The images are hidden by the black color to avoid identity revealing. The output what I am expecting to achieve is the following image: Kindly suggest me what I need to improve. -
Django Error when creating model entries with Django shell
My model looks like this. class Test(models.Model): eval_id = models.ForeignKey(Evaluation, on_delete=models.CASCADE) teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE) class_id = models.ForeignKey(Class, on_delete=models.CASCADE) score1 = models.IntegerField() score2 = models.IntegerField() class Meta: unique_together = ('eval_id','teacher_id','class_id') Here eval_id,teacher_id and class_id are defined accordingly in their respective models eval_id = models.IntegerField(primary_key=True) teacher_id = models.CharField(max_length=10, primary_key=True) co_id = models.CharField(primary_key = True, max_length=5) I get the below error when I try to create an entry for the model via the shell from trial.models import Test >>> t1 = Test('1','AC23002','C001','48','50') I get the below error Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 904, in _save_table forced_update) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1199, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 871, in execute_sql sql, params = self.as_sql() File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1165, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/related.py", line 963, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 762, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", … -
Django URL Regex Exact Match Only (Basic Regex)
I am new to django and trying to build my first API. The url structure is as follows but the problem is: when the first part of the URL matches, it calls that one. Ex. If I call 'welcome/example' it matches with welcome and doesn't make it to the actual welcome/example... from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^login/', include('shopify_app.urls')), url(r'^', include('home.urls'), name='root_path'), url(r'^admin/', admin.site.urls), url(r'^welcome/', views.welcome), url(r'^welcome/example', views.create_example), #regex not working ] -
can we edit snippet plugin in django cms ? if yes then how?
I am adding HTML in my page using djangocms_snippet I want snippets that I have created for first page should not be shown in another page while adding snippet there. Is there another plugin present through which I can achieve these or there is any way by which I can edit djangocms_snippet plugin. -
How to display a MySQL blob image in html in django?
I have a mysql blob image in my database and I want to show it in html. I retrieved the blob in my views.py using raw SQL query and passed it to my my html page as a dictionary object.I have not used models so please refrain from giving an answer using models. -
Can I use Django as backend and Javascript as frontend for web development? What limitation will it be?
I am very new to web development. I've some experience in Python but not in web development. Also, I've learned the basics, i.e. syntax etc, about Javascript, Html, CSS. I want to develop a website some sort like a forum. So I am wondering can I do it with only Javescript (maybe using Angular) as frontend and Python (Django) as backend. Is this achievable? What kind of limitation may I encounter? Or can I just use Node.js as backend instead of Django? I really don't wanna spend extra time to learn PHP. Appreciated! -
How to Set Initial Data as list For Inline Model Formset in Django
Friends, a big help please I have a formset that is created in the CreateView function CartItemFormset = inlineformset_factory(Cart, CartItem, can_order = True, fields = '__all__') Now I need to transfer data to this formset as the initial data before saving this formset. But this data is a list of values. First of all, we create a copy of the main form, check it and save it. self.form = CartForm(request.POST) if self.form.is_valid(): self.new_cart = self.form.save() items = Item.objects.filter(slug__in=cart_items.keys(), is_visible=True, price__gt=0) Now we create a copy of the formset and it’s necessary to transfer the initial data to the formset. This is a reference to the record of the main model and the values of the list of items. Thus, in each form of the formset, there must be a reference to the record of the main model and one of the elements of the list of items. But how to do that??? self.formset = CartItemFormset(request.POST, instance = self.new_cart, initial = [{‘cart’: self.new_cart, ‘item’: items}]) But it does not work! Maybe there should be something to sort out in a cycle or something like. Please, help me. -
Integrate Paypal IPN with Django
I have integrated Paypal IPN payment method in my Django project. I am using django-paypal django package. I am able to make payments using sandbox and it goes well but I don't get the transaction details back in my application for future reference (i.e. transaction ID, date, reference details etc.). I am sending below parameters while initiating payment. paypal_dict = { "business": "xxxxxxxx@mail.com", "amount": subscriptions.price, "item_name": subscriptions.name, "invoice": subscriptions.invoice_no, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return_url": request.build_absolute_uri(reverse('subscriptions:return_url')), "cancel_return": request.build_absolute_uri(reverse('subscriptions:cancel_return')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) # "landing_page": "billing", "paymentaction": "authorization", "first_name": company_profile.company_name, "last_name": "", "address1": company_profile.address_1, "address2": company_profile.address_2, "city": company_profile.city, "country": company_profile.country, "state": company_profile.state, "zip": company_profile.zip_code, "email": company_profile.email, "night_phone_a": company_profile.work_phone } I read that IPN keeps sending response but not sure if I have missed to set any parameter. Your valuable input will help us a lot. Thanks in Advance!!!!! -
Why can't I make DateTimeField data?
I wrote in models.py from django.db import models import uuid import random class User(models.Model): uu_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.IntegerField(null=True) regist_date = models.DateTimeField(auto_now=True) random_id = random.randint(1000,9999) @property def composite(self): return ''.join([str(self.uu_id), '_', str(self.regist_date), '_', str(self.random_id)]) in views.py def response(request): user = User() composite_id = user.composite print(composite_id) When I print out composite_id in print(composite_id),it is like f07c164e-2ce1-43aa-8bbf-75342b69c88d_None_8727 .I cannot understand why DateTimeField is None because UUIDField can be gotten. I wanna use DateTimeField 's data in composite_id.So how should I fix this?What should I write it? -
Django Form Field name Changing- Class Based View
In order to change the name in the form label in Django class-based view, I have to write this code into get_context_data ctx['form'].fields['dob'].label = 'Date of Birth' This changes dob to Date of Birth in form. Suppose there are 10 fields like this in the model. Is there a better way to change the name of all the form fields instead of writing 10 line of code? -
How save User data in OneToOneField | Django?
I have two models(User and Profile). In Profile model as you can see I have idx field which I use for sorting. In my project I show list of profiles and admin can sorting them by drag and drop. For thats why I use idx. Also this field is invisible and admin dont change its value manually. Question: How edit User data by profile id. As I said before I show list of profiles. Right now I have edit form where I show user data by profile id. Problem raise when I try to submit form after changes. models.py: # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) idx = models.IntegerField(verbose_name='Field for sorting, default=0, blank=True,) class Meta: ordering = ['idx', 'pk'] db_table = 'user_profile' @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() @receiver(post_delete, sender=Profile) def delete_user(sender, instance=None, **kwargs): try: instance.user except User.DoesNotExist: pass else: instance.user.delete() forms.py: from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserForm model = User def get(self, … -
Sending mail works in manage.py shell, but not in running app
I'm attempting to send an email to the site admins using django.core.mail.mail_admins when a comment is submitted via a view. I have a method on my Comment model called send_notification_email: from django.db import models from django.core.mail import mail_admins class Comment(models.Model): comment = models.TextField() time_received = models.DateTimeField() def send_notification_email(self): mail_admins( f'New Comment (id = {self.id})', f'Comment {self.id}, received at {self.time_received}: {self.comment}', ) The view creates an instance of Comment, saves it to the database, then calls send_notification_email(). When that happens, I get the following error: Traceback (most recent call last): File "/home/conda/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/conda/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/conda/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/conda/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/radio-website/main/views.py", line 56, in comments ) File "/home/radio-website/main/models.py", line 33, in send_notification_email [settings.SERVER_EMAIL], File "/home/conda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 56, in send_mail fail_silently=fail_silently, File "/home/conda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 36, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "/home/conda/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/home/conda/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked …