Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django: login link to appear only when a user is logged in
I am making an app in django in which i have used the django built in authentication system. Both login and logout links are present in the navbar. I want to make the logout link appear only when the user has logged in and not at all times. How do i do that? code snippet of project/urls.py: urlpatterns = [ url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), ] code snippet of login.html; <div class="container"> <section id="content"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" … -
Unknown field specified for Model - datetime
I have this model: class Schedule(models.Model): name = models.Charfield(max_length=250) due_date = models.DateTimeField() I have also tried providing a default value for the due date but it also produces the error. I have this generic view: class ScheduleCreate(CreateView): model = Schedule fields = ['name', 'due_date'] PS: I have tried to changed due_date to CharField and it worked propely. I think the cause of the problem is the date time. How can this be solved? -
Django templates iterate model fields with indices
I have the follow model: class UserProfile(...): ... photo1 = models.URLField() photo2 = models.URLField() photo3 = models.URLField() photo4 = models.URLField() photo5 = models.URLField() And in the Create/Update template, I have to write five copies of the following div for file1 to file5: <div> Photo 1: {% if userProfileForm.instance.file1 %} <a href="{{ userProfileForm.instance.file1 }}" target=_blank>View</a> {% endif %} <input type=file name=file1> {% if userProfileForm.instance.file1 %} <a href="{% url 'account:deletePhoto' userProfileForm.instance.id %}">Delete</a> {% endif %} </div> Is there a way to iterate field file<i>? {% for i in '12345' %} <div> Photo {{ forloop.counter }}: ... </div> {% endfor %} -
Django - display all products created by a user
I have built a product app where a logged in user can create products by filling out a form. There is a products page that lists all products created by all users. When a user clicks on the profile link they will see a list of products they have created. When a user is logged in their username appears in the nav bar (this will be relevant further down this post). I want to create a page where visitors can can view products by user. I created this view: def designs_by(request, username): user = get_object_or_404(User.objects, username=username) products = Product.objects.filter(user=user) return render(request, 'designs_by.html', {'user':user,'products': products}) with this url: url(r'^designs_by/(\w+)/$', views.designs_by, name='designs_by'), which works, for the most part, but when a visitor clicks on the link to view the products by a user, the users profile link appears in the nav bar. The link won't work but I have no clue why it appears. Yeah, an odd one. -
Error Dockering Django with Webpack_Loader
Getting a stack of errors concluding to "ImportError: No module named webpack_loader". I have a Django app created that I'm trying to Docker using Gunicorn. My Dockerfile and start.sh are in a root directory alongside another directory called approot. In approot is everything you'd expect to see from running django-admin startproject. My wsgi.py file is in a directory called app inside of approot. Here is my... requirements.txt: Django>=1.8 gunicorn==19.6.0 Dockerfile: #Dockerfile # FROM directive instructing base image to build upon FROM python:2-onbuild # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifies the command to execute to start the server running CMD ["/start.sh"] start.sh: #!/bin/bash echo Starting Gunicorn. cd approot exec gunicorn app.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 My settings.py includes: INSTALLED_APPS = [ ..., 'webpack_loader' ] WSGI_APPLICATION = 'app.wsgi.application' WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': join(PROJECT_ROOT, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } error stack is $ docker run -it -p 8000:8000 app Starting Gunicorn. [2017-10-31 02:23:31 +0000] [1] [INFO] Starting gunicorn 19.6.0 [2017-10-31 02:23:31 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2017-10-31 02:23:31 +0000] [1] … -
How to represent value which have same field name in Django?
How to represent two columns which have the same name in Django? I have designed views and template below. However, the second and third column didn't show. Here is the my raw query cursor = connection.cursor() query = str("SELECT\n" " MG.valData,\n" " MG0.valData as value1,\n" " MG1.valData as value2,\n" " FROM\n" " T_USER AS TU\n" " LEFT JOIN M_GENERAL AS MG\n" " ON MG.Cd='002'\n" " LEFT JOIN M_GENERAL AS MG0\n" " ON MG0.Cd='001'\n" " LEFT JOIN M_GENERAL AS MG1\n" " ON MG1.Cd='001'\n") cursor.execute(query) row = dictfetchall(cursor,) return row Here is template {% for item in table_data %} <tr> <td>{{ item.MG.valData|default_if_none:"" }}</td> <td>{{ item.MG0.valData|default_if_none:"" }}</td> <td>{{ item.MG1.valData|default_if_none:"" }}</td> </tr> {% endfor %} I also tried used the alias like item.value1 and item.value2 in template. But it still showed blank values. Does anyone knows the mistakes? Thank you in advance. -
'str' object is not callable Am I wrong to assign User to method wrong?
I wanna print out composite_id in views.py. I wrote in response method like from django.shortcuts import render from .models import User def response(request): user = User() composite_id = user.composite(User) print(composite_id) return render(request, 'response.html') 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)]) I really cannot understand why this error happens because I do not think I assign string somewhere. But I think ,maybe am I wrong to assign User to method wrong? But I think argument of views.py's composite method should be User bacause models.py's self = User.How should I fix this?What should I write it? -
Call A Django View Without Refreshing The Page
Here's the view that updates the timestamp of a model in database whenever it's called, def data(request): new = Data.objects.filter(user=request.user) new.update(timestamp=timezone.now()) return HttpResponse('') This view is related to this URL, url(r'^go/$', views.data, name='data') Everything is fine, but how can I call this view & update the database without refreshing the page? -
Django Rest Framework: Filtering in Read/Write Related Field
I have Users and Groups, where Groups are a PrimaryKeyRelatedField on Users. When retrieving a User, I only want to show the Groups that it has in common with the current users. For example, suppose user_1 belongs to group_1, and user_2 belongs to group_2. If user_1 pings my LIST USERS endpoint I want to get: [{'groups': [1], 'username': 'user_1'}, {'groups': [], 'username': 'user_2'}] Note that although group_2 exists, it is not listed under user_2's groups, because user_1 is not in it. Thoughts so far: Overloading to_representation seems like it will just change how the group is shown in the list of groups, not whether it is shown at all There are some guides about how to filter the writable group choices here, meaning that user_1 couldn't, for instance, add itself to group_2 There are some guides about how to filter for a read-only field I could combine the above two and do a read-only field and a write-only field, as suggested here for a different problem, but I'd rather not. I don't see any guides on how have a single read/write RelatedField filtered by the current user. Any ideas? My code: # serializers.py, vanilla from django.contrib.auth.models import User, Group from …