Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing Django application with --parallel argument in Shippable
I have an application in django / python. I use Shippable to run my tests. In the shippable configuration file "shippable.yml", I use the following command: coverage run --source='.' manage.py test apps/ --parallel 2 But with that, Shippable displays a false coverage at just 23% But if I remove --parallel 2 like this: coverage run --source='.' manage.py test apps/ I get 58% Do you know how can I get the correct coverage using --parallel 2? -
How to test phonenumber_field.modelfields.PhoneNumberField
I am using django-phonenumber-field to store a phone number in my model. While covering the model with unit tests, raised a question of what would be an appropriate unit tests to test this field. The module itself is well tested and I should not retest this logic. But what shall I test instead? from phonenumber_field.modelfields import PhoneNumberField class User(models.Model): first_name = models.CharField(max_length = 50) phone_number = PhoneNumberField(null=False, blank=False, unique=True, help_text='Phone number') -
How to switch from MySQL to Postgre on Heroku
I want to host a django project on heroku. Locally, I developed it using MySQL database. And I have also pushed it to heroku but I get an Error message whenever I run heroku open command on command prompt. The error message is Can't connect to local MySQL server through socket. Though I'm a newbie in using databases, the way I understand the error is that heroku can't connect to local MySQL server which I'm using for local development. I don't want to connect to a remote MySQL database, instead, I want to connect to Postgre database just as heroku recommended. Being a newbie in the use of database, I don't know the best way to migrate to Postgre or how to add MySQL in my project to .gitignore. Is it possible for me to start running Postgre on heroku while MySQL isn't added to . gitignore and is still the database in settings.py? Must I clear MySQL database or add it to gitignore before I can use Postgre? -
Gitlab, How to have Multiple Project Folder in one repo, and only run unit test on merged project folder
I would like to create a Gitlab repo that have multiple projects accessing the same shared folder below are the details Repo of Project A Shared Folder project_folder 1 project_folder 2 project_folder 3 for each project_folders have it's own unit test when merge to git only runs it's own pipeline when deploy the whole project A gets deployed To be more specific, I have a django project, however as the project grows bigger, i would like to split the different sets of API into a project_folder of it's own However, each project_folder needs to refer to the same shared folder(django models, shared functionality code) So i would like to know if Git have a way to support this, and for each individual project_folder when i merge, gitlab will only run the unittest for the individual project_folder Thanks -
Why I obtain this error migrationg data from SQL Lite to Posgres DB ? duplicate key value violates unique constraint
I am pretty new in Django and Python and I am trying to follow this videotutorial about how to migrate a Django application from SqlLite to Postgres database: https://www.youtube.com/watch?v=ZgRkGfoy2nE&t=554s But I am finding some problem. Following the details on what I have done: I am working on Ubuntu 20.04 and I have a Django application made by someone else that uses SQLLite and that have to be migrated on Postgres. Following the previous tutorial I have done the following steps: First of all I installed Postegres and PgAdmin4 on my Ubuntu system. Then here I created a DB named dgsrgdb that have to be my new database for my application in replacement of SQL Lite DB. I installed this package to let Python\Django operate with Postgres: pip3 install psycopg2-binary I performed the backup of my original SqlLite DB by this command: python3 manage.py dumpdata > datadump.json and I obtained the datadump.json file that should contains the data inside the original DB that have to moved on the new Postgres DB. Into the Django settings.py file I replaced this configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } whith this configuration related to Postgres: DATABASES = { … -
DataInput in Django forms
I would like to ask if it is possible in DataInput to set date display range only for given month I have already something like this in my files: forms.py class DataInput(forms.DateInput): input_type = 'date' class TimeInput(forms.TimeInput): input_type = 'time' class AvailabilityForm(forms.ModelForm): class Meta: model = Availability fields = ['user', 'date', 'starting_hour', 'ending_hour'] widgets = { 'date': DataInput(), 'starting_hour': TimeInput(), 'ending_hour': TimeInput() } I would just like the user to be able to select a day from the current month I would appreciate any advice -
Changing default Django site name and domain from example.com to the proper ones
According to the Django documentation (here): django.contrib.sites registers a post_migrate signal handler which creates a default site named example.com with the domain example.com. This site will also be created after Django creates the test database. To set the correct name and domain for your project, you can use a data migration. Isn't it safe to directly change the default values from the Django admin panel? why? -
Need a downgrade of Django on MacOS
I'm currently using Django version-3.1.5 but for my university course it's recommended for testing version-2.2.17. Was wondering how to downgrade using MacOS Terminal? When I use pip3 install Django-2.2.17 I get a error message saying I'm already on a newer version of Django. -
In Django, how to add username to a Model automatically, when the Form is submitted by a logged in user
In my Django app, I have defined a Many-to-one relationship using ForeignKey. Now what I want is that when a logged-in user submits the ListForm then his username should automatically add to the owner field of the ListModel. Currently when a user submits the form, None is being shown in the owner field, how I can add the username to the database along with the form? my models.py: from django.db import models from django.contrib.auth.models import User class ListModel(models.Model): owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) task = models.CharField(max_length=255) completed = models.BooleanField(default=False) my forms.py: from django.forms import ModelForm from .models import ListModel from django import forms class ListForm(ModelForm): class Meta: model = ListModel fields = ['task', 'completed'] -
Prefetch cannot resolve keyword with self through table
I have these model relations class Category(models.Model): categories = models.ManyToManyField( "self",symmetrical=False, through='ChildCategory', through_fields=('from_category', 'to_category')) level = models.IntegerField(default=1, db_index=True) description = models.CharField(max_length=100, blank=True, null=True) breadcrumb = models.CharField(max_length=255, blank=True, null=True) is_leaf = models.BooleanField(default=False) display_category = models.BooleanField(default=False) category_order = models.PositiveIntegerField(default=0, db_index=True) class Meta: default_related_name = 'categories' verbose_name = 'category' verbose_name_plural = 'categories' ordering = ['category_order'] def __str__(self): return self.description class ChildCategory(models.Model): from_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='from_category') to_category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='to_category') category_order = models.PositiveIntegerField(default=0, db_index=True) class Meta: default_related_name = 'childcategories' ordering = ['category_order'] in context processor file i have this function from django.db.models import Prefetch from myapp.models import Category, ChildCategory def get_data(request): top_categories = Category.objects.prefetch_related( Prefetch('categories',queryset=ChildCategory.objects.select_related('from_category', 'to_category'),to_attr='children')).filter(level=1) print(top_categories.query) return { 'top_categories': top_categories, } but i get error Cannot resolve keyword 'category' into field How can i prefetch related child categories though the m2m ? -
why the django rest framework's search filter giving errors?
I am working on a demo DRF project to develop search and filter feature. However, I am not able to understand the issue with my project. I have some data stored in DB, and the GET is working fine. However, if I am doing some search operations in POSTMAN, I am seeing error, which is beyond my understanding. I have followed the below DRF official link. Below is the error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains [12/Jan/2021 11:32:53] "GET /api/shop/?search=Amitesh HTTP/1.1" 500 154116 Below are the project details: models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return user class Shop(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) shop_name = models.CharField(max_length=150) contact = models.CharField(max_length=10) State = models.CharField(max_length=100) district = models.CharField(max_length=100) location = models.CharField(max_length=100) … -
Django -: adding multiple songs to playlist
i am creating the playlist to add songs in it....but i am unable to add multiple songs...i do not how to add. models.py---> from django.db import models from django.contrib.auth.models import User # Create your models here. class Song(models.Model): movie=models.CharField(max_length=200,blank=True) song_name=models.CharField(max_length=200) artist=models.CharField(max_length=200) year=models.IntegerField() image=models.ImageField(upload_to='images/') song_file=models.FileField(upload_to='songs/') def __str__(self): return self.song_name class Playlist(models.Model): list_name=models.CharField(max_length=100) user=models.ForeignKey(User,on_delete=models.CASCADE) song=models.ForeignKey(Song,on_delete=models.CASCADE,blank=True,default=None,null=True) def __str__(self): return self.list_name views.py ---> in this i have addsongs_view function through which i am trying to add the songs to the playlist but it is adding the only one song to the playlist and that one song is updated to all other playlists i.e. if am adding one song to playlist_1 ...that is also added to playlist_2 and rest others. **I want to add multiple songs to playlist and those songs should not add be added in other playlist if i am not adding it please help me thank you:) ** from django.shortcuts import render,redirect,get_object_or_404 from .models import Song,Playlist from django.contrib.auth.models import User # Create your views here. def home_view(request): songs=Song.objects return render(request,'home.html',{'songs':songs}) def allplaylists_view(request): playlists=Playlist.objects currentuser=request.user return render(request,'allplaylists.html',{'playlists':playlists, 'currentuser':currentuser}) def playlistsongs_view(request): playlists=Playlist.objects.all() playlistName=request.GET.get('name') return render(request,'playlistsongs.html',{'playlists':playlists, 'playlistName':playlistName}) def createplaylist_view(request): songs=Song.objects if request.method == 'POST': playlist=Playlist() playlist.list_name=request.POST['playlistname'] playlist.user=request.user playlist.save() print(playlist.list_name,playlist.user) return render(request,'addsongs.html',{'songs':songs}) else: return render(request,'createplaylist.html',{'songs':songs}) def … -
Django migration error : return self.cursor.execute(sql, params) django.db.utils.ProgrammingError:
I tried to delete the migrations folder and db.sqlite3 as suggestions but it didn't work. I've also tried to downgrade version of django. Please look at the error below, I think it's the problem with database : The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "c:\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\user\models.py", line 8, in <module> from home.models import Language File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\home\models.py", line 21, in <module> for rs in llist: File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 54, in __iter__ results = … -
Serialize a get query in django-channels
I am trying to serialize a get queryset just as I did for filter below: from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): full_info = Order.objects.filter(order_number = number) data = serializers.serialize('json', list(full_info)) return data I keep getting certain errors, getting confused. I am trying to do something like: from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): full_info = Order.objects.get(order_number = number) data = serializers.serialize('json', list(full_info)) return data But it doesn't return a Queryset, so there are errors. How do I fix this? -
pylint with pylint-django doesnt throw errors for missing arguments
As far as I understood the function of pylint_django, not everything is possible due to the dynamic magic of Django, but missing arguments in "model fields" should be detected, right? I have this simple models class: from django.db import models class Product(models.Model): title = models.CharField() summary = models.TextField() CharField has a required argument max_length. Starting pylint: (project_venv) ➜ rorow pylint --load-plugins pylint_django --django-settings-module=rorow.settings products/models.py ************* Module products.models products/models.py:1:0: C0114: Missing module docstring (missing-module-docstring) products/models.py:2:0: C0115: Missing class docstring (missing-class-docstring) ------------------------------------------------------------------- Your code has been rated at 6.00/10 (previous run: 10.00/10, -4.00) Shouldn't the linter give an error here, like python manage.py runserver: ERRORS: products.Product.price: (fields.E130) DecimalFields must define a 'decimal_places' attribute. products.Product.price: (fields.E132) DecimalFields must define a 'max_digits' attribute. products.Product.title: (fields.E120) CharFields must define a 'max_length' attribute. -
Estoy iniciando en el python con django y tengo este problema: [closed]
Necesito buscar en una lista, pero necesito consultar en varias tablas o modelos que están relacionados. Un caso de ofidismo tiene lesionados (de la tabla Lesionados), ofídico (de la Tabla Ofidicos) y faboterápicos (de la tabla faboterá), además de sus campos específicos como Localización y Dosis de faboterápicos que se utilizaron en este caso específico. el código es este: def listar_ofidismos(request): busqueda = request.GET.get("buscar") post = Ofidismo.objects.all() if busqueda: post = Ofidismo.objects.filter( Q(Localización__icontains = busqueda) | Q(Dosis_Faboterápicos__icontains = busqueda) | Lesionado.objects.filter( Q(Nombres__icontains = busqueda) | Q(Apellidos__icontains = busqueda) ) | Ofidico.objects.filter( Q(Nombre_Cientifico__icontains = busqueda) | Q(Nombre_Popular__icontains = busqueda) | Q(Especie__icontains = busqueda) ) | Faboterapico.objects.filter( Q(Nombre_Comercial__icontains = busqueda) | Q(Nombre_Científico__icontains = busqueda) | Q(Compuestos__icontains = busqueda) ) ).distinct() print(post) paginator = Paginator(post,5) page = request.GET.get('page') post = paginator.get_page(page) return render(request, 'ofidismo_list.html', {'post':post}) No sé qué está mal, me dice algo del or, pero realmente no sé cómo formular esta consulta con varias tablas. Si alguien pudiera ayudarme! Please!! Gracias de antemano y saludos a todos los que están dispuestos a ayudar a la comunidad. Gracias! -
How can I create in Django Framework a serializers for a model self referenced ManyToMany with intermediate table
I am try to create a simple model that is referred to itself through an intermediate table. Below the code. class Entity(models.Model): ..... childs = models.ManyToManyField( to='Entity', symmetrical=False, related_name='from_entities', verbose_name='Child Entities', through='EntityChild', through_fields=('from_entity', 'to_entity')) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'entity' verbose_name_plural = 'Entities' The intermediate table below class EntityChild(models.Model): from_entity = models.ForeignKey( Entity, on_delete=models.RESTRICT, related_name='from_entity') to_entity = models.ForeignKey( Entity, on_delete=models.RESTRICT, related_name='to_entity') ....., type = models.CharField( max_length=255, verbose_name='Type') class Meta: db_table = 'entity_childs' And the serializeres class EntityChildSerializer(serializers.ModelSerializer): to_entity = serializers.RelatedField(many=False, read_only=True) def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) class Meta: model = EntityChild fields = ('to_entity', 'type',....) class EntitySerializer(serializers.ModelSerializer): fields = FieldSerializer(many=True) tags = TagSerializer(many=True) childs = EntityChildSerializer(source='from_entity', many=True) class Meta: model = Entity fields = ('id', 'childs', 'created_at', 'updated_at') So at the end my entity child will have a relation ManyToMany with the EntityChild that hold a reference to another entity. With the code below the serializer will return { "id": 1, "childs": [ null ],... } I tried follow this Nested serializer "Through model" in Django Rest Framework with no luck. Any help will be appreciated... Thank you all. -
Django TestCase crashes
I've created quite a few TestCases for my apps and everything was working as expected so far, recently I get this error Message when trying to run any TestCase (SimpleTestCase works fine, since it doesnt create any DB Objects, at least thats my theory). Example: # # pages/tests.py from django.test import SimpleTestCase, TestCase from non_voice.models import Product class HomePageTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEquals(response.status_code, 200) class ProductTests(TestCase): def setUp(self): Product.objects.create(product='test', product_name='test', header_text='test', language_code='DE') def test_text_content(self): product = Product.objects.get(id=1) expected_object_name = f'{product.product}' self.assertEquals(expected_object_name, 'test') Output: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/runner.py", line 684, in run_tests old_config = self.setup_databases(aliases=databases) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/runner.py", line 606, in setup_databases self.parallel, **kwargs File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/utils.py", line 156, in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/utils.py", line 272, in get_unique_databases_and_mirrors (connection.settings_dict['NAME'], set()) TypeError: unhashable type: 'set' I haven't changed anything I can think of, DB … -
How to insert a HTML Page inside HTML File without conflicting styles of each other
I have an HTML stored in database. I want to add that HTML page inside a HTML. the page has inline styling cdn of bootstrap etc. If I just add it inside a div element it affects the styling of the page that's it added to. How can I insert the html page in the html without conflicting styles of each other? -
Problems with creating obejcts with CreateView Django
I have a website with a blog section and when I am on a specific post page I want to add the comment section, where a specific user can leave a specific comment for a specific post. I tried a lots of methods but nothing is seems to work as expected. First I tried to handle this with a View class with get and post method and now I tried this and I'm not sure what is wrong with my code. my view: lass PostDetailView(CreateView): template_name = 'blog/post.html' form_class = CommentCreateForm slug = None def get(self, request, slug, *args, **kwargs): context = self.get_context_data(**kwargs) self.slug = slug post = Post.objects.get(slug=slug) context['banner_page_title'] = post.title context['page_location'] = 'home / post' context['post'] = post context['author_description'] = Profile.objects.get( user=post.author).description return render(request, self.template_name, context) def get_context_data(self, **kwargs): context = {} return context def form_valid(self, form): form.instance.user = request.user forms.instance.post = Post.objects.get(slug=slug) return super().form_valid(form) my model: class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') content = models.TextField(_('Content')) posted_date = models.DateTimeField( _('Posted Date/Time'), auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True) def __str__(self): return f'{self.author.username} - {self.post.title}' my html: {% if user.is_authenticated %} <div class="comment-form"> <h4>Leave a Comment</h4> <form class="form-contact comment_form" action="#" id="commentForm"> <div class="row"> <div … -
Reverse for 'chat_friend' with arguments '('',)' not found
I am building chat app and I am using Django Version 3.8.1. I am stuck on Error. 1 pattern(s) tried: ['chat_friend/(?P<pk>[0-9]+)/$'] This view is for Chat with friend private. views. def chat_friend(request, pk): # Chat info friend = get_object_or_404(User, pk=pk) chat_box = ChatBox.objects.filter( user_1=request.user, user_2=friend).first() if not chat_box: chat_box = ChatBox.objects.filter( user_1=friend, user_2=request.user).first() for message in Message.objects.filter(Q(is_read=False), ~Q(message_sender=request.user)): message.is_read = True message.save() chat_messages_list = Message.objects.filter( chat_box=chat_box).order_by('date') paginator = Paginator(chat_messages_list, 7) if request.GET.get('page'): page = int(request.GET.get('page')) else: page = 0 page = paginator.num_pages - page try: chat_messages = paginator.page(page) except EmptyPage: chat_messages = [] except PageNotAnInteger: chat_messages = paginator.page(paginator.num_pages) if request.method == 'GET' and not request.GET.get('action') and not request.GET.get('page'): return render(request, 'chat_friend.html', {'friend': friend, 'chat_messages': chat_messages, }) elif request.GET.get('page'): return JsonResponse({'chat_messages': serialize('json', chat_messages)}) elif request.GET.get('action') == 'load_new_messages': last_message_id = int(request.GET.get('last_message_id')) chat_messages = Message.objects.filter( chat_box=chat_box, id__gt=last_message_id).order_by('date') return JsonResponse({'chat_messages': serialize('json', chat_messages)}) urls.py path('chat_friend/<int:pk>/', views.chat_friend, name='chat_friend'), profile.html Chat The Problem When i open profile.html in browser after put <a href="{% url 'chat_friend' friend.id %}">Chat</a> link, I got an error named :- ` Reverse for 'chat_friend' with arguments '('',)' not found. 1 pattern(s) tried: ['chat_friend/(?P[0-9]+)/$']`. Please, tell me where is the Problem. When I start a chat through Admin. Chat is working fine with Two … -
Show loading gif until the django view performs the data processing and renders the template with this data
I have a django project where the page has multiple nav links. On clicking any nav link, the urls.py redirects to nav specific view and the view needs to perform some processing to get the data needed to render the template. def nav_view(request): rows = Model.objects.all() data = get_data(rows) # takes about 15-20s return render(request, 'app/nav1.html', {'data': data}) The processing of data required to render the template takes some time in the order of 15-20s and until this time I would like to show a loading gif to the user. As the page is not rendered yet I am not sure how to do this. Could someone please help how to make the view the point to a loading gif on a page until the actual template is rendered. -
Django Form save error due to input field
I created a system with Django. I have several users. This users has comp_name. When a user open signup or signup update page, he/she cannot see this field. It is a hidden field. Only admin can see it. In signup page and admin page there is no error. But in the signup update (profile edit page) the label of comp_name is shown and input is hidden and there is a form error: Select a valid choice. That choice is not one of the available choices. 2-3 days ago it works but now it is not working. What is wrong in my code? models.py class UserProfile(AbstractUser): ranks = ( ('Analyst', 'Analyst'), .... ) comp_name = models.CharField(max_length=200, default='', blank=True, null=True) ... rank = models.CharField(max_length=200, choices=ranks) image = models.ImageField(upload_to='profile_image', blank=True, null= True, default='profile.png') forms.py class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your role?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False, widget=forms.HiddenInput()) class Meta: model = UserProfile fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'rank', 'comp_name', 'image') labels = { "comp_name": "" } class SignUpChangeForm(UserChangeForm): email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your role?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False) class … -
Which database and backend is best for an Ecommerce website?
I am currently developing an ecommerce website. I am wondering which database should I use for my site. Relational Database vs Non-Relational Database like SQL vs NoSQL which one is the best? also the stack, I know Django and Node.js (Express) but Django is my primary if I have to say. But I've seen people using MERN stack for eCommerce. So I just want to know which one is the best one. -
how to push new file to a repository in Github using python[Django]
I created a new repository on github.com and I need to push the file that I generated via Django python application, I need to automate the push sequences to GitHub repo once the file is generated using python. I already refer to this How do I push new files to GitHub? But I don't want to provide credential default into the code, I prefer to use login authentication via GitHub authenticator in a web browser and once login it starts to push the generated HTML file. Thank you in Advance!!!