Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /addtodo/: Not able to add new items in todo-list
I've tried to run this to-do app many times, first I wrote my own code, but it gave a lot of errors so I followed multiple tutorials, and read the documentation. First, I tried to submit data using html forms only(i.e.without making a forms.py file), but it didn't return anything and just kept redirecting to my todo page; although I was able to add new items through the admin-site, but my form didn't return anything. Second, I redid the entire project, removed the 'due_date' field (because it was causing problems) and created ModelForm in forms.py I found out the main problem lies somewhere in my views.py file, with my AddTodo function. I made changes in my function multiple times following instructions from here, here, and here when I was writing the views for html forms only. In my models.py file: from django.db import models # Create your models here. class TodoItem(models.Model): task = models.CharField(max_length = 100) category = models.CharField(max_length = 30) description = models.TextField() def __str__(self): return self.task In my forms.py file from django.forms import ModelForm from .models import TodoItem class TodoItemForm(ModelForm): class Meta(object): model = TodoItem fields = ["task","category","description"] In my project urls.py file from django.contrib import admin from … -
Django : How to generate multiple times the same form on a page?
I have to allow a user to register multiple participants to an event based on the number of participants that the user entered before. To make it clear : Event A : X participants --> X forms must be generated on the next page. So my code on the next view looks like this : if request.method == 'POST': for i in range(0, quantity - 1): eventParticipant_form = EventForm(request.POST, request.FILES) if eventParticipant_form.is_valid(): participant = eventParticipant_form.save(commit=False) participant.customer = customer participant.customerOrder = customerOrder participant.event = product participant.save() The problem is that it only save the last form that i fill. It make sens i think as if even if I generate X eventParticipant_form the form is not saved after. I don't really see how to do it the proper way. Any idea ? Thanks -
login using obtain_jwt_token return AnonymousUser django
I use obtain_jwt_token to login to my application (django framework) in front end react js i get the user but when i request this method from frontend i got AnonymousUser Bad Request: views.py class EmployeeAssetsView(APIView): #queryset = Employee.objects.all() serializer_class = EmployeeAssetsSerializer def get(self, request, format=None): print(request.user) try: employee = Employee.objects.get(name=request.user) serializer = self.serializer_class(employee, context={'request': request}) return Response(serializer.data, status=HTTP_200_OK) except: return Response({"message": "incorrect username or password"}, status=HTTP_400_BAD_REQUEST) url.py path('api/login/', obtain_jwt_token, name='login'), path('api/EmployeeAssets/', EmployeeAssetsView.as_view(), name='Employee-data'), it works in postman when i put jwt token in headers i don't know where is the problem -
Nginx Gateway timeout error in Ubuntu 18.04 after large file upload finished
Now I am using Ubuntu 18.04 and installed django project. After large file upload around 5GB, upload finished but still uploading status And after a long time, I see Gate way timeout error I checked the error log of Nginx and I saw this error 2019/12/18 08:47:26 [error] 10907#10907: *23 upstream timed out (110: Connection timed out) while sending request to upstream, 2019/12/18 09:15:10 [crit] 10907#10907: *49 SSL_do_handshake() failed (SSL: error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low) while SSL handshaking, client: 198.108.66.96, server: 0.0.0.0:443 2019/12/18 10:29:16 [error] 10907#10907: *110 connect() failed (111: Connection refused) while connecting to upstream, What is this error and where is the reason? -
When to use a custom model manager?
Right now i'm reading about custom managers that you can use to add additional logic when doing a CRUD action like Create. You make a custom manager class and then initialize the objects attribute of the table class with an instance of the custom manager class. I've also read that you can also use the pre_save and post_save signals to add additional save logic to the save action. My question is: When should i use a custom manager class over signals and is the use of a custom manager slower then the default manager of the Model class? Thank you -
Django Celery get TaskResult right after applying a task asynchronously
Is it possible to get the TaskResult object right after applying a task? Example: async_result = some_task.apply_async() TaskResult.objects.get(task_id=async_result.task_id) # raises ObjectDoesNotExist but getting after some delay works without any issues. -
Page 404 error in Password reset confirm in django 2.2.8
Dear All I am trying to create a password reset for my django project. Everything works including the email that is sent and the link where I enter a new password but I get the error as shown in screenshot as I click submit on my password_reset_confirm view. I am a complete beginner. Here are my urls.py: from django.urls import path from django.urls import path, reverse_lazy from django.contrib.auth import views as auth_views from accounts.views import login, register, logout from django.contrib.auth.views import PasswordResetView from django.conf.urls import url urlpatterns = [ path('login/', login, name='login'), path('register/', register, name='register'), path('logout/', logout, name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_form.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete') ] my main urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views urlpatterns = [ path('', include('home.urls')), path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), ] -
Python Complex List-Comprehensions
Is it any way to write this for loops with List-Comprehensions p_list = [] pt_list = [] for pt in part_task_list: pt.progress = pt.progress * pt.project_task.weight pt_list.append(pt) for p in part_list: for pt in pt_list: if pt.part.id == p.id: p.final_progress += pt.progress p.finla_progress = p.final_progress/100 p_list.append(p) -
Is it possible to connect with django to HP ALM database?
Is it possible to connect with django to HP ALM database? I tried by modify settings for db: """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'User': 'myuser', 'PASSWORD' : 'mypass', 'Host': 'https://alm.mydomain.com/qcbin', 'Domain': 'Project Domain', 'Project' : 'Project', } } """ and after that I run the command "python manage.py inspectdb > models.py" the models file is empty -
Django, overloading a function for post and get requests is a good practice? [closed]
Im farily new in Django, and I noticed you can check if the request is a POST or GET so you can build functions like this def policies_edit(request, policy_id): if request.method == "POST": #Do some stuffs return HttpResponseRedirect(reverse('policies_index')) #Do other stuffs return render(request, 'policies/edit.html', context) is this a good practice? should I try to do this for most crud functions? wont it make the code harder to understand? -
Using php login session for django application
I have developed a django application for my company of which I have to integrate with a current system that was built in php. My task is to ensure that users would not have to login separately on both applications thus a single sign on. Since the users are currently using the php application, I want a way whereby I can use the same user schema from the php and also when they are authenticated through the php application, they would not have to authenticate again in the django application. -
TypeError: LoginView() received an invalid keyword 'templates_name'. as_view only accepts arguments that are already attributes of the class
My url code ; path('login/', auth_views.LoginView.as_view(templates_name='users/login.html',name='login')), My error is; TypeError: LoginView() received an invalid keyword 'templates_name'. as_view only accepts arguments that are already attributes of the class. I dont understand this problem. -
why this error in django website keeping show to me in hosting?
somebody can tell me, why my website on hosting , show me this error when i add new link ? explain : i have uploaded my django project to namecheap (hosting) and it's running perfect , but my problem is when i try to add something from admin panel (link field ) and add it in url.py and views.py it's says Not Found The requested resource was not found on this server. but the link already exist in project ? for more explain open the app in website (mario): https://softdlr.com/pc_games/ it will show that message for you any help ? -
Saving other model atribute to form in django
I want to get an atribute of other model binded by ForeignKey from ulr or displayed page and save it to my form, that my dropdown will filled automatycly, as well as eg. form.instance.commentAuthor = self.request.user. My CreateView in views.py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = [ 'commentText', 'commentScenario' ] def form_valid(self, form): form.instance.commentAuthor = self.request.user form.instance.commentScenario = ??? return super().form_valid(form) I need to get the id of the currently displayed scenario, eg. from url. path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'), My models.py: class Comment(models.Model): commentText = models.CharField(max_length=256) commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE) commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE) commentDate = models.DateTimeField(default=timezone.now) How to do it? Can anyone help me? -
DRF image url not returning on filtering
If I write some queries in serializers or views and it does not return url of image, instead it returns /media/image.jpg why is that? for example class GetWishlistSerializer(serializers.ModelSerializer): review = SerializerMethodField() product = CustomForeignKeyField(required=False, queryset=Product.objects.all()) class Meta: model = WishList fields = ['id', 'user','product', 'review'] def get_review(self, obj): return Review.objects.filter(product_id=obj.product_id).count() this is not returning url of image but /media/product_images/image.png How filter effects on image url? class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) class ProductImage(models.Model): image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images', null=True) here is the model, without filtering everything works fine but with it does not work. -
How to get request from android to my django views?
I need to link my django models with android app.So i have to get data which send from android application to my django views.Also i need to compare the data exist on my django model.But i don't know how do i get the response .Any help is appreciated. -
Django - Each view class is one .py file or all in one file?
I have a django project with about 100 class-based views (to now) in views.py file. now the managing views is getting harder. if I put each view in a separate .py file and import all in views folder __init__.py, does it have affect on the performance? My issue is performance, not code style (to be pythonic or Java). what about DRF class-based views and serializers? -
Django + MongoDB - pymongo.errors.ServerSelectionTimeoutError
Im trying to implement MongoDB in my Django app like this: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'mongodb', } } But I get this error: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it Traceback: Traceback (most recent call last): File "c:\users\...\appdata\local\continuum\anaconda3\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\...\appdata\local\continuum\anaconda3\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\Users\...\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\...\env\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "D:\Users\...\env\lib\site-packages\django\core\management\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "D:\Users\...\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "D:\Users\...\env\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "D:\Users\...\env\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "D:\Users\...\env\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "D:\Users\...\env\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "D:\Users\...\env\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names return get_names(cursor) File "D:\Users\...\env\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "D:\Users\...\env\lib\site-packages\djongo\introspection.py", line 46, in get_table_list for c in cursor.db_conn.list_collection_names() File "D:\Users\...\env\lib\site-packages\pymongo\database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "D:\Users\...\env\lib\site-packages\pymongo\database.py", line 819, in list_collections _cmd, read_pref, session) File "D:\Users\...\env\lib\site-packages\pymongo\mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "D:\Users\...\env\lib\site-packages\pymongo\mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) File … -
Convert Django Website into Desktop Application
I want to wrap my Django Website and its database into a desktop app. The app needs to store data locally with no connectivity required to the website. -
How to write a single query for multiple tables having various columns resulting in the creation of rest api using python-django
I have several tables in my mysql database. I'm supposed to perform a single query for multiple tables having various columns resulting in the creation of rest api using python-django. I have created rest api for a single table but not for more than two tables. How can I solve this issue? I tried solving using queryset=model.objects.all() but resulted in not knowing which model to use. I also tried raw query but didn't get any result. Kindly help me out with a solution. -
Proforma payment in with Stripe
I'm building an application with Django and Stripe and I need to support payment with card (online) and manual payment (proforma). I've created a model like this: Transaction(models.Model): PAYMENT_CARD = 1 PAYMENT_PROFORMA = 2 PAYMENT_OPTIONS = ( (PAYMENT_CARD, 'Pay by card'), (PAYMENT_PROFORMA, 'Pay manually') ) payment_type = models.PositiveIntegerField(default=1, choices=PAYMENT_OPTIONS) uuid = models.CharField(max_length=200, unique=True) created_at = models.DateTimeField(auto_now_add=True) paid = models.DateTimeField(null=True) The idea is that every time a user makes a payment through application we add an insert into transactions table, and when the payment is processed by Stripe, through callback the paid property is updated. I'm having problems on how to incorporate manual payment into this flow, or whether manual payment can even be done via stripe or does the logic for manual payment have to be done inside the app itself. -
List user in a Django Channels group [version 2.3.0]
Is it possible to get the list of all present user in a django channels group. I thought about using a database and add / remove users manually each time someone connect/disconnect, but I wonder if there's a native solution included in the library. -
DRF - Token authentication alongside normal
I have an internal API where all ViewSets has LoginRequiredMixin because this API is used only by logged in users. Now I need to sometimes make it available through auth_token - eg. when the user is not logged in but has a token. I've added TokenAuthentication: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter'], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], } And tried to access API using Authorization header: Token <MYTOKEN> but it redirects all requests to log in. How to make it work so the user has to be either authenticated or use an Authorization header? This is a ViewSet: class OrderViewSet(LoginRequiredMixin, ModelViewSet): serializer_class = OrderSerializer filterset_class = OrderFilter -
How to call the methods of the model in django template?
I have the model of Invoicetracker in Models.py and I want to call the methods of the model in the template. Model.py class Invoicetracker(models.Model): TotalBillAmount = 0 invoicenumber = models.IntegerField() invoicedate = models.DateTimeField() BillAmount = models.IntegerField() TotalPaid = models.IntegerField() Remark = models.CharField(max_length=100) def __str__(self): return self.invoicenumber def totalbill(self): total = Invoicetracker.objects.all().aggregate( TotalBillAmount = Sum('BillAmount')) return total def totalpaid(self): total = Invoicetracker.objects.all().aggregate(TotalPaid = Sum('TotalPaid')) return total I want to call the method totalbill and totalpaid in the order.html template. Can I call this through instance method? or Shall we use an classmethod? -
How to rename and upload file using Django to an FTP server using django storages
I am using django-storages to let users upload files to a remote ftp location. settings.py DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' FTP_STORAGE_LOCATION = 'ftp://me:pwd@my.ftp.com:21' models.py from django.db import models from storages.backends.ftp import FTPStorage from django.conf import settings fs = FTPStorage() class FTPTest(models.Model): file = models.FileField(upload_to=settings.DEFAULT_FILE_STORAGE, storage=fs) However, I would like to validate and rename the file before uploading. This is my renaming method: def update_filename2(instance, filename): import os, uuid from django.core.exceptions import ValidationError ext = os.path.splitext(filename)[1] # [0] returns path+filename valid_extensions = ['.png', '.jpeg', '.jpg', '.xlsx', '.xls', '.txt', 'csv'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') path = "documents/" ext = filename.split('.')[-1] _format = "%s_%s.%s" % (instance.id, uuid.uuid4(), ext) return os.path.join(path, _format) Previously I used this file-renaming callable with upload_to but now, upload_to calls for something else. Is there a way to rename first and upload then?