Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is use of python package like HTMLParser and urlparse for Django application?
Today i saw a django code and i have some confusion in it. Here they were using htmlparser() to a json object and store the parsed data with the same json key before sending Jsonresponse() from HTMLParser import HTMLParser h =HTMLParser() data['some_json_key'] = h.unescape(data['some_json_key']) Here they were taking rawjson on request and used urlparse() and did some operation which was like : import requests import urlparse def my_fun(request): data = urlparse.parse_qs(request.body) some_variable = data['some_json_key'] I didnt get the point of using any of the above packages, becuase my implemention for the same would have been: import requests import json def my_fun(request): data = json.loads(requests.body) some_variable = data.get('some_json_key') What is the diffrence in each implementation? -
Django - Join 3 tables to get records
Need the Queryset to perform join on 3 tables. please help objective is to join these 3 tables and to get data from Queryset.I have a html table where i need to put records from queryset. Models.py class Item_Table(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=127) description = models.TextField(null=True,blank=True) qty_in_ferma_warehouse = models.IntegerField(null=True,blank=True,default=0) status = models.BooleanField() ListID = models.CharField(max_length=80, null=True,blank=True) def __unicode__(self): return self class Order_Table(models.Model): id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=63) notes = models.TextField() created_at = models.DateField() status = EnumField(Choice,max_length=2, null=True,blank=True) Total_Amount = models.DecimalField(max_digits=18,decimal_places=2) must_fill_in_items = models.IntegerField() total_replenish_small_order = models.IntegerField() order_type = EnumField(Choice3,max_length=2, null=True,blank=True) delivery_method = EnumField(Choice6, max_length=2, null=True, blank=True) def __unicode__(self): return self class Orderitems_Table(models.Model): id = models.AutoField(primary_key=True) order_id = models.ForeignKey(Order_Table,on_delete='') item_id = models.ForeignKey(Item_Table,on_delete='') qty = models.IntegerField() next_order_qty = models.IntegerField(null=True,blank=True,default=0) Rate = models.DecimalField(max_digits=18,decimal_places=2) Amount = models.DecimalField(max_digits=18,decimal_places=2) status = EnumField(Choice2,max_length=2,null=True,blank=True) accumulated_residual_item = models.IntegerField() accumulated_damaged_item = models.IntegerField() def __unicode__(self): return self -
'startproject' command not working with virtualenv, but working without it
Django is unable to create a new project folder when I code after activating virtualenv (namely myDjangoEnv): django-admin.py startproject myproject The error displayed is: Unable to create process using 'C:/Users/Shreyas Jain/Miniconda3/envs/myDjangoEnv\python.exe "C:\Users\Shreyas Jain\Miniconda3\envs\myDjangoEnv\django-admin.py" startproject myproject' When I tried the same command without activating the virtualenv, django created a project folder without any error. This problem is occurring from past 2-3 days and I am still unable to fix this issue. Please help me. Thanks in advance. Before asking this question, I've tried to google it a lot. I read so many community answers on various communities and also I read a lot on StackOverflow. But unfortunately, nothing helped me. -
Django production server locally test in windows
How to configure a django project for production level in windows. I can't find out how to serve static and media files when DEBUG=False and how to work with gunicorn and nginx in windows. I want to test the project in production level before deploy on a web server. -
how to find which user logged in Django using oauth2
I am using react js and django, I am signing in users using google account from front end. In my backend i am using OAuth2_provider, social_django and rest_framework . It is working fine, i am able to see user details like emailID and access tokens in my django admin. but how to find which user logged in and how to get loggedin user details details. -
Is there any way to add value of two <h> tags using jquery?
I have two tags, one which contain price, and another contains percentage value. I need to find the percentage and set into new tag. I tried to calculate but which return NaN instead. I tried alert(parseFloat(price)+parseFloat(percent)) which return concatenated result, not the sum(for just testing). I tried following, value is assigned based on checkbox click. $("#checkbox1").click(function () { if ($(this).prop("checked")) { var price = $("#tex2").text(); var percent = $("#percent").text(); price = parseFloat(price); percent= parseFloat(percent); var dis_price; dis_price = parseFloat(dis_price); dis_price = price-(percent/100)*price; $('#tex1').text(dis_price); } else { $("#tex1").text("test"); } }); I want to get calculated value instead of NaN. Please find me way to solve this problem. -
When we extend an allauth view and create a new url based on that view is the old "/accounts/*" URLs of django allauth still required?
I extended the SignupView of django-allauth and created a url "/account-signup/" and also some minor changes in the template and I'm using the url name of my url. So, it keeps showing error that: NoReverseMatch at /account-signup/ Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name. I've tried searching where the url name account_login is used in the template. Also, I've tried enabling the default URLs given by django allauth. It doesnt show error when the allauth URLs are included in the urls.py file. /signup.html {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <p>some content from sugat</p> <form class="signup" id="signup_form" method="post" action="{% url 'my_app:custom_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> {% endblock %} /my_app/urls.py from django.conf.urls import url from .views import * app_name = "my_app" urlpatterns = [ url(r'^account-signup/$', AccountSignUp.as_view(), name="account_signup"), ] /myproject/urls.py from django.conf.urls import … -
Is there any way to convert this into django orm?
I needed to get all the rows in the table1 even it is not existing in table2 and display it as zero. I got it using raw sql query but in django ORM im getting the values existing only in table2. The only difference on my django orm is that im using inner join while in the raw sql query im using left join. Is there any way to achieve this or should i use raw sql query? Thanks. Django ORM: total=ApplicantInfo.objects.select_related('source_type').values('source_type__source_type').annotate(total_count=Count('source_type')) OUTPUT OF DJANGO ORM IN RAW SQL: SELECT "applicant_sourcetype"."source_type", COUNT("applicant_applicantinfo"."source_type_id") AS "total_count" FROM "applicant_applicantinfo" INNER JOIN "applicant_sourcetype" ON ("applicant_applicantinfo"."source_type_id" = "applicant_sourcetype"."id") GROUP BY "applicant_sourcetype"."source_type" RAW SQL: SELECT source.source_type, count(info.source_type_id) as total_counts from applicant_sourcetype as source LEFT JOIN applicant_applicantinfo as info ON source.id = info.source_type_id GROUP BY source.id -
Is it possible to work with database in django shell without pre-installed app?
Without defining an app's models in models.py, i want to work with models such as defining a model class and creating/deleting/modifying object of this model. How can i do this in django shell? I tried this in django shell. from django.db import models class Question(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date_published') This causes runtimeerror. RuntimeError: Model class main.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. -
How to use the verbose name of a language choice in Django-Countries with Django Filter
I have this Django Filter: from django_countries.data import COUNTRIES owner__nationality = filters.MultipleChoiceFilter(choices=COUNTRIES, widget=Select2MultipleWidget) So I guessed I just use the original choices field to filter on nationality (for which I used Django Countries to fill the data) As you can see in the source code here, the import is correct: https://github.com/SmileyChris/django-countries/blob/master/django_countries/data.py However on the front end the dropdown looks like this: How can I get full countries to be displayed there? I also don't quite understand why there is only one letter there. Can somebody clarify? By the way I know about get_FOO_display() -
Django Test Client client.post() sends GET request in my Testcase
How can I submit a POST request with Django test Client? I just want to test the login function of my application. It's strange that I put response = self.client.post(reverse('rbac:login'), data=data) in my testcase, and I want to validate it so I print response.status_code.Actually it should return 302 coz it should turn to another page. but it return 200. This situation happens when I use "python manage.py test testmodel" to test. However, if I use "python manage.py shell" to make an InteractiveConsole and write exactly the same code, it return 302 at last. I have nearly tried all the methods provided from stack overflow, e.g. change the url, offer the content-type when I post....but these are meaningless. from django.test import TestCase from django.test.utils import setup_test_environment,teardown_test_environment from django.test import Client from django.urls import reverse import django from rbac.models import RbacUser, RbacRole from system_module.models import Redeploy from urllib import urlencode class CreateUser(TestCase): @classmethod def setUp(self): self.client = Client() def test_create_user(self): data = {"Username": "admin_xy", "Password": "aaa"} response = self.client.post(reverse('rbac:login'), data=data) print response and it shows me 200..... However, in interactive console: >>> response = client.post('/', data, content_type="application/x-www-form-urlencoded") >>> print response.status_code 302 it shows the right result. I want to know how to … -
How to write json data in html file in python
I have this json data {'latest_question_list': ((1, "What's up?", datetime.datetime(2019, 4, 19, 7, 38, 6, 449735)),)} , i want to show this data in my html file can anyone please help me how to show this data in it, here is my code for that, views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Choice, Question from django.urls import reverse from django.shortcuts import get_object_or_404, render def index(request): latest_question_list = Question.get_poll_question() context = {'latest_question_list': latest_question_list} print(context) return render(request, 'polls/index.html', context) index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
Portrait image rotates to landscape while imported to PyCharm with Django
I have an image that I would like to appear on my Django website so I import it (portrait) from photos or Finder (MacOs) and when I view it in PyCharm and on my website, it's in landscape. My html template is below: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="font-family: Verdana"> {% extends 'base.html' %} {% block content %} <h1>Title</h1><br> <div class="row"> {% for product in clothes %} <div class="col"> <div class="card" style="width: 30rem"> <img src="/static/{{product.img_dir}}" class="card-img-top" alt="Product Image"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description }}</p> </div> </div> <br> <br> </div> {% endfor %} </div> {% endblock %} </body> </html> The image should be displayed in portrait orientation but is displayed in landscape -
Read a CSV file and store data in JSON form in Django
I have a CSV file in media folder inside my django project. I want to read the data from the CSV file and store it in JSON format either directly in the database or convert it into JSON from CSV file and then store it, and enable me to view it on an html page, in my Django Web Application. Kindly help me. -
django model FileField is not storing database
from django.core.files.storage import FileSystemStorage fs_photo = FileSystemStorage(location='/media/photos') fs_files = FileSystemStorage(location='/media/files') # this method i tried offer_letter = models.FileField(storage=fs_files,null=True) appraisal_letter = models.FileField(storage=fs_files,null=True) #this method resume = models.FileField(upload_to='resume/',null=True) #this method also i tried to save offer_letter = models.FileField(upload_to='media/',blank=True,null=True) # media path MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL ="/media/" # in urls.py ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i am trying to save a file to database but its not saving and my media paths are also perfect.please help me out for this problem -
i have connection problems in django, I was using it for a while and from one moment to the next it stopped working
I was using it for a while and from one moment to the next it stopped working, the problem in console: > uccessfully created virtual environment! Virtualenv location: > c:\Users\andre\.virtualenvs\app-HT4rt8Tz Installing dependencies from > Pipfile.lock (46aede) To activate this project's virtualenv, run > pipenv shell. Alternatively, run a command inside the virtualenv with > pipenv run. Traceback (most recent call last): File > "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\db\backends\base\base.py", > line 213, in ensure_connection > self.connect() File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\db\backends\base\base.py", > line 189, in connect > self.connection = self.get_new_connection(conn_params) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\db\backends\postgresql\base.py", > line 176, in get_new_connection > connection = Database.connect(**conn_params) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\psycopg2\__init__.py", > line 130, in connect > conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call > last): File "manage.py", line 28, in <module> > execute_from_command_line(sys.argv) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\core\management\__init__.py", > line 363, in execute_from_command_line > utility.execute() File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\core\management\__init__.py", > line 355, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\core\management\base.py", > line 283, in run_from_argv > self.execute(*args, **cmd_options) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\core\management\base.py", > line 330, in execute > output = self.handle(*args, **options) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\core\management\commands\makemigrations.py", > line 110, in handle > loader.check_consistent_history(connection) File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\db\migrations\loader.py", > line 282, in check_consistent_history > applied = recorder.applied_migrations() File "c:\Users\andre\.virtualenvs\app-HT4rt8Tz\lib\site-packages\django\db\migrations\recorder.py", > line 65, in applied_migrations > … -
How do I activate my virtual environment with cronjob?
I am running a python script. The script requires environment variables that are defined in my virtaul environment's ~/.bash_profile Here is my cronjob script, I edit it by SSHing to my EC2 instance and running: crontab -e */1 * * * * cd /home/ec2-user/code/green_brick_django/pricecomparison_project/pricecomparison && /home/ec2-user/MYVENV/bin/python /home/ec2-user/code/green_brick_django/pricecomparison_project/pricecomparison/run_cronjob_script.sh > /tmp/cronlog.txt 2>&1 I keep getting a python error saying it can't find my ENVIRONMENT variables. What am I doing wrong? Please help! I've tried every single option listed here, multiple times over, in every which way I can think of. Please! Cron and virtualenv -
How to use autocompleteselect widget in a modelform
I know there is a new feature in Django 2.0, which is AutocompleteSelect widget in ModelAdmin. I am trying to use it in my custom modelForm but just failed. Tried like this #unit is the foreign key to the incident class AccountForm(forms.ModelForm): class Meta: model = Invoice ... ... widgets = { 'incident':widgets.AutocompleteSelect(Invoice._meta.get_field('incident').remote_field, admin.site) } ... #Invoice model class Invoice(models.Model): ... incident = models.ForeignKey(Unit, on_delete=models.CASCADE,null=True) ... Hope anyone can help me. Thanks -
Is it possible to use a URL to access a template and JSON result - Djanto?
Is it possible to use a URL to access a template and JSON result - Djanto? The idea is not to generate unnecessary url. Something like that: > path(r'cnpj', CNPJ.as_view(), name='cnpj'), > path(r'cnpj', CNPJ_JSON.as_view(), name='cnpj_json'), -
Deploy failure - elastic beanstock
I'm attempting to deploy my django app to elastic beanstalk. When I run eb deploy, the deployment fails. The logs indicate this: File "src/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/python/run/venv/lib64/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 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'userordersaccess' (ElasticBeanstalk::ExternalInvocationError) 2 of the apps that I have in my project are called 'access' and 'userorders'. I've never seen this issue before. The string userordersaccess doesn't exist anywhere in my project. Any ideas? Thanks! -
ImproperlyConfigured at /live/dashboard/edit/events/
Could not resolve URL for hyperlinked relationship using view name "articles2-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. class EditViewSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Articles2 fields = ['id','url'] I should get a url link to fetch the data. -
How to deploy django web app to google cloud ? please provide me best solution
i want to know how can i deploy python/django web app to Google Cloud , i am using django 2.2 and python 3.7.3. -
I have a post model and user model, and I want to divide the post into groups depends on the user groups
I have two models, post model and user model, and I want to divid the posts into groups depend on the user's group I add the foreignkey of Group in the post models, but I found that when I change the post user's group, the post's group didn't change, so I add the post_save signal in the post model, but I found that when I changed the user's group, the post's group was updated with the last record of user. It seems that the user model didn't save immediately.ps I change the user's group in Website backstage (/admin) class User(AbstractUser): worker_id = models.CharField(max_length=10, verbose_name='worker_id', unique=True) avatar = models.ImageField(blank=True, upload_to='avatar/', default='images/default_avatar.jpg') class Meta(AbstractUser.Meta): pass def post_save_callback(*args, **kwargs): print(kwargs) user = kwargs['instance'] print(user.groups.get()) for post in user.post_author.all(): # User.objects.get(pk=2).groups.get() # group info post.author_group = user.groups.get() post.save() signals.post_save.connect(post_save_callback, sender=User) -
How to create the same form in Group and Permission on Django Templates
How can i custom my django templates like admin group page, I tried to fetch all fields but its only fetch the avaible permissions and not fetching out chosen permission field Please help me, Thanks The fields i want: enter image description here And then the results i get: enter image description here Some code in Forms: class UserGroupForm(forms.ModelForm): class Meta: model = Group fields = '__all__' Some code in Views: def save_all(request, form, template_name): data = dict() error = None if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True data['action'] = True else: data['form_is_valid'] = False error = form.errors context = { 'form': form, 'error': error, } data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def create(request): if request.method == 'POST': form = UserGroupForm(request.POST) else: form = UserGroupForm() form2 = UserPermissionForm() return save_all(request, form, 'usergroups/create.html') Some code in Templates: <form action="" method="post" data-url="{% url 'userroles:create' %}" class="create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Create Test</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if error %} <div class="alert alert-danger text-center" role="alert"> {% for field, error in error.items %} {{ error | striptags }} <br> {% endfor %} </div> {% endif %} <div class="form-group"> {{form}} </div> … -
How to implement a dependent drop down list with Django CreateView?
I am trying to create a CreateView for one of my models "service". My "service" model has a foreign key to an "asset" model. "asset" model has a foreign key to the current user. I would like to populate a drop down in "service" CreateView with all the "assets" owned by the current logged in "user". Service model class Service(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=100) provider = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) asset = models.ForeignKey(Asset, on_delete=models.CASCADE) Asset model class Asset(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) suburb = models.CharField(max_length=100) postcode = models.CharField(max_length=4) state = models.CharField(max_length=3) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) ServiceCreateView in views.py class ServiceCreateView(LoginRequiredMixin, CreateView): model = Service fields = ['name', 'category', 'provider', 'asset'] If I user 'asset' in fields, I get all the assets added to the drop-down list. I need it to be only the assets owned by the current user. Any help in this much appreciated. Thank you. (I am using the latest Django version)