Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pull a Serializer object into def create() function separately?
class ArticleCreateSerializer(serializers.ModelSerializer): images_set = ArticleImagesViewSerializer(source='images',required=False,many=True) tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('images_set','tags_set','id') def create(self,validated_data): images = self.context['request'].FILES.getlist('images_set') articleinit = Article.objects.create(**validated_data) tags = validated_data.pop('tags_set', None) for imageinit in list(images): m2 = ArticleImages(article=articleinit , image= imageinit ) m2.save() for taginit in list(tags): m3 = ArticleTags(article=articleinit , tag = taginit ) m3.save() return articleinit I am trying to post request array of tags and I have to pull them into create function separately for obvious reasons, I have to work them one by one in another serializer. My only request here is that how can U pull them correctly?This code does not work as intended(it pulls data as null value): tags = validated_data.pop('tags_set', None) Does anybody have a clue? -
How do set default values in django for an HttpRequest.POST?
how can i set a default value If the field is not sent?! for example my code: class SampleViewSet(ParentListAPIView): def post(self, request, *args, **kwargs): _email = self.request.data['email'] -
Issue with Paginiation
I am quite new to python/django and I am following CoreyMSchafer's youtube tutorials. However, when trying to get pagination to work it displays the elif command on the webpage itself and doesn't render it server side.elif code being displayed home.html {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add: '3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} {% endblock content %} -
count likes in ManyToManyField - django rest framework
in models.py: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] in serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() class Meta: model = Post fields = ('body','date','user') how to count likes of a single post? and also show which user liked the post. -
Digitalocean spaces too slow to upload even from the droplet of same region
I am using django-storages to upload my static and media files to digital-ocean spaces. Problem is it was really slow. All of the sudden, requests started becoming too slow. Then I started debugging with django-silk, and found that boto3 function was taking too much time. then inside the droplet itself, I tried to upload the s3cmd function. truncate -s 20M sample_file.txt #created a 20 mb file s3cmd put sample_file.txt s3://disbug-media The output was upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 1 of 2, 15MB] [1 of 1] 15728640 of 15728640 100% in 26s 584.56 KB/s done upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 2 of 2, 5MB] [1 of 1] 5242880 of 5242880 100% in 41s 123.58 KB/s done The 15mb part upload took 26 seconds and 5MB part took 41s 😱. My droplet and the spaces are in the same region. Is there anyway I could speedup the upload ? Or is this performance issue common in digitalocean spaces. I am really starting to regret for choosing DO as my infrastructure 😭. -
web developpement in python [closed]
I have a project where I need to build a website that keeps track of orders. The client just needs to enter the order number and it gives him the information that I want. I used python Django to build the website and request to get the data (API) I don't know how I can display the different orders. If you have an example of something similar or advice, please send it to me. Thanks -
Django Flask - Exception happened during processing of request
I'm getting this issue when I'm communicating with my app. At present I'm using flask and it is running on my local port. Here is the code which causes the first error: def _handle_request_noblock(self): """Handle one request, without blocking. I assume that selector.select() has returned that the socket is readable before this function was called, so there should be no risk of blocking in get_request(). """ try: request, client_address = self.get_request() except OSError: return if self.verify_request(request, client_address): try: self.process_request(request, client_address)(#error occuring at this line) except Exception: self.handle_error(request, client_address) self.shutdown_request(request) except: self.shutdown_request(request) raise else: self.shutdown_request(request) 2nd error: def process_request(self, request, client_address): """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ self.finish_request(request, client_address)(#error occuring at this line) self.shutdown_request(request) 3rd error: def __init__(self, *args, directory=None, **kwargs): if directory is None: directory = os.getcwd() self.directory = directory super().__init__(*args, **kwargs) #error at this line when I start communicating with the app it is showing error 503 the following error in the console: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 316, in _handle_request_noblock self.process_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 347, in process_request self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/server.py", line 647, in __init__ super().__init__(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ … -
Django AllAuth does not extend 'base.html', despite base.html existing in templates
base.html works for all other url links, but as soon as I load localhost:8000/accounts/ (e.g. logout or login), the css template does not work at all. The functionality still works, it's just the css that isn't working. This is as per the tutorial (From 8:22 to 10:44): https://www.youtube.com/watch?v=bopkZBbIa7c. I have followed the tutorial step by step, yet it gives a different result than the tutorial. (Just want to reiterate the functionality is fine, just plain django css) My current settings.py is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'posts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name='post_list'), path('post/<id>', post, name = 'post_detail'), path('search/', search, name = 'search'), path('tinymce/', include('tinymce.urls')), path('accounts/', include('allauth.urls')), path('accounts/profile/', blog, name='post_list') ] Any help would be appreciated. Thanks. Django version 3.1.4 Python 3 -
NoReverseMatch Error in Django when mapping items
I am trying to map different items using the pk(primary key). I have used it in my urls.py, views.py as well as the templates file. But I am a NoReverseMatch Error. I have also tried changing the str to int in the urls.py file but it still gave the same error. I hope I could get someone to kindly help. Thanks error log Environment: Request Method: GET Request URL: http://localhost:8000/update-reservation/1/ Django Version: 3.1.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'dashboard', 'widget_tweaks', 'phonenumber_field'] Installed 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'] Template error: In template C:\Users\Habib\Documents\django\FIVERR\adam_mailk\templates\dashboard\super\admin\base.html, error at line 41 Reverse for 'updatebar' with keyword arguments '{'updatebar': ''}' not found. 1 pattern(s) tried: ['updatebar/(?P<pk>[^/]+)/$'] 31 : <aside class="left-panel"> 32 : <div class="logo"> 33 : <a href="{% url 'dashboard' %}" class="logo-expanded"> 34 : <img src="{% static 'logo.png' %}" style="background-color: white; width: 140px; height: 65px;" alt="logo"> 35 : </a> 36 : </div> 37 : <nav class="navigation"> 38 : <ul class="list-unstyled"> 39 : <li {% if request.path == '/dashboard/' %} class="active" {% endif %}><a href="{% url 'dashboard' %}"><i class="ion-home"></i> <span class="nav-label">Dashboard</span></a> 40 : </li> 41 : <li {% if request.path == '/updatebar/' %}class="active"{% endif %}><a href=" {% … -
.sql to ER diagram
i am trying to create a er diagram from a .sql file which was originally a sqlite file PLEASE HELP!!!! i tried to create an ER Diagram in mysql workbench but i got these errors PLEASE HELP!!!! PLEASE HELP!!!! PLEASE HELP!!!! ERROR: (1, 27) "django_migrations" is not valid at this position for this server version, expecting a new table name ERROR: (1, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (1, 1) "app" is not valid at this position for this server version, expecting an identifier ERROR: (1, 20) "NOT" is not valid at this position, expecting EOF, ';' ERROR: (8, 27) "auth_group_permissions" is not valid at this position for this server version, expecting a new table name ERROR: (8, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "group_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 13) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 41) "auth_permission" is not … -
convert django url with '|' (or) regex to modern Django path
I have a question regarding conversion of pre - Django 2 urls to path If I have an url like this: url( r'^some_path/(?P<type>type_one|type_two)/', views.SomeViewHere.as_view(), name='important_name', ), Question is how to convert this url to modern Django path keeping same functionality and keeping same name? Important aspect: kwargs type_one and type_two should be passed into view. Name parameter can’t be changed or split. What I have done: path('some_path/', include( [ path('type_one/', views.SomeViewHere.as_view(), kwargs={'type': 'type_one'}), path('type_two/', views.SomeViewHere.as_view(), kwargs={'type': 'type_two'}), ] ), name='important_name', ), But reverce doesn’t work with this configuration Thank you. ps. type is a string -
Django_filters and apache2 500 internal server Error
I'm try to use Django_filters for filtering in my app and use apache2 , so after I install Django_filters using below documentation https://django-filter.readthedocs.io/en/stable/guide/install.html then add INSTALLED_APPS = [ 'django_filters', ] the app crash and return 500 internal server error ,then try to update ubuntu and apache2 , nothing is change so what is the solution for it ? -
DRF: How to define a custom error message for UnsupportedMediaType exception during parsing
Question: What's the easiest way to define a custom error message when an 'Unsupported media type' error is raised by a Django Rest Framework parser? Some context For a certain APIView-based POST call, I use the default MultiPartParser, which requires the Content-Type: multipart/form-data. If this is not set correctly, Django responds with a 415 status code with a message like "Unsupported media type "application/x-www-form-urlencoded" in request." However, I'd like to customize this message (i.e., including that multipart/form-data should be used). I know I can define custom serialization validation error messages in serializer classes using the error_messages property of a field (docs here). I couldn't find anything similar for the parser. (apart likely from creating a custom parser) The skeleton of my POST view looks like this: class UploadView(APIView): parser_classes = [MultiPartParser, ] def post(self, request): ... return Response(status=status.HTTP_204_NO_CONTENT) Triggering the 415 error described above is easy using e.g. curl -d "test=123" http://localhost:8000/my/upload/url -
How do you successfully get the id of any of your objects that you want in django?
One piece of functionality I'm trying to build for a fantasy football app is to have a page where any logged in user can see a list of all the other teams and their scores so that you can compare your score to teams of other users. Earlier today I got some interesting advice that suggested making a function in views.py that can show any team - not just your own. The function would obviously need to get the id of the team you want to display. It sounds logical, but I can't think of how to start/implement this though. This is the model object in question. class Team(models.Model): team_name = models.CharField(max_length=255, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) quarter_back = models.ForeignKey(Quarterback, on_delete=models.CASCADE, null=True) running_back = models.ForeignKey(Runningback, on_delete=models.CASCADE, null=True) wide_receiver = models.ForeignKey(Widereceiver, on_delete=models.CASCADE, null=True) tight_end = models.ForeignKey(Tightend, on_delete=models.CASCADE, null=True) kicker = models.ForeignKey(Kicker, on_delete=models.CASCADE, null=True) I've tried making a function but I get a 404 error because there's no id submitted to the url in the first place. How can you get the object's id if there is no id showing in the template's url? If I manually type the object's id integer at the end of the url, it does get … -
How to create a custom GET method that matches a certain URL patttern?
I am using a DefaultRouter and have a custom method in it. Right now I am passing values as POST but I want to pass as GET with the pattern like example.com/wallets/balance/<customerID>/. I am using ViewSet. My current urls.py looks like: router = routers.DefaultRouter() router.register('wallets', views.WalletView, basename='WalletModel') router.register('wallets/balance/1/', views.custom_balance,basename='CustomBalanceModel') # This crashes and models.py def custom_balance(id): return Response({'status': 'OK', 'data': 'success'}, status=status.HTTP_200_OK) class WalletView(viewsets.ModelViewSet): ..... -
MultipleObjectsReturned at /cart/ in Django
i'm a beginner and i am getting this error "Exception Value: get() returned more than one Order -- it returned 2!" views.py def cart(request): customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() context={ 'items':items } return render(request, 'catalog/cart.html',context) models.py class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL, blank=True, null=True) date_orderd=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False, null=True, blank=False) transaction_id=models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product=models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order=models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity=models.IntegerField(default=0, null=True, blank=True) date_added=models.DateTimeField(auto_now_add=True) thanks. -
How to convert k8s resources into django models in real time?
How to convert K8S resources into Django models in real time and retain the mapping relationship between K8S resources, such as a cluster with multiple workloads. The K8S resource data I obtained through API is json data, which I converted into list data. I did not find a way to convert the list to Django's Queryset in real time, and it can also support ORM operations. I found a link to discuss how to convert list data into Django's QuerySet, but the solution can't solve my problem.I need help. -
I am getting object has no attribute update in my Django Website
I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks views.py def UpdateReservation(request, pk): table_exists = Reservation.objects.get(id=pk) form = ReservationForm(instance=table_exists) if request.method == "POST": if request.POST['table']: request.POST = request.POST.copy() table_exists = Reservation.objects.get(id=pk) try: if table_exists: time = form['time'] people = form['people'] comment = form['comment'] date_reserved = form['date_reserved'] email = form['email'] phone = form['phone'] first_name = form['first_name'] resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists) resrv.save() messages.success(request, "you have successfully edited.") return redirect(request.path) else: messages.error(request, "Unable to edit.") return redirect(request.path) except Exception as e: messages.error(request, "Unknown error" + str(e)) return redirect(request.path) context = {"form":form} return render(request, "dashboard/super/admin/update_reserve.html", context) After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update' -
Passing object from View.py to Template.html with Django
I am building my first application with Django, and I would like to add model object to a template. in the views.py I have : @login_required(login_url="/login/") def index(request): return render(request, "index.html") @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] html_template = loader.get_template( load_template ) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template( 'error-404.html' ) return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template( 'error-500.html' ) return HttpResponse(html_template.render(context, request)) def restricted_list(request): restrictednames = Restrictednames.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, '/restricted_list.html', {'restrictednames': restrictednames}) the object i am looking to pass through is restrictednames. in the template I have : <body> {{ restrictednames }} </body> But nothing shows up. The page http://127.0.0.1:8000/restricted_list.html does not seem to be loading using def restricted_list(request) function. I am sure this is fairly simple, but not familiar with the Django structure yet. Does anyone sees what I am not doing right please ? -
How can I use a JSON file such as a database to store new and old objects?
I get the JSON objects from one of the sites and I want to attach these objects into a JSON file. the task is: I want to use JSON file as a database to save all information from the site I get objects from it so, the data I will show it breaking into 2 data which titled by the date like so: first: will be new data that will appear in the news.html second: will be old data that will appear in the old.html the problems that I'm facing are, which file handling I have to use (r, a, w)? of course, will not be r because I want data to be written when new data comes from the request so, in this case, I should use (a or, w), but if I used w will override all data that exists in JSON file. and if I used a I will face 3 challenges in every request process I do: the main curly braces will repeat with new data that appended to File but I need to repeat data into the main curlies itself. curly braces will not be separated by a comma. in every request process that occurs … -
update a Model field in DetailView
As a newbie in Django, I'm sure there is something obvious I'm not seeing. I have a user model with a one to one relationship to a userprofile model, where I'm storing the profile photo. I mixed DetailView and Formview because I want the user to go to his details page and update just the photo, but somehow its not working for me. I know I could do the job with UpdateView, but for didactic purposes, can anyone tell me why this is not working? I'm trying to updated the model fields in the form_valid method but this is not working, they just remain with the old values. I thought at the beginning it was the photo that could not be updated because of some errors on my side, but I've tried also updating other string fields and it doesnt work. Here the code: (the commented out fields are the places where I tried updating several model fields using get_object_or_404 and other functions) class UserDetail(FormMixin, DetailView): template_name = "users/user_detail.html" model = User form_class = forms.UserPhotoForm def get_success_url(self): return reverse('users:user_detail', args=[str(self.get_object().pk)]) def get_context_data(self, **kwargs): user = self.get_object() form = forms.UserPhotoForm(instance=user) context = super().get_context_data(**kwargs) context['user_rating'] = CotizacionReview.objects.filter(cotizacion__user=self.get_object()).aggregate(Avg('nota')) context['form'] = form return context … -
Can't obtain token with graphql_jwt even with valid login credentials
I am using Django 3.1.4 alongside the most recent version of this library and trying to obtain a token but I keep getting: { "errors": [ { "message": "Please enter valid credentials", "locations": [ { "line": 2, "column": 3 } ], "path": [ "tokenAuth" ] } ], "data": { "tokenAuth": null } } I have done everything right but this keeps happening. I am using a custom user model and I have created my own authentication backend as mentioned in #46. If I try logging in with an email, it throws that error, but if I use a username, it works fine. Anyone experiencing something similar? Here's my setup: ... # settings.py AUTHENTICATION_BACKENDS = [ "graphql_jwt.backends.JSONWebTokenBackend", "django.contrib.auth.backends.ModelBackend", "apps.auth.EmailBackend", ] GRAPHENE = { "SCHEMA": "cnapi.schema.schema", "SCHEMA_INDENT": 4, "MIDDLEWARE": ["graphql_jwt.middleware.JSONWebTokenMiddleware"], } GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_EXPIRATION_DELTA": timedelta(days=30), "JWT_PAYLOAD_HANDLER": "apps.accounts.auth.jwt_payload", "JWT_PAYLOAD_GET_USERNAME_HANDLER": ( lambda payload: payload.get("email") or payload.get("mobile") ), "JWT_GET_USER_BY_NATURAL_KEY_HANDLER": "apps.auth.get_user_by_natural_key", } # backends.py class EmailBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is not None: try: user = get_user_model().objects.get(email__iexact=username) except ObjectDoesNotExist: """Not found, try another backend""" else: if user.check_password(password) and user.is_active: return user return None def get_user_by_natural_key(username): try: return get_user_model().objects.get(email__iexact=username) except ObjectDoesNotExist: return None def jwt_payload(user, context=None): payload = { "mobile": … -
How to deal with Django translations / .po-files?
We have lot of problem in a project I'm working on now, regarding the texts. What we have now is a generated -po-file (committed in git) and one of the administrators of the site changes this file on github and then goes for the entire deploy process. Obviously, this is not ideal, very time consuming and error prone. Ideally you don't want to risk crashing the entire site from just changing one word on the site. I haven't found any good way of dealing with django translations from searching myself. Do you have any suggestions how to deal with this? https://phrase.com/ looks interesting, but isn't free. This looks interesting too, but means that we have to change quite a bit of code: https://github.com/dreipol/django-translator I'm thinking of writing something on my own that reads the po-file into the db and use those texts when compiling. But it feels like I would be reinventing a few wheels if I did that. Also, this would have to restart the server which feels a bit iffy. How do you deal with these translation issues? EDIT: All texts are generated using either the trans-template tag or ugettext -
Wagtail Contact Form but with a Template
So I have seen the tuorials and they are suggesting I make a Contact page so it is creatable within the admin section of WagtailAdmin but I don't want that. I already have a pre created contact Template page and I don't want to use the Wagtail way to auto generate form elements. Is there a way in which I can use my custom HTML template instead of having an auto generated one that I have to create within WagtailAdmin? I just want to be able to recive the input via a View and then process the data, is there a way in which I can accomplish this? Thanks. -
Django: Download .xls file
I have a button which downloads a excel file with extension .xls. I am using module xlrd to parse the file and return it back to the user. However it appears to add the object name into the excel file instead of the data. How can I return the file to the user with the data rather than the objects name? View def download_file(self, testname): import csv, socket, os, xlrd extension = '.xls' path = r"C:\tests\{}_Report{}".format(testname, extension) try: f = xlrd.open_workbook(path) response = HttpResponse(f, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension) return response except Exception as Error: return HttpResponse(Error) return redirect('emissions_dashboard:overview_view_record') Excel result Download successful: Content: Note: I understand this is an old file format but is required for this particular project.