Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: send_login_mail() got multiple values for argument 'email'
I am learning Celery+Reddis and trying to send email through Celery. I have created a task in which I have encapsulated my send email logic. I am calling the send_login_mail function and passing the keyword arguments using .delay(). #views.py class SignUpOTP(APIView): permission_classes = [AllowAny] def post(self, request): request_email = request.data.get("email",) try: user = User.objects.get(email__iexact = request_email) return Response({"status": "User is already registered."}, status=status.HTTP_403_FORBIDDEN) except: if request_email: send_login_mail.delay(email=request_email, subject="[OTP] New Login for Connect App") return Response({'status':'OTP sent successfully.'},status = status.HTTP_200_OK) else: return Response({"status":"Please enter an email id"},status = status.HTTP_400_BAD_REQUEST) #tasks.py @shared_task(bind=True) def send_login_mail(email=None, subject="[OTP] New Login for Connect App"): print("Wowowofdsofsdojsdjdofdffdojodjodfdfjdoofdods\nsdfjdsfjdsofjdsojdsdsosdoosdjfosdsdfodf") OTP.objects.filter(otp_email__iexact = email).delete() otp = random.randint(100000,999999) msg = EmailMessage(subject, f'<div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;overflow:auto;line-height:2"><div style="margin:50px auto;width:70%;padding:20px 0"><div style="border-bottom:1px solid #eee"><a href="" style="font-size:2em;color: #FFD243;text-decoration:none;font-weight:600">Connect</a></div><p style="font-size:1.2em">Greetings,</p><p style="font-size:1.2em"> Thank you for creating an account on Connect. You can count on us for quality, service, and selection. Now, we would not like to hold you up, so use the following OTP to complete your Sign Up procedures and order away.<br><b style="text-align: center;display: block;">Note: OTP is only valid for 5 minutes.</b></p><h2 style="font-size: 1.9em;background: #FFD243;margin: 0 auto;width: max-content;padding: 0 15px;color: #fff;border-radius: 4px;">{otp}</h2><p style="font-size:1.2em;">Regards,<br/>Team Connect</p><hr style="border:none;border-top:1px solid #eee" /><div style="float:right;padding:8px 0;color:#aaa;font-size:1.2em;line-height:1;font-weight:500"><p>Connect</p><p>Boys Hostel, Near Girl Hostel AKGEC</p><p>Ghaziabad</p></div></div></div>', 'swaad.info.contact@gmail.com', (email,)) msg.content_subtype = … -
Django - Filter out All Values from one Field in Model and Delete
Part of my django website is that when a user deletes one value from one model it deletes all data within a field of another model. Currently I am having trouble filtering out all values from a field in a model to delete. I know all my other code works because as a test I can do... delete = Data_Repo1.objects.all()filter(user=request.user) delete.delete() This works great when inputed into my code below. My problem is that I need to delete all data from a field called "date1" in a model called "Data_Repo1" not delete all data from all field in a model called "Date_Repo1". I have tired "values("date1")" and "values_list("date1")" in place of ".all()" in the above code but I get the error "Cannot call delete() after .values() or .values_list()". How else can I "filter" out all values from one field from one model in order to delete them?. Code Below. Thanks in advance. def deletefield_repo1(request, pk): context = {} title = get_object_or_404(Field_Repo1, pk=pk) #Title is needed to have the database value to delete context['title'] = Field_Repo1.objects.values_list('title', flat=True).filter(user=request.user).get(pk=pk) #Just to print the name fo the field to delete for the user type = Field_Repo1.objects.values_list('type', flat=True).filter(user=request.user).get(pk=pk) if request.method == "POST": title.delete() if type … -
Django User status not saving during registration
I am using abstract user model. Default is_subscriber value is false is_subscriber = models.BooleanField(default=False). But I am trying to change it ture during registration but I am not understanding why it's not changing false to ture. here is my code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) is_subscriber = models.BooleanField(default=False) forms.py class SubscriberSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = UserManagement @transaction.atomic def save(self): user = super().save(commit=False) user.is_subscriber = True #here I am changing value False to True user.save() Subscriber.objects.create( user=user, email=self.cleaned_data.get('email'), first_name =self.cleaned_data.get('first_name'), last_name =self.cleaned_data.get('last_name'), ) my_group = Group.objects.get(name='SubscribersGroup') my_group.user_set.add(user) return user views.py class SubscriberSignUpView(CreateView): model = UserManagement form_class = SubscriberSignUpForm template_name = 'members/subscriber-registration.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'subscriber' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() why is_subscriber status not changing False to True? -
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'comment')
Hello guys. I will like you to help me solve this issue, I don't know, I am trying to get data related to a single post, like (list of comments for a particular post) which I did manage to get in my api but I don't know how to get it to display to the frontend(React JS), but I'm seeing something odd in the console log. maybe it might be the problem. check it out! my console log my (Backend) Django serializer -
How To Send Basic Auth Headers To Django From Angular?
I have this in my Angular request service: async login() { var key = localStorage.getItem('access'); var httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('username:password') }), }; return this.http.post('https://example.com/login/', httpOptions); } Here is my Django view: from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from rest_framework.decorators import api_view from django.http import JsonResponse from django.contrib.auth import authenticate, login import base64 import basicauth from django.contrib.auth import authenticate @method_decorator(csrf_exempt, name='dispatch') #@api_view(['GET', 'POST']) def login(request, format=None): auth_header = request.META.get('HTTP_AUTHORIZATION', '') token_type, _, credentials = auth_header.partition(' ') toAscii = credentials.encode('ascii') messageBytes = base64.b64decode(toAscii) message = messageBytes.decode('ascii') user = message.split(':')[0] return JsonResponse({"response":user}) When I do a postman request for Basic Auth the response I get back is: { "response": "username:password" } That's exactly what I want. With the Angular request I get: item Object { response: "" } Doing it with Angular, its as if I didn't send anything at all. HttpClient has a funny way about doing things. I couldn't receive query strings in Django without sending 'Content-Type': 'application/x-www-form-urlencoded', in my headers; I am assuming I need to do something unusual here as well. Anyone know how to get this working correctly? -
Trying to associate a function to a specific radio generated on Django to show a modal
im trying to make a modal show up upon a onclick event function on django, but whenever i try to do it, instead of overwriting/assing the function on the radio, they just generate another radio on the side, how i can do that? This is the html on django where the radios it is generated <div class="form-row"> <div class="col-lg-6 col-12 mb-1" style="line-height: 0px;"> <h6 style="margin: 0px;">TONALIDADE</h6><br> </div> {% for choice, valor in situacoes_disponIns|slice:":3" %} <!-- descobrir como colocar parametro dentro da função --> <input type="radio" class="col-lg-2 col-12 mb-1 d-flex justify-content-center align-items-center" value="{{ choice }}" name="sTonalidade" id="id_situacaoIns"> {% if choice is 2 %} <input type="radio" onclick="funcao1();" class="col-lg-2 col-12 mb-1 d-flex justify-content-center align-items-center" value="{{ choice }}" name="sTonalidade" id="id_situacaoIns"> {% endif %} And this is the function where i call the modal to show up on clickevent <script> function funcao1() // { $("#cq-open").appendTo("body").modal("show"); } </script> -
Django custom lookup field raises EmptyResultSet when passed empty set
I have been trying to implement the not_in lookup field, but it generates a different query to ~Q. On querying against a list of ids such as: ids = [1, 2, 3, 4] both my not_in and ~Q yield same queryset although their generated SQL is different. The issue I found with my implementation was that for example querying against an empty list empty_list ~Q(id__in=empty_list) will return all the rows whose ids are not in empty_list, in this case, all rows. But with my implementation, it returns an empty queryset. Code for above implementation for reference from django.db.models.lookups import In as LookupIn @Field.register_lookup class LookupNotIn(LookupIn): """ Acts as opposite to `__in` """ lookup_name = "not_in" def as_sql(self, compiler, connection): lhs, params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) return "%s NOT IN %s" % (lhs, rhs), params It generates different SQL to ~Q: In [28]: print(ShopItem.objects.filter(~Q(id__in=deleted_ids)).query) SELECT "shop_shopitem"."id", "shop_shopitem"."bakery_id", "shop_shopitem"."name", "shop_shopitem"."is_deleted", "shop_shopitem"."is_visible", "shop_shopitem"."number", "shop_shopitem"."description", "shop_shopitem"."special_information" FROM "shop_shopitem" WHERE NOT ("shop_shopitem"."id" IN (5c6a4164-252a-4aa5-abc1-62cebbc3119a, 6dcbc509-435e-4ccc-a6fd-6a48c652278f, f647ceac-34dd-4e1a-8fcd-ebb255b7d6f9, a1be4bc9-0a10-447f-8215-94df18c53fe2)) ORDER BY "shop_shopitem"."name" ASC In [29]: print(ShopItem.objects.filter(id__not_in=deleted_ids).query) SELECT "shop_shopitem"."id", "shop_shopitem"."bakery_id", "shop_shopitem"."name", "shop_shopitem"."is_deleted", "shop_shopitem"."is_visible", "shop_shopitem"."number", "shop_shopitem"."description", "shop_shopitem"."special_information" FROM "shop_shopitem" WHERE "shop_shopitem"."id" NOT IN (5c6a4164-252a-4aa5-abc1-62cebbc3119a, 6dcbc509-435e-4ccc-a6fd-6a48c652278f, f647ceac-34dd-4e1a-8fcd-ebb255b7d6f9, a1be4bc9-0a10-447f-8215-94df18c53fe2) ORDER BY "shop_shopitem"."name" ASC My second implementation … -
post_migrate signal - call just once after all migrations
In this (very simplified) example, I need to do one thing (call do_something_after_all_apps_migrated() ) after all the apps have migrated. The problem is that post_migrate signal is called once for every app. I have one app: after_migrations apps.py from django.apps import AppConfig from django.db.models.signals import post_migrate from django.dispatch import receiver class AfterMigrationsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'after_migrations' def ready(self): @receiver(post_migrate) def _post_migrate(sender,**kwargs): app_name = kwargs['app_config'].name if app_name == 'after_migrations': do_something_after_all_apps_migrated() As you can see this would work but the problem is that it is not guaranteed that my app (after_migrations) is the latest app that is migrated. That means the Database structure is not guaranteed. How can I call do_something_after_all_apps_migrated() after everything migrated? It does not have to be a signal. -
Customizing Django Admin Add User With Blank Password
I'm am creating a Django web app with customised users authentication policy: only the superuser has a password and the users identification is the email field. The users will only login by OAuth protocol so I don't need to store passwords for them. I created a custom user by overriding AbstractBaseUser class. Is there a way to allow Django Admin interface to add/edit users with a blank password field (unusable password)? Thank you. -
How do I close a browser tab after running Python?
I have a web application where I need to open a new tab, run some Python, then close the tab. The reason I'm doing it this way rather than redirecting to the previous page is because the users would like it to retain the search filters. I'm using Firefox to test it, and I'm aware that Javascript won't close the window if it wasn't opened with Javascript; apparently the same is true if I run any Python functions, because the "cancel" button on the same tab works without any problems. Things I have tried: using HttpResponseRedirect to redirect to a new page with a "close" button that runs a Javascript function to close - the function is definitely being called (I can prove this with a window.alert) but the "window.close()" line gets ignored (no errors or anything, it simply does nothing). using HttpResponse to return 'window.close()' in the Python code - again, if I change it to a window.alert, I can prove the script is running, but again, the 'window.close()' is completely ignored. adding a window.close() function to the Submit button - this only works if I run it before the "submit", in which case the tab will close, but … -
Django 4.0 NoReverseMatch
So I'm learning to create a confirmation email address while registering an account using Django. This is my urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('sign-up', views.sign_up, name='sign-up'), path('sign-in', views.sign_in, name='sign-in'), path('sign-out', views.sign_out, name='sign-out'), path('activate/<uidb64>/<token>/', views.activate, name='activate'), ] I'm having this email_confirmation.html template: {% autoescape off %} Hello {{ name }}! Please confirm your email by clicking on the following link. http://{{ domain }}{% url 'activate' uid64=uid token=token %} {% endautoescape %} tokens.py: from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) ) generate_token = TokenGenerator() And this is my views.py: def sign_up(request): # other code (didnt specify in this question) # Confirmation email current_site = get_current_site(request) email_subject = "Email confirmation of My Page" confirmation_message = render_to_string('email_confirmation.html', { 'name': user.first_name, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user), }) email = EmailMessage( email_subject, confirmation_message, settings.EMAIL_HOST_USER, [user.email], ) email.fail_silently = True email.send() return redirect('sign-in') return render(request, "authentication/sign-up.html") def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) … -
How to set the fields in Django based on inputs?
models.py class NewsImage(models.Model): IMAGE_TYPE = (('Attachments','Attachments'),('URL','URL')) news = models.ForeignKey(Post, related_name='News', on_delete=models.CASCADE) image_type = models.CharField(max_length=12, verbose_name='Image Type', choices=IMAGE_TYPE) attachments = models.ImageField(upload_to='media/news_images', verbose_name='Image Attachments', blank=True) url = models.CharField(max_length=255, verbose_name='Image url', blank=True) def __str__(self): return (self.news)+ ' - ' +self.image_type So, based on the image_type the choices should work. For eg: If choice = attachments then url field should be blank or If choice = url then attachment field should be blank I'm working on Django Rest Framework ModelViewSets So anyone can please help me solving these. Thanks alot -
Search fields in custom action method
now i'm studying DRF and have to do project with photo albums. One of my tasks is to create custom @action "patch" method, using model field "title", but i can't understand how to add fields for search in custom methods. We can see them in base methods, like "get", "patch" and "put", but i can't find any info about how to add them to custom actions. If anyone knows how to do it, please, tell me. My model: class PhotoAlbum(models.Model): title = models.CharField(verbose_name='Название альбома', max_length=50, null=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Автор') created_at = models.DateTimeField(verbose_name='Дата создания', editable=False, default=datetime.datetime.today()) class Meta: verbose_name = 'Фотоальбом' verbose_name_plural = 'Фотоальбомы' def __str__(self): return f'{self.title} Автор: {self.created_by} Дата: {self.created_at}' My view: def photo_album_view(request): photo_albums = PhotoAlbum.objects.all() context = { 'photo_albums': photo_albums, } return render(request, 'photo_album.html', context=context) My viewset: class AlbumFilter(django_filters.FilterSet): title = django_filters.Filter(field_name='title') class PhotoAlbumViewSet(viewsets.ModelViewSet): queryset = PhotoAlbum.objects.all() filterset_class = AlbumFilter serializer_class = PhotoAlbumSerializer pagination_class = ResultPagination filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', ] ordering_fields = ['created_at', ] -
How to make middleware object callable in Django 2.2
I'm trying to update a django/mezzanine application from python 2.7 to python 3.7. Can you help me in fixing the error below (CTypeError: 'CheckNewsDateStatus' object is not callable)? Seems that this class is not used at all; if I grep through all code only the attached settings.py and middleware.py match. Is it something partly implemented in django/mezzanine or it it so that the whole class can be removed as unnecessary ? I don't know how the code was planned to work and I don't know is the feature has been used at all... and I don't know how the callable objects should be presented in settings.py-file. (python-3.7) miettinj@ramen:~/pika-py-3.7/pika> python manage.py runserver 0:8034 BASE_DIR /srv/work/miettinj/pika-py-3.7/pika PROJECT_ROOT /srv/work/miettinj/pika-py-3.7/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE setting is not set, using closest match: %s" % tz) BASE_DIR /srv/work/miettinj/pika-py-3.7/pika PROJECT_ROOT /srv/work/miettinj/pika-py-3.7/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE setting is not set, using closest match: %s" % tz) … -
Unable to access context object in HTML page rendered in Django
The below view function send news object to HTML page but HTML page gives no result/blank page. def Newsdetail(request,slug): news = get_object_or_404(News,slug=slug) return render(request, 'newsfront/news_detail.html', {news:news}) below is the model class News(models.Model): title=models.TextField() .......... def get_absolute_url(self): return reverse('Newsdetail', kwargs={'slug': self.slug}) HTML PAGE <h5>{{news.title}}</h5> -
DRF Serializers .orderitem_set.all()
I was following serializer tutorial and came across some code that i did not understand its function. def get_order_items(self, obj): items = obj.orderitem_set.all() print(obj) print(items) return OrderItemSerializer(items, many=True).data What does the order item function do. The snippet was from the serializer class below: class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() """ Calculate order_items field """ def get_order_items(self, obj): items = obj.orderitem_set.all() print(obj) print(items) return OrderItemSerializer(items, many=True).data class Meta: model = Order fields = ('phone', 'first_name', 'delivery_date', 'delivery_time', 'address', 'comment', 'payment', 'order_items',) def create(self, validated_data): items_data = validated_data.pop('order_items') order = Order.objects.create(**validated_data) for item_data in items_data: OrderItem.objects.create(order=order, **item_data) return order -
Multi databases in django project, dublicate the database
Multi databases in django project, dublicate the database While posting the form of models, it must be stored in two databases at a time. like dublicate the database. settings.py DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'auth_db.db.sqlite3'), }, 'primary': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'primary.db.sqlite3'), }, 'app_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'app_db.db.sqlite3'), }, 'app2_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'app2_db.db.sqlite3'), } } DATABASE_ROUTERS = ['routers.AuthRouter', 'routers.PrimaryReplicaRouter'] Routers file in project read, write in first routers is working(auth_db), if create same in other it is not working. routers.py import random class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'auth', 'contenttypes'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'auth_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'auth_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def … -
error while hosting django site on local system
I am facing the following error while hosting a Django site on my local machine. I am doing the same thing in a VM and it is working fine. Can someone, please let me know what should I do differently while hosting it in local environment. Thanks in advance. -
How can I find if there is memory leak for my Docker + Django app?
I'm running my Django app with docker compose. There are 4 containers, web, postresql, nginx, cron. The web container in my dev server is using 170MB Ram, mainly running gunicorn / Django / Python / DRF. The web container in my production server is using 600MB Ram. It's definitely growing over time. I've set max requests and max request jitter for gunicorn (gunicorn byob.wsgi:application --workers=4 --threads=4 --max-requests=1000 --max-requests-jitter=30 --worker-class=gthread -b 0.0.0.0:8000) I don't want to restart the container coz it may affect some users. My questions are: how can I find out if there is a memory leak? how can I reduce memory usage? I am thinking to add a task queue to my 2GB ram server. But this issue may use up the memory. -
Have issues getting data to display on my web application
I am trying to get the "About us" information from my database to my web application but its not displaying, what could be wrong... here is the code from the database class About(models.Model): about_us = models.TextField() achieve = models.TextField(blank=True) image_abt = models.ImageField(upload_to="admin_pics", null=True) class Meta: verbose_name_plural = "About Us" def __str__(self): return self.about_us and here is the Html code ` {% extends 'jtalks/base.html' %} {% load static %} {%block content%} <section id="about-home"> <h2>About Us</h2> </section> <section id="about-container"> {% for about in abouts %} <div class="about-img"> <img src="{{ about.image_abt.url }}" alt=""> </div> <div class="about-text"> <h2>Welcome to TechEduca, Enhance your skills with best Online Courses</h2> <p>{ about.about_us}</p> <div class="about-fe"> <img src="images/fe1.png" alt=""> <div class="fe-text"> <h5>400+ Courses</h5> <p>You can start and finish one of these popular courses in under our site</p> </div> </div> <div class="about-fe"> <img src="images/fe2.png" alt=""> <div class="fe-text"> <h5>Lifetime Access</h5> <p>You can start and finish one of these popular courses in under our site</p> </div> </div> </div> {% endfor %} </section> {% endblock %} Nothing is displaying in the frontend of the website. -
Django and PostgresSQL - cannot cast type integer to date
When I run python3 manage.py migrate, I get this: Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0024_alter_userrents_return_date...Traceback (most recent call last): File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.CannotCoerce: cannot cast type integer to date LINE 1: ...TER COLUMN "return_date" TYPE date USING "return_date"::date ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 535, in alter_field old_db_params, new_db_params, strict) File "/home/ubuntu/bookclub/venv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 122, … -
Django: PNG not downloading, but opening in browser
I have one API response in which I have one URL, when I am clicking on the URL it is opening in the browser and not getting downloaded. I want to make it downloadable through the backend only. { "count": 1, "next": null, "previous": null, "results": [ { "id": 132, "certificate_url": "https://temp.com/images/export/61ca22ef07dd8b000980b7a9/image-1640637167913.png" } ] } -
django: html form submit without jumping into new page or refreshing/reloading
I am new to django and html. below is my first test web page of a simple online calculator. I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit". I saw there might be several different ways to do this work, iframe/AJAX. Since I am new, what is the really simplest way to achieve this goal? BTW, I dont write javascripts. html: <form method="POST"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="1" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="2" placeholder="Enter value" /> </div> <br /> <div>{{ result }}</div> <button type="submit">Submit</button> </form> view.py def post_list(request): result = 0 if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) print(request.POST) print(result) context = { 'result': result } return render(request, 'blog/post_list.html', context) -
Django Template :: How to Use POP() in django template
In Below code, am iterating through 2 list. users and roles, where I want to print first element from the roles list for the first element from the user. user = ['abc','cde'] roles = [[1,2,3] , [4,5,6]] for user 'abc' roles should be printed as 1,2,3 only. but am getting all roles for 'abc' user. <table> {% for u in users %} <tr> {% for r in roles.0 %} <th><b>{{ u }}</b></th> <td><b>{{ r }}</b></td> {% endfor %} {{ roles.pop.0 }} </tr> {% endfor %} </table> Can someone help me understanding that why the {{ roles.pop.0 }} is not deleting first element in the roles list? -
How to change the field of username to user_name in to django custom user model?
I have created custom user model. now I want to use user_name as username field instead of username. like shown in below code snippet. class CustomUser(AbstractBaseUser): username_validator = UnicodeUsernameValidator() user_name = models.CharField( _('username'), max_length=100, unique=True, help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) USERNAME_FIELD = 'user_name' i'm unable to do that. i'm getting below error: SystemCheckError: System check identified some issues: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.CustomUser'. <class 'accounts.admin.CustomUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'CustomUserAdmin', or an attribute or method on 'accounts.CustomUser' the reason of using this, is because all the project's database tables convention is like this. It would be more better if i could define field name is database just as we do for tables in Meta class like below. where i'm calling my customuser model as user model in db. class Meta: db_table = "user" is there anyway to call table field like this way ? class Meta: db_table_user_name = "username" if it possible then we dont need to change …