Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'six' from 'django.utils'
Currently, I have upgraded version of Django 2.0.6 to 3.0 and suddenly after calling python manage.py shell command got this error: ImportError: cannot import name 'six' from 'django.utils' (/path-to-project/project/venv/lib/python3.7/site-packages/django/utils/init.py) Full trace: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/path-to-project/project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/path-to-project/project/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/path-to-project/project/venv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/path-to-project/project/venv/lib/python3.7/site-packages/corsheaders/__init__.py", line 1, in <module> from .checks import check_settings # noqa: F401 File "/path-to-project/project/venv/lib/python3.7/site-packages/corsheaders/checks.py", line 7, in <module> from django.utils import six Similar Questions: I read this Question and django-3.0, release note , but those answers couldn't help me. -
Printing all records with all the attributes
I am from PHP background and very new to Django. I just want to see all the records with it's values for that I have write below code Model file : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text View file: q = Question.objects.all() print(q) In console it only outputs question_text. How can I print all the records with all the attributes. -
ModuleNotFoundError: No module named 'Social'
Upgrading Django project to Python 3, python3 manage.py check is throwing this traceback. The project works fine in Python 2.7. I cannot figure out what is missing in my pip3 installs. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "~/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "~/src/languages/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "~/src/languages/env/lib/python3.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "~/src/languages/env/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "~/src/languages/env/lib/python3.7/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "~/src/languages/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "~/src/languages/env/lib/python3.7/site-packages/social/__init__.py", line 12, in <module> from Social import _metadata … -
Django Channels: How to keep socket alive
I am trying to use django channels and templates to implement authentication. I know that there is an authentication section in the official website, but I have a question about the socket, which is created in the client side via templates. From my understanding, django templates multi-page application, so if I create a socket in login.html, the socket will be disconnected in main.html, and I have seen it happen. Is there a way to keep the socket alive even if I navigate to different pages? -
social auth with drf and react
I am using rest_framework_social_auth2 library for social authentication and using simple-jwt for authentication urls.py: path('auth/', include('rest_framework_social_oauth2.urls')), settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'image', 'crispy_forms', 'django_countries', 'users', 'corsheaders', 'api', 'sorl.thumbnail', 'rest_framework', 'social_django', 'rest_social_auth', 'django_filters', 'oauth2_provider', 'rest_framework_social_oauth2', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':[ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ], AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend',) SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] also changed the middleware templates created new application from django backend: this is the postman output: but how can i create api endpoint for facebook, google. -
How to use py dictionary to get names respect to ids in table?
I have id of selected department from dropdown in my database , i want to bind name of that id to table , so it is possible using py dictionary .. how? html <tbody id="myTable"> {% for employee in employees %} <tr> <td>{{ employee.employee_id}}</td> <td>{{ employee.Name}}</td> <td>{{ employee.designation}}</td> <td>{{ employee.department_id}}</td> <td>{{ employee.manager_id}}</td> <td>{{ employee.location_id}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> </td> </tr> {% endfor %} </tbody> Here "{{ employee.department_id}}" is binding my id from database , so how can i set id and names in dictionary so i will get name of that id? -
Moving from backend to Django graph
i am quite new in Django and now matplotlib. I want the following code to conert to graph and seek for any help: import numpy as np import pandas as pd from pandas_datareader import data as wb from yahoofinancials import YahooFinancials symbols='AAPL' yahoo_financials = YahooFinancials(symbols) new_data = pd.DataFrame() for s in symbols : new_data[s] = wb.DataReader(s, data_source ='yahoo', start = '2014-1-1')['Adj Close'] a = new_data[s] a contains stock prices and i want them to be in graph. I did with matplotlib in backend in python, but confused how to convert it in graph in Django. Would be thankful to any help and tips. -
Problem while using mypy with my django project
I have implemented mypy in my django rest framework but I am getting errors ModuleNotFoundError: No module named 'config' while running mypy.Is there any wrong with my django_settings_module in my mypy.ini file ? I used to run my project with the command python manage.py runserver --settings=config.settings.development which was working fine but while configuring this setting in the mypy it is giving me error. What I might be doing wrong ? Any help would be appreciated. mypy.ini [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main ignore_missing_imports = True warn_unused_ignores = True strict_optional = True check_untyped_defs = True follow_imports = silent show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.development settings directory /project /config __init__.py urls.py wsgi.py /settings __init__.py base.py development.py wsgi.py app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "project")) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application() -
RelatedObjectDoesNotExist at /admin/login/
Django beginner. the project is aboud a really basic food delivery app. I have extended the User Model using a One-to-One link as specified here, in order to include a 'city' field when a new user tries to register. The problem is that when I create a superuser in the python shell, and try to access that account from http://127.0.0.1:8000/admin/login/?next=/admin/ and hit login, the following page is returned: As far as I can tell, this is due to the fact that every User/Superuser has to be linked to one Customer object. How can I avoid this? Could a solution be to overwrite the superuser class by specifying that that field 'city' is not needed? If yes, how can I do that? If not, what is the best practice in this case? here is accounts/model.py from django.db import models from django.contrib.auth.models import User from city.models import City from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_customer_user(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def save_customer_user(sender, instance, **kwargs): instance.customer.save() If you need any other code to be uploaded, please let me know that, … -
Django with asgi_rabbit why do i get connection closed error. Not establishing new connection
I am using Django with asgi and a rabbitmq broker. It works fine but on some request i get the following error message. And then django loses its connection and does not open a new one. I have no clue where to start searching. I tried with asgi-rabbitmq 0.5.5 but there the same happend always after 60s since rabbitmq did get a heartbeat timeout. But i don't know how to avoid that. dependencies: Rabbit mq 3.8.1 amqp==2.5.2 # via kombu asgi-rabbitmq==0.5.3 asgiref==1.1.2 # via asgi-rabbitmq, channels, daphne autobahn==19.11.1 # via daphne billiard==3.6.1.0 # via celery cached-property==1.5.1 # via asgi-rabbitmq, zeep celery==4.3.0 daphne==1.4.2 # via channels defusedxml==0.6.0 # via zeep django==1.11.26 djangorestframework==3.9.4 kombu==4.6.6 # via celery lxml==4.4.2 # via zeep markupsafe==1.1.1 more-itertools==5.0.0 # via zipp msgpack-python==0.5.6 # via asgi-rabbitmq six==1.13.0 # via asgiref, singledispatch, structlog, txaio, zeep twisted==19.10.0 # via daphne Channels confg: BROKER_URL = 'amqp://' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_rabbitmq.RabbitmqChannelLayer', 'CONFIG': { 'url': 'amqp://guest:guest@localhost:5672/%2F', }, 'ROUTING': 'timeline_prototype.apps.core.routing.channel_routing', } } django error (ie. runserver) ERROR daphne.http_protocol http_protocol.py 184 process 2019-12-05 09:31:03 [error ] Traceback (most recent call last): File "/myproject-env/lib/python2.7/site-packages/daphne/http_protocol.py", line 178, in process "server": self.server_addr, File "/myproject-env/lib/python2.7/site-packages/asgi_rabbitmq/core.py", line 812, in send future = self.thread.schedule(SEND, channel, message) File "/myproject-env/lib/python2.7/site-packages/asgi_rabbitmq/core.py", … -
converting string to int, django rest framework, passing data from front end as formdata
One of my field in models accept integer, and i am using formdata() to send data from front-end to my rest api. After some research i came to know that formdata() converts everything to strings and so i am not able to do a successful post. my code at serializers at this moment is : class xyzSerializers(serializers.ModelSerializer): class Meta: model = Profile fields = ('__all__') Trying to find a solution i read about Field-Level-Validation in serializers of rest framework 'user' is the field which accepts value in integer and my new code is : class xyzSerializers(serializers.ModelSerializer): user = serializers.CharField() def validate_user(self, value): if not value: return 0 try: return int(value) except ValueError: raise serializers.ValidationError('You must supply an integer') class Meta: model = Profile fields = ('__all__') I am getting the same error, can some one please tell me the correct way to use field level validation. or also to convert string to int at serializers of rest api. Thanks -
How to filter on a field for a set of values
I have a model called products. The category belongs to this model. Now I can filter for this section field with a value. Actually I wanted to filter by multiple values for the same field Example: If I filter with ** phone ** (is a category) it works But for this section field, I need to filter by ** phone ** and ** cases ** filter class ProductFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr='gte') max_price = filters.NumberFilter(field_name="price", lookup_expr='lte') class Meta: model = Product fields = ['category', 'min_price', 'max_price' ] View class ProductListView(generics.ListAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = ProductListSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = ProductFilter How do I do that? Can someone help me? -
Django - invalid literal for int() with base 10: b'latest_start_date'
I dont know what happened, it worked fine yesterday. Traceback: File "D:\Users\...\env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\...\env\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\...\env\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\...\personal\views.py" in display_mobiles 69. return render(request, 'header.html', context) File "D:\Users\...\env\lib\site-packages\django\shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "D:\Users\...\env\lib\site-packages\django\template\loader.py" in render_to_string 62. return template.render(context, request) File "D:\Users\...\env\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 171. return self._render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "D:\Users\...\env\lib\site-packages\django\template\loader_tags.py" in render 150. return compiled_parent._render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "D:\Users\...\env\lib\site-packages\django\template\defaulttags.py" in render 309. return nodelist.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "D:\Users\...\env\lib\site-packages\django\template\defaulttags.py" in render 309. return nodelist.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "D:\Users\...\env\lib\site-packages\django\template\loader_tags.py" in render 62. result = block.nodelist.render(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "D:\Users\...\env\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "D:\Users\...\env\lib\site-packages\django\template\defaulttags.py" in … -
how to paginate a ModelMultipleChoiceField when form loads in Django CreateView
I have to paginate a queryset when form loads in Django Createview. I am using ModelMultipleChoiceField as of now to list all the products,how can i implement pagination to this? forms.py class CustomUserForm(forms.ModelForm): first_name = forms.CharField(validators=[not_special_charactor]) last_name = forms.CharField(validators=[not_special_charactor]) class Meta: model = User fields = ( 'first_name', 'last_name', 'email','products') def __init__(self, company_id, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields["products"] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={ "class":"noti_select" } ), queryset = CustomerProduct.objects.filter( customer=company_id).filter(parent=None), required=False, ) views.py class CustomerUserCreateView(PermissionCheckMixin, CreateView, MultipleObjectMixin): form_class = CustomUserForm template_name = 'add-customer-user.html' raise_exception = True paginate_by = 10 def get_form_kwargs(self, *args, **kwargs): form_kwargs = super(CustomerUserCreateView, self).get_form_kwargs(*args, **kwargs) form_kwargs['company_id'] = Customer.objects.get( slug=self.kwargs['slug']) return form_kwargs def form_valid(self, form): user = form.save() user.company = Customer.objects.get(slug=self.kwargs['slug']) password = User.objects.make_random_password() user.set_password(password) user.save() return HttpResponseRedirect(reverse('customer_users', kwargs={'slug': user.company.slug})) def get_context_data(self, **kwargs): context = super(CustomerUserCreateView, self).get_context_data(object_list=object_list, **kwargs) context['customer'] = Customer.objects.get(slug=self.kwargs['slug']) context['activate'] = 'customers' return context I am getting all the products in my template from forms.I want to implement page number pagination. I need to select products the user can have access.Since there are large products, i wan't show all the products with pagination on user create form. How can i do this.I am new to django templates...please help me out. … -
Is it possible to show urls in django including request type?
I want to have a list with all the url in a django project with the type of request(GET,POST,PUT,DELETE) I already tried this pip install django-extensions and after this code on terminal python manage.py show_urls I get a list with all the urls, but it would be nice to have the request type aswell -
Django Admin LogEntry: how it works in non admin actions?
I am having some struggles how does exactly django.admin.LogEntry objects are created. Consider the following scenario: I have a bunch of functions which take a csv file with data that allow me to create multiple objects at one call (just iterate through the file, use the data and if data in given row is correct: create a Model instance). I want to make sure that that each of that creation will be logged. The question is: django docs are not very descriptive on how does LogEntry works and I am not sure if such actions (not taken in the admin panel itself) will be logged there. Also: will the LogEntries be created for the related objects or I have to trigger them manually? Does anybody got any experience with such scenarios and can share thoughts about it? -
How to set Authentication and Permission on django URLs for imported views
I want to use django REST framework's inbuilt API documentation. The problem is that I need it to be private with a login and I couldn't manage thus far. I do the following to create my API doc as documented: from rest_framework.documentation import include_docs_urls API_TITLE = "Cool title" API_DESCRIPTION = "Badass description" urlpatterns = [ path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION) That creates my docs, which is fantastic. But it is accessible by everyone even though I have set my permissions and authentications for all the endpoints to private. I did this like this in my configs: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ) } But even with this set I can access all site of the docs. So I am looking for a way to protect my URLs which I imported and thus have no classes or methods at my disposal to protect. (So I can't use any decorators on them). Then I tried using the login required decorator on my URL like so: path('docs/', login_required(include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))), but it throws me the following error: django.template.exceptions.TemplateDoesNotExist: registration/login.html Is there a way of protecting such URLs? Help is very much appreciated! Thanks a lot in advance! -
Django - simple_history.models To capture who did changes in the database and integrate with the admin page
Django - simple_history.models To capture who did changes in the database and integrate with the admin page I want to have capture updated_by(who updated the changes in the filed.)But the updated_by columns does not updates and is always empty. I am able to capture uddated_timestamp but not updated_by. and it remains empty. I have installed django-simple-history,then installed _app of setting added 'simple_history' and in middleware 'simple_history.middleware.HistoryRequestMiddleware', As I saw in doc at https://django-simple-history.readthedocs.io/en/2.7.0/user_tracking.html I am pasting my codes here . Please help Models.Py from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from django.core.validators import MaxValueValidator, MinValueValidator ## changes by rahul from django.db import transaction from simple_history.models import HistoricalRecords #from audit_log.models.fields import LastUserField, LastSessionKeyField from django.contrib.auth.models import User class Company(models.Model): class Meta: verbose_name_plural = "companies" name = models.CharField(max_length=128) def __str__(self): return self.name class Game(models.Model): company = models.ForeignKey('projects.Company', on_delete=models.PROTECT, related_name='projects') title = models.CharField('Game title', max_length=128) start_date = models.DateField('Game start date', blank=True, null=True) end_date = models.DateField('Game end date', blank=True, null=True) estimated_design = models.DecimalField('Estimated design hours', decimal_places=2, max_digits=10, blank=True, null=True, validators=[MinValueValidator(0.00), MaxValueValidator(10000)]) actual_design = models.DecimalField('Actual design hours', default=0, decimal_places=2, max_digits=10, blank=True, null=True, validators=[MinValueValidator(0.00), MaxValueValidator(10000)]) estimated_development = models.DecimalField('Estimated development hours', decimal_places=2, max_digits=10, blank=True, null=True, validators=[MinValueValidator(0.00), MaxValueValidator(10000)]) actual_development … -
How to count objects in django
Thank you all for always sharing your knowledge here. I have an issue with counting an object in Django. I am currently learning and working on a basic HR system and already have my views, models, et al set up. I plan to have an interface whereby I can print out employees count based on gender. The one I currently have set up is increasing the counts for both male and female any time I create a new employee. Please how do I correct this anomaly? views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.shortcuts import render from django_tables2 import RequestConfig from django_tables2.export import TableExport from .models import Employee from .models import EmployeeFilter from .tables import EmployeeTable @login_required() def employees(request): filter = EmployeeFilter(request.GET, queryset=Employee.objects.all()) table = EmployeeTable(filter.qs) RequestConfig(request, paginate={"per_page": 15}).configure(table) count = Employee.objects.all().count() male_count = Employee.objects.filter(gender__contains='Male').count() female_count = Employee.objects.filter(gender__contains='Female').count() user_count = User.objects.all().count() export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format("csv", "xlsx")) return render(request, "employees/employees.html", { "table": table, "filter": filter, "count": count, "male_count": male_count, "female_count": female_count, "user_count": user_count, }) template.html {% extends "employees/base.html" %} {% load render_table from django_tables2 %} {% load django_tables2 %} {% load querystring from django_tables2 %} {% block content %} <!--Data … -
How do I make individual users in my project to make posts which are particular to them?
I need help with my program. I need to make a dynamic "Homepage" for users where they can see their past posts. I haven't tried anything since I am clueless. Please help. -
Getting error cannot import name 'six' from 'django.utils' when using Django 3.0.0 latest version
Currently I have upgraded version of Django 2.2 to 3.0 and suddenly getting error like below. ImportError: cannot import name 'six' from 'django.utils' I have checked Traceback is like below. Traceback (most recent call last): File "c:\Users\admin\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module> main(ptvsdArgs) File "c:\Users\admin\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main run() File "c:\Users\admin\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file runpy.run_path(target, run_name='__main__') File "C:\Python37\Lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "C:\Python37\Lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Python37\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\production\myproject\erp_project\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "d:\production\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "d:\production\myproject\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "d:\production\myproject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "d:\production\myproject\venv\lib\site-packages\django\apps\registry.py", line 92, in populate app_config = AppConfig.create(entry) File "d:\production\myproject\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "d:\production\myproject\venv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "d:\production\myproject\venv\lib\site-packages\post_office\__init__.py", line 3, in <module> from .backends import EmailBackend File "d:\production\myproject\venv\lib\site-packages\post_office\backends.py", line 6, in <module> from .settings import … -
Register page couldn't register user
I have setup register page by Django. The URL of register input on IE, register page is ok, but I cliked 'register' button on page, no register form display. enter image description here users\urls.py urlpatterns = [ # register page re_path('^register/$', views.register, name='register'), ] users\views.py def register(request): """register new user""" if request.method != 'POST': # display blank register form form = UserCreationForm() else: # deal filled form form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # auto login, and redirect to home page authenticated_user =authenticate(username=new_user.username,password=request.POST['password1']) login(request, authenticated_user) return HttpResponseRedirect(reverse('learning_logs:index')) context = {'form': form} return render(request, 'users/register.html', context) register.html {% extends "learning_logs/base.html" %} {% block content %} <form method="post" action="{% url 'users:register' %}"> {% csrf_token %} {{ form.as_P }} <button name="submit">register</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> {% endblock content %} -
Cannot install Pillow on Windows (Offline)
I downloaded the Pillow package from: https://pypi.org/project/Pillow/ The latest version is 6.2.1. But when I try to install it to my offline-computer, it gives the error: The header or library files could not be found for zlib, a required dependency when compiling pillow from source Then i tried downloading and installing it into my Internet connected PC and copied the installed folder in my venv to the offline system and placed it on the correct path (lib/site-packages). But when I run the command: python manage.py migrate It gives the same error again. My current Python version is 3.7. -
Django/i18n: how to translate method result in a template?
I am working on internationalization of my project. There is something I do not understand even reading Django documentation I have a view where I pass a context (a list) In my template, I loop on this list and run a method on each element of my list this method return a string ('string#1' or 'string#2' depending of the element) I would like to translate (en/fr) but I did not understand how to do it? Should I apply the translation in my models or in the template? Below a simplified code for an example models.py class mymodel(models.Model) def mymethod(self): condition = othermodel.objects.get(pk=self.ide) if condition == 1 : return 'string#1' # the string I want to translate else: return 'string#2' # the string I want to translate return '' views.py def test(request): mylist= _(["elt#1","elt#2","elt#3","elt#4","elt#5"]) return render(request, 'myapp/test.html', {'mylist': mylist}) test.html {% for element in mylist %} {{ element.mymethod }} {% endfor %} -
ModuleNotFoundError: No module named 'config' while running mypy
I have implemented mypy in my django rest framework but I am getting errors ModuleNotFoundError: No module named 'config' while running mypy.Is there any wrong with my django_settings_module in my mypy.ini file ? I used to run my project with the command python manage.py runserver --settings=config.settings.development which was working fine but while configuring this setting in the mypy it is giving me error. What I might be doing wrong ? mypy.ini [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main ignore_missing_imports = True files=**/*.py warn_unused_ignores = True strict_optional = True check_untyped_defs = True follow_imports = silent show_column_numbers = True [mypy.plugins.django-stubs] django_settings_module = config.settings.development settings directory /project /config __init__.py urls.py wsgi.py /settings base.py development.py wsgi.py app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "project")) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application()