Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any ways to run django server without changing Korean hostname to English hostname?
When I run django server on a computer which has English hostname, it runs without any problem. But with Korean hostname, it shows error. I have to use Korean hostname. Is there any ways to run django server without changing Korean hostname to English hostname? System check identified no issues (0 silenced). May 18, 2020 - 16:47:39 Django version 3.0.4, using settings 'tutorial.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\PycharmProjects\scoring\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Administrator\PycharmProjects\scoring\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Administrator\PycharmProjects\scoring\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Administrator\PycharmProjects\scoring\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 456, in __init__ self.server_bind() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte -
Generate unique id or class for the canvas tag eveytime a question is asked?
I just wanted to know is there any chance I can dynamically generate a random id for my canvas in js/HTML? I am appending a screenshot of my current work done until now.Current work In this image, there is a container in which a chart is rendering also there a expand button on the top left which takes to a modal where a zoom image of the same chart shows. My main concern is, for the first question it shows properly but when I ask second question it is not showing the chart in the second question's container. I think it is getting the same id which is why it is doing it so. I just wanted some references where I can generate new id every time a question is asked? Is it Possible?? I am a newbie to frontend coding a help would be great -
I want to one Goal to have different Dates and Checks, how should i structure the relationships?
This is the models.py file from django.db import models This are the choices i want to have # Create your models here. DISPLAY = [ ('Done', 'Done'), ("Didn't do", "Didn't do"), ] this is the Check model class Check(models.Model): Check=models.CharField( max_length=50, choices=DISPLAY, default='some') def __str__(self): return str(self.Check) this is the date model class Date(models.Model): Date=models.DateField(auto_now=False) Check=models.ForeignKey(Check, on_delete=models.CASCADE) def __str__(self): return str(self.Date) this is the Goals model class Goals(models.Model): Goal=models.CharField(max_length=50) Date=models.ForeignKey(Date, on_delete=models.CASCADE) def __str__(self): return str(self.Goal) I'm a newbie, how should i structure the relationships? -
how to change date format in xltw and how to set up a foreign key on django?
models.py class Admission(models.Model): date = models.DateField() id_type= models.ForeignKey( 'Type', null=True, on_delete=models.SET_NULL, related_name='type' ) class Type(models.Model): name = models.CharField(max_length=100,db_index=True) views.py def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Admission') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['date', 'type', 'name'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Admission.objects.all().values_list('date', 'id_type', 'name',) print(rows) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response urls.py path(r'^export/xls/$', export_users_xls, name='export_users_xls'), I want to export data to an excel file. in the exсel file, numbers are displayed instead of the date, and the value of the foreign key is as the model id. how can this be fixed? -
django tables2 create extra column with hyperlinks
I am using django-table2 and wanted to get an extra column Edit for each row. Here I am getting only a dash(-) instead of any link. Could you please help. tables.py class computertable(tables.Table): Edit = tables.LinkColumn("computer_edit", args=[A("int:id")], attrs={ 'a': {'class': 'btn'}, }) class Meta: model = Computer fields = ['computer_name','Edit'] urls.py urlpatterns = [ path('', views.computer_list, name='djform-home'), path('computer_edit/<int:id>/', views.computer_edit, name='computer_edit'),] -
Internal server error at every rest endpoint in django
I am working on a django application which is deployed on heroku, my application only consists of restApis as my main motive is to develop an android application using django as backend. My issue is when my DEBUG is False and i am sending request to any end point it returns 500 Internal Server Error as a response and working fine when debug is True. I used 'whitenoise.middleware.WhiteNoiseMiddleware' as i am using a cdn for my static files storage STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Here is my full code import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'rest_framework', 'rest_framework.authtoken', 'Birds', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'forBirds.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] … -
Can't get data from form in django template into view?
Currently both of these print statements either log 'None' or just do not show at all. Even if I just print("hello') in the form.is_valid conditional I do not see it. Not sure what I have done wrong but the data was saving into the django admin but now it is not... def create_user_account(request, *args, **kwargs): form = UserAccountForm(request.POST or None) print(request.POST.get('account_email')) if form.is_valid(): print(form['account_email'].value()) form.save() form = UserAccountForm() context = { 'form': form } return render(request, 'registration/register_user.html', context) and the html: {% block content %} <form action="{% url 'home' %}" method='POST'> {% csrf_token %} {{form.as_p}} <input type='submit' value='Submit'/> </form> {% endblock %}} edit: i do get "POST / HTTP/1.1" 200 when I send the request which is weird. -
How can I set form field value in a template in django forms?
So, here I have a piece of HTML code that is supposed to render a form using django form class. I have several forms on one page, they are rendered in 'for' cycle and should have different values as default (appointment.id). How can I set a value of a field here inside a template? Is in at least possible? {% for appointment in appointments%} {% load crispy_forms_tags %} <form action="/register/" method="post" class="inline"> {% csrf_token %} <div class="form-group w-25"> <div class="col-sm-10"> {{form.appointment_id|as_crispy_field}} </div> <input type="submit" class="btn btn-primary mt-1" value="Register"> </div> </form> </p> {% endfor %} -
How to add pylint for Django in vscode manually?
I have created a Django project in vscode. Generally, vscode automatically prompts me to install pylint but this time it did not (or i missed it). Even though everything is running smoothly, I am still shown import errors. How do I manually install pytlint for this project? Also,in vscode i never really create a 'workspace'. I just create and open folders and that works just fine. ps. Im using pipenv. dont know how much necessary that info was. -
Django serve Angular App only loads polyfills.js and shows empty page
Currently I try to serve my Angular App through Django static dir. I already run the two apps seperate on port 8000 and 4200 and everything works! Now I wanted them to work on one server. I run "ng build" and stored the dist folder in Django static folder. I added a Template folder in Django App dictionary and created index.html Edit the index.html as follows: {% load static %} Home created a view and url, which loads the index.html edit the settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) run server with command "python manage.py runserver" Now the page shows the loading gif and in the console I can see that polyfilly.js is loaded, but nothing else happens. Why isnt my Angular page showing up ? -
I get database error when creating serializer data
I am trying to create article by receiving data from serializers.py but i always get exception error in my code. Serializers.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Article fields = ('caption','details') def create(self, validated_data): article = Article.objects.create(**validated_data) return article Django Shell Output File "C:\Users\Umar\Desktop\Umar\Project\Backend\server\accounts\serializers.py", line 55, in create article = Article.objects.create(**validated_data) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 740, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 777, in save_base updated = self._save_table( File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 907, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1375, in execute_sql cursor.execute(sql, params) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Umar\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) … -
Progress bar that update after completion of each function in Django
I make an OCR application which take an input image from user and do this following steps (In order): Image Processing Bounding Box Character Segmentation Predicting each characters But Since this all above steps is taking too much time, so I decided to implement a progress bar which show how much process is done to users. But I am new to Django and I read about celery-progress-bar. Ans I can't figure out how do I use this in my app. Here is what I thought, what my view.py should look like: def my_function(request): # Here I want to start progress bar .... cleared_image = image_processing(image) # Image Processing segmented = character_segmentation(cleared_image) # Segmented Characters as list (in sorted) ..... predicted = [] # This list will store prediction of each character for character in segmented: .... prediction = predict(obj.picture) predicted.append(prediction) ### Here I want to Update Progress bar .... def image_processing(image): # Correct skew and Do Image Processing ### Here I want to Update Progress bar return resulted_image def character_segmentation(image): #Do Bounding Box and character Segmentation ### Here I want to Update Progress bar return list_of_characters -
API Key cannot access a view in Django when using the library: Django REST Framework API Key
I am using the DjangoRestFrameworkAPIKey for my Django Project I have a view to create a client(ClientCreateAPIView), which is only accessible when an API Key is sent. I first create an Organization and then I create an API Key. Then, I try to make a POST request to the ClientCreateAPIView. I am using POSTMAN to send POST requests. So in Postman, in the "Header" section, I have X-Api-Key written in the Key Field and the API Key in in Value Field. However, whenever I make a POST request, I get a "Authentication credentials were not provided." 403 error. This error does not happen, when I comment out the permission classes code from the view - I can access the view then. I tried a lot of variations of X-Api-Key, capitalizing them, removing the dashes but nothing seems to work. Also, I know that the API Key exists because in the Django shell, I can print out the id of the APIKey that I am using. I cannot debug what is causing the error. Following are some code snippets that could be useful: mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'rest_framework_api_key', ] API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" api/models.py … -
Use Django's Generic Date Views There's a 404 error
views.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDAV.as_view(), name='post_day_archive'), path('archive/today/', views.PostTAV.as_view(), name='post_today_archive'), ] urls.py from django.views.generic.dates import DayArchiveView, TodayArchiveView from blog.models import Post class PostDAV(DayArchiveView): model = Post date_field = 'modify_dt' class PostTAV(TodayArchiveView): model = Post date_field = 'modify_dt' error code Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/archive/today/ Raised by: blog.views.PostTAV No posts available You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When using DayArchiveView, template is opened, but 404 error occurs when using TodayArchiveView.On the official website of the library (https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-date-based/), I'm sure TodayArchiveView and DayArchiveView have the same template name, but why does 404 error occur only when I use TodayArchiveView? Why does the TodayArchiveView alone have 404 errors when both use the same template? Just in case, I named the template for TodayArchiveView as something else and tried using another template, but there is still a 404 error. Is there anything I missed? I'm sorry for my poor English. -
Can someone helps me to create a Django Project?
I wanted to create a Django project with PyCharm. So I created a project with templates.. PyCharm generates nothing. On my Desktop after creating is a directory named MI always if I create a project and in this Directory are following datas: __init__.py asgi.py settings.py urls.py wsgi.py manage.py Why is this folder on my desktop ?? And why is there no template directory? Environment : Virtualenv Base Interpreter is : /usr/bin/local/Python3.8 under More settings: Template Language : Django Mark on Django admin I´m using a macOS I hope anyone can help me -
Django 3: Form with model and dynamic count of elements that the initial model is a foreign key for?
I have the following models: class Entry(models.Model): number = models.IntegerField(max_length=255, blank=True) name = models.CharField(max_length=255, blank=False) class AdditionalVisitor(models.Model): name = models.CharField(max_length=255, blank=False) entry = models.ForeignKey(Entry, on_delete=models.CASCADE, blank=False) Now I want to create and display a form that allows a user to create one Entry and as many AdditionalVisitors as they like. When they submit the form, one Entry and all the AdditionalVisitors are persisted into the database with the Entry being the foreign key for each of the AdditionalVisitors. How would I go ahead and do this? I've read about formsets in the docs but I'm not sure how to apply them for this exact use case where I have foreign keys and want the number of elements to be dynamically changeable. Thanks in advance for trying to help me! -
(Django) Http POST request keeps returning bad request. I ran out of ideas regarding how to debug this
I have been trying to emulate Instagram login which takes either one of 'username', 'fullname', or 'email'. Below are the files for my 'account' Django app that I created: account/urls.py from django.urls import path from .views import SignInView, SignUpView urlpatterns = [ path('signup', SignUpView.as_view()), path('signin', SignInView.as_view()), ] account/models.py from django.db import models class Account(models.Model): email = models.CharField(max_length=200) password = models.CharField(max_length=700) fullname = models.CharField(max_length=200) username = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'accounts' account/views.py import json import bcrypt import jwt from django.views import View from django.http import HttpResponse, JsonResponse from django.db.models import Q from .models import Account class SignUpView(View): def post(self, request): data = json.loads(request.body) try: if Account.objects.filter(email=data['email']).exists(): return JsonResponse({"message": "ALREADY EXIST"}, status=409) hashed_pw = bcrypt.hashpw(data['password'].encode('utf-8'),bcrypt.gensalt()).decode() Account.objects.create( email = data['email'], password = hashed_pw, fullname = data['fullname'], username = data['username'], ) return JsonResponse({"message": "SUCCESS"}, status=200) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=400) class SignInView(View): def post(self, request): data = json.loads(request.body) try: if Account.objects.filter(Q(email=data['email']) | Q(username=data['username']) | Q(fullname=data['fullname'])).exists(): account = Account.objects.get(Q(email=data['email']) | Q(username=data['username']) | Q(fullname=data['fullname'])) encoded_pw = account.password.encode('utf-8') encoded_input = data['password'].encode('utf-8') if bcrypt.checkpw(encoded_input, encoded_pw): token = jwt.encode({ 'email' : account.email }, 'secret', algorithm='HS256').decode('utf-8') return JsonResponse({ 'access_token' : token }, status=200) return HttpResponse(status=403) return HttpResponse(status=402) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, … -
Embedding interactive Bokeh Plots into Django project
I've a Django project where we use matplotlib within an App to plot charts and save them as PNG files, and use Buffer of the photos within views and urls. Now, we want to elevate the project and add some interactivity like the hover and zoom options in Bokeh. I managed to use to Bokeh, but still not able to embed the new interactive plots instead of the static photos. -
How to use Lower() to sort a queryset in reverse order
If I don't use the Lower() function when sorting a queryset, then my queryset sorts uppercase and lowercase values separately. So if my queryset contains "Apples, Bananas, cherries, Oranges" and I use order_by('name') then I get: "Apples, Bananas, Oranges, cherries". If I use order_by(Lower('name')) then all works fine. My problem is that my view sorts using MyModel.objects.all().order_by(order_by) where order_by is set using a user specified GET variable. Lower() errors when the GET variable tries to sort in reverse order, eg order_by='-name' I tried the following code but I get a traceback error when order_by='-name', but works fine when order_by='name': MyModel.objects.all().order_by(Lower(order_by)) I then tried something smarter, but now when order_by='-name' then the queryset stops sorting alphabetaically and just sorts using the object ID. But sorts fine when order_by='name'. Views.py @login_required def merchantgroups_show_all(request): order_by = request.GET.get('order_by', 'name') from django.db.models.functions import Lower if order_by[0]=='-': order_by = order_by[1:] merchant_groups = MerchantGroup.objects.all().order_by('-'+Lower(order_by)) else: merchant_groups = MerchantGroup.objects.all().order_by(Lower(order_by)) paginator = Paginator(merchant_groups,20) page = request.GET.get('page') merchant_groups2 = paginator.get_page(page) return render(request, 'monzo/merchantgroups_show_all.html', {'merchant_groups': merchant_groups2,}) Any ideas on how to get Lower() to work when the GET variable order_by starts with a negative value? -
Django Models Dynamic changing default value of ImageField
I have the following model: class ImageTest(models.Model): pic = models.ForeignKey(Pic, on_delete=models.CASCADE) image_field = models.ImageField(upload_to='images/', default=' << HERE I WANT TO CHANGE DYNAMIC >>') When adding a ImageTest Object, I select a pic from my existing Pic objects. But then, I want to auto-complete the image_field with a image from path that corresponds to the Pic object. For example: If I choose the Pic Object #1 (foreign key) -> my path for imageField to be: images/pic1.jpg If I choose the Pic Object #2 -> my path to be images/pic2.jpg and so on. How can I make this to be done the moment I choose the Pic object, not when pressing Save button? -
Pass kwargs to a form __init__ method with AJAX
I'm trying to dynamically filter query-set in one of my forms. The idea was i capture group and subgroup values from auxiliary forms with ajax, send them back to form's __init__ method, filter content in my form and reload it with jquery. class Press(models.Model): group = models.CharField() // ChoiceField subgroup = models.CharField() // ChoiceField class Order(models.Model): origin = models.ForeignKey(Press) class OrderCreateView(CreateView): def get_form_kwargs(self, **kwargs): kwargs = super(OrderCreateView, self).get_form_kwargs() request = self.request group = request.GET.get('group') subgroup = request.GET.get('subgroup') kwargs.update(request=request) kwargs.update(group=group) kwargs.update(subgroup=subgroup) return kwargs class OrderCreateForm(forms.ModelForm): def __init__(self, request=None, group=None, subgroup=None, *args, **kwargs): super(OrderCreateForm, self).__init__(*args, **kwargs) self.fields['local'].queryset = Press.objects.filter( group=group, subgroup=subgroup) urlpatterns = [ path('order/create/', OrderCreateView.as_view(), name='new_order'), path('ajax/order/create/', OrderCreateView.as_view(), name='ajax_new_order'), ] <script> $("#groupSelect, #subgroupSelect").change(function () { var endpoint = "{% url 'ajax_new_order' %}"; var group = $("#groupSelect").val(); var subgroup = $("#subgroupSelect").val(); $.ajax({ url: endpoint, data: { 'group': group, 'subgroup': subgroup, }, success: function (data) { $("#idOrigin").load(location.href + " #idOrigin"); } }); }); {% endblock %} </script> <form action="{% url 'new_order' %}" method='post' id="orderForm"> {% csrf_token %} ... <select class="form-control" name="group" id="groupSelect"> ... <select class="form-control" name="subgroup" id="subgroupSelect"> ... <div class="col-sm" id="idOrigin"> {{ form.origin }} ... <button name="submit" role="button">Save order</button> </form> The problem I face is this way i am not just updating one … -
TypeError at /accounts/login/ 'module' object does not support item assignment
i'm using django-allauth and my project was working good, aslo i didn't change any thing only make upgrade for pip after that i can't login to my project and give me the follwing error: TypeError at /accounts/login/ 'module' object does not support item assignment Traceback AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py in inner -
Broken image in Django
im getting a broken image i tried almost everything looked at a lot of questions but still not working settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media") STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static_root") STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), "static", "static_files") ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('products/', views.all, name='products') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the html file {% for item in product.productimage_set.all%} {% if item.featured %} <div><img src="{{ MEDIA_URL }}{{ item.image }}"/></div> {% endif %} -
request() got an unexpected keyword argument 'amount' in razorpay integration with django
I am trying to integrate Razorpay with my django application, As suggested in their documentation I did, pip install razorpay and Now I'm trying to create an order by doing, client = razorpay.Client(auth=("<key>", "<secret>")) resp = client.order.create(amount=5000, currency='INR', receipt='TR110462011', payment_capture='1') But I'm getting, request() got an unexpected keyword argument 'amount' I referred, request() got an unexpected keyword argument 'customer' But it was not much of a help. What am I doing wrong here? Thank you for your suggestions. -
Django + backgroundtask + AWS Elasticbeanstalk times out to deploy
I want to use Django-background-tasks on my Django projekt. Now, I want elastic beanstalk to run the process_tasks, so I added a cron job config file. This is read by the server, but deployment times out eventually without delivering an error. If I ssh into my EC2 and use type in the commands below it works. Does anyone know why this might be a problem? commands: processtasks: command: "source /opt/python/run/venv/bin/activate && source /opt/python/current/env && cd /opt/python/current/app && python manage.py process_tasks"