Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, celery and kombu: how to allow pickle?
I want to use picker as the celery serializer. I'm getting a kombu error that pickle is not allowed. Celery documentation says (https://docs.celeryproject.org/projects/kombu/en/master/userguide/serialization.html#guide-serialization) By default Kombu will only load JSON messages, so if you want to use other serialization format you must explicitly enable them in your consumer by using the accept argument: But I have no idea how to implement that. I have celery[redis]==5.1.2 and in my project's settings.py I have tried CELERY_TASK_SERIALIZER = 'pickle' which leads to the error. (This setting is not documented here, is it old? https://docs.celeryproject.org/en/stable/userguide/configuration.html#task-settings) -
Facing Error While Pushing Code To Heroku
I have python Application in django and Pushing the code to Heroku using following command git push heroku master but at the end faces following error: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/ktietz/src/ci/alabaster_1611921544520/work' Can anyone help, Thanks in advance -
Django db field not displaying modified slug field value after serializing
I am trying get the user names instead of user id, in the created_by field of the Comment class. My model is below: class Comment(models.Model): thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) content = models.TextField() created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) Have used slugfield in the serializer. class CommentSerializer(serializers.ModelSerializer): created_by = serializers.SlugRelatedField( slug_field='email', queryset=User.objects.all()) class Meta: model = Comment fields = ("id", "thread_id", "content", "created_by", "created_at", "likes") Where as in the api below, the field created_by still has user id and not email. @action(detail=True, methods=["GET"]) def list_comments(self, request, pk): comments = Comment.objects.filter( thread_id = pk ) data = json.loads(serialize('json', comments)) print("**************data**************") print(data) return Response(data, status.HTTP_200_OK) The data printed looks like this : [{'model': 'blog.comment', 'pk': 20, 'fields': {'thread_id': 19, 'content': 'hi', 'created_by': 2, 'created_at': '2021-07-14T03:34:11.333Z', 'likes': 0}}] Is this because of serialize? How do I correctly get the value of the created_by as user email and not id ? -
Unable to load django variables in html through static javascript file
I have defined my javascript file inside static folder of my django project with path js/info.js and content as follows:- function info() { $('#outer_info').append('<div id="get_info"></div>'); console.log('info_btn clicked') document.getElementById('get_info').innerHTML = `<div class='modal fade' id='exampleModal1' tabindex='-1' aria-labelledby='exampleModal1Label' aria-hidden='true'> <div class='modal-dialog modal-dialog-centered modal-md'> <div class='modal-content' style='background-color:#47423e;'> <div class='modal-header'> <h3 class='modal-title text-white' id='exampleModal1Label'>xbguvolrtktest</h3> <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button> </div> <div class='modal-body'> <center><h3 class="text-white">Bucket Details</h3> <table class="table table-dark table-sm table-hover border-white"> <tbody> <tr> <td class="text-white">Items in Bucket:</td> <td class="text-white">{{ bucket_item_count }}</td> </tr> <tr> <td class="text-white">Bucket Size:</td> <td class="text-white">{{ bucket_size }}</td> </tr> <tr> <td class="text-white">Last Updated On:</td> <td id="last_updated" class="text-white">{{ last_updated_time }}</td> </tr> <tr> <td class="text-white">Directories:</td> <td class="text-white">{{ directory_count }}</td> </tr> <tr> <td class="text-white">Files:</td> <td class="text-white">{{ file_count }}</td> </tr> </tbody> </table> <br></center> </div> <div class='modal-footer'> <button type='button' class='btn btn-secondary' data-bs-dismiss='modal' style='background:#e2513c'>Close</button> </div> </div> </div> </div> <input type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal1" data-bs-whatever="@mdo" id="infoButton" hidden>` document.getElementById("infoButton").click(); } Here is how it is being called in index.html file:- <script src="{% static '/js/info.js' %}" type="text/javascript"></script> This is basically a Bootstrap Modal. The problem is that the value of the django variables is not getting rendered on html although it works fine when I include the entire script inside index.html directly. Here is how it looks:- What might be going … -
Django select count of same foreign keys within the same model
I have this model: class File(models.Model): id = models.CharField(max_length=21, null=False, blank=False, primary_key=True, unique=True) id_content = models.ForeignKey(Content, db_column="id_content", on_delete=models.CASCADE) I want to select the id and the count of other files with the same Foreign Key as this id. I literally have got no clue about where to define such query inside filter, extra etc. I have done this previously inside this MySQL query, but I'm looking for a Django Model solution: SELECT f1.`id` AS id, (SELECT COUNT(f2.`id_content`) FROM `file` AS f2 WHERE f2.`id_content` = f1.`id_content`) AS total FROM `file` AS f1; Thanks -
Use image URL in easy_thumbnail django
Currently I am using the following code in my django template which I use to display a picture and crop accordingly: <img src= "{% thumbnail obj.picture 375x550 box=obj.cropping crop detail %}" alt=""> instead I want to use the obj.picture.url instead of the picture object itself. Is there anyway to do this using django's easy_thumbnails. I don't want to use another way because I already have a cropping feature setup that I am using accross the app. -
django, gunicorn, grpc: "Failed to pick subchannel" if run django grpc client with gunicorn
I am a beginner in the Django framework. I wrote an application consist of 2 microservices. One as a Django Rest Server and the other as a Django GRPC Server. the rest request translated to GRPC requests in the first server and sent to the second for the process. ------>|-----------|------->|-----------| |rest server| |grpc server| | | | | <------|-----------|<-------|-----------| when I ran the first server with python manage.py runserver ip:port the application works properly. but when I ran the first server with gunicorn myapp.wsgi --workers=1 --bind=ip:port, a grpc request from the rest server randomly counter an error: {"created":"@1593330482.005402565","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":3981,"refer enced_errors":[{"created":"@1593330482.005396918","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_l ine":394,"grpc_status":14}]} the interesting thing is the grpc request was received by grpc server and it sent back the response. wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() -
GET HTTP 405 Method Not Allowed
I am getting the following error when trying to access view using the following url: http://127.0.0.1:8000/api/hello-view/. I have posted code below incorporated views.py and urls.py created in my django-app. I will appreciate if review codes and advise where the errors are: enter code here Error message: HTTP 405 Method Not Allowed Allow: OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } enter code here views.py file content: from rest_framework.views import APIView from rest_framework.response import Response class HelloApiView(APIView): def get(self,request, format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) enter code here urls.py file content from django.urls import path from profiles_api import views urlpatterns = [ path('hello-view/', views.HelloApiView.as_view()), ] -
For a project with multiple user types across different apps, what is the correct AUTH_USER_MODEL to specify in the settings conf?
I have a Django 3.2.5 project in which I want to implement the different user types Artist and User (normal site user). I wouldn't want to share one User model and have all user types sharing redundant fields, e.g. a regular site user wouldn't have artist-specific information. The Django documentation advises that when starting a new project it is best to create a custom user rather than to inherit the built-in User. I can implement two models, Artist and User (both inheriting AbstractUser) - but what would the value of my AUTH_USER_MODEL config then be? -
Do sandbox CopyLeaks result requests send headers?
When CopyLeaks sends the completed webhook to my server, I then send an export request like the following (note that I'm specifying "headers") { "completionWebhook": "***REDACTED***/copyleaks/webhook/exported/56", "crawledVersion": { "endpoint": "***REDACTED***/copyleaks/webhook/crawled/56", "headers": [ [ "Authorization", "PRECI ***REDACTED***" ] ], "verb": "POST" }, "results": [ { "endpoint": "***REDACTED***/copyleaks/webhook/result/56/2a1b402420", "headers": [ [ "Authorization", "PRECI ***REDACTED***" ] ], "id": "2a1b402420", "verb": "POST" } ] } but I don't see that "Authorization" header when CopyLeaks submits the result to the indicated URL. The result requests are being received by my Django website. This is what Django shows for headers: {'UNIQUE_ID': 'YO5jaCH4wN9w5X3ozii3nQAAAAY', 'SSL_TLS_SNI': 'dev.earlychildhoodeducator.com', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'POST', 'QUERY_STRING': '', 'REQUEST_URI': '/copyleaks/webhook/crawled/56', 'SCRIPT_NAME': '', 'PATH_INFO': '/copyleaks/webhook/crawled/56', 'PATH_TRANSLATED': '***REDACTED***/wsgi.py/copyleaks/webhook/crawled/56', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_KEEP_ALIVE': '600', 'HTTP_ACCEPT_ENCODING': 'gzip', 'CONTENT_LENGTH': '179', 'HTTP_HOST': 'dev.earlychildhoodeducator.com', 'SERVER_SIGNATURE': '', 'SERVER_SOFTWARE': 'Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/4.6.2 Python/3.6', 'SERVER_NAME': 'dev.earlychildhoodeducator.com', 'SERVER_ADDR': '10.68.195.10', 'SERVER_PORT': '443', 'REMOTE_ADDR': '35.239.30.65', 'DOCUMENT_ROOT': '/var/data/websites/dev.earlychildhoodeducator.com/static', 'REQUEST_SCHEME': 'https', 'CONTEXT_PREFIX': '', 'CONTEXT_DOCUMENT_ROOT': '/var/data/websites/dev.earlychildhoodeducator.com/static', 'SERVER_ADMIN': 'tech@earlychildhoodeducator.com', 'SCRIPT_FILENAME': '/var/data/websites/dev.earlychildhoodeducator.com/main/wsgi.py', 'REMOTE_PORT': '39827', 'mod_wsgi.script_name': '', 'mod_wsgi.path_info': '/copyleaks/webhook/crawled/56', 'mod_wsgi.process_group': 'pacrimdev', 'mod_wsgi.application_group': 'dev.earlychildhoodeducator.com|', 'mod_wsgi.callable_object': 'application', 'mod_wsgi.request_handler': 'wsgi-script', 'mod_wsgi.handler_script': '', 'mod_wsgi.script_reloading': '1', 'mod_wsgi.listener_host': '', 'mod_wsgi.listener_port': '443', 'mod_wsgi.enable_sendfile': '0', 'mod_wsgi.ignore_activity': '0', 'mod_wsgi.request_start': '1626235752847504', 'mod_wsgi.request_id': 'YO5jaCH4wN9w5X3ozii3nQAAAAY', 'mod_wsgi.queue_start': '1626235752847648', 'mod_wsgi.daemon_connects': '1', 'mod_wsgi.daemon_restarts': '0', 'mod_wsgi.daemon_start': '1626235752847734', 'mod_wsgi.script_start': '1626235752847820', 'wsgi.version': (1, 0), 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': … -
TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'DeferredAttribute' django
Good afternoon community, I am new to Django and in order to practice, I am building a financial website. The goal is that the user will insert data regarding company x, e.g. Apple, and the website will perform some metrics calculations to return to the user. I have two models so far: class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name class Market_Cap(Company): market_cap= Company.share_price * Company.outstanding_shares When I run python manage.py check I get the following error: Market_Cap market_cap= Company.share_price * Company.outstanding_shares TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'DeferredAttribute' Any hints as to how I can solve this problem? Thanks a lot in advance. -
How do I display an image from an API in a Django
I am creating a website in Django. On the homepage I would like to display a different image on the every time the site's reloaded. I found an API with all the pictures I think I would ever need but I've never used an API before and I've found researching how to do this simple specific thing overwhelming. The docs didn't help me much either. I'm trying to use https://waifu.pics/docs. When you give a specific URL (ex. https://api.waifu.pics/sfw/dance ) you get a JSON with the actual Image URL you'd need to use. My first attempt: <a href="{% url 'index'%}"><img src="https://api.waifu.pics/sfw/dance" alt="Homepage IMG"> </a> I knew it would be more complicated than this but my first idea was to use the link in an ... that didn't work, because I need to get the specific URL every time. Any help would be appreciated, thanks. -
Why is django not finding any object matching the query, even though object is created
HEADSUP: I don't know if this is a duplicate. There are many with similar titles one, but they aren't answering my question. If it is a duplicate, however, please inform me. I have this model called Item: class Item(models.Model): title = models.CharField(max_length=120) date_created = models.DateTimeField(default=timezone.now) deadline = models.DateTimeField(default=timezone.now() + timedelta(5)) task = models.ForeignKey(Task, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) def __str__(self): return f'{self.title} for {self.task.title} - Item {self.id}' I have a delete view for Item: class DeleteItemView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Item template_name = 'function/delete_item.html' success_url = reverse('all-items') def test_func(self): item = get_object_or_404(Item, id=self.kwargs['pk2']) if item.task.author == self.request.user and not item.task.is_completed: return True return False def get_context_data(self, **kwargs): context = super(DeleteItemView, self).get_context_data(**kwargs) context['task'] = Task.objects.filter(id=self.kwargs['pk'])[0] return context Now, my problem is this. Whenever I try to go to this delete view, it results in an error, saying there is no item found matching the query (404). And it says Raised by: function.views.DeleteItemView . I am at my wits end, spending almost half a day trying to figure this out, but with no success. Any help or answers will be immensely and greatly appreciated. -
Ajax Like button is not working in infinite scroll javascript pagination
I am building a BlogApp and I build infinite scroll pagination using JavaScript, When user go down then page is loading and scrolling BUT When user likes a blogpost which came from infinite scroll then blogpost's like is showing directly JsonResponse message without ajax. AND when user like from top blogpost ( First Post ) which is already there without infinite scroll then like button is working fine. I have tried two libraries on infinite scroll but both are not working in ajax button. models.py class Blog(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) title = models.CharField(max_length=50) likes = models.ManyToManyField(User, related_name='blog_like', blank=True) views.py class BlogListView(ListView): model = Blog context_object_name = 'books' paginate_by = 5 template_name = 'blogs/blog-list.html' def post_like_dislike(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) # Like if request.GET.get('submit') == 'like': if request.user not in post.likes.all(): post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) return redirect('mains:posts') blog-list.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <body> <div class="blog-list"> {% for book in blogs %} <div class="card mb-3"> <div class="card-body"> <h5 class="card-title">{{ book.title }}</h5> <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'post_like_dislike' book.id %}" data-pk="{{ book.id }}"> <span id="id_likes{{book.id}}"> {% if user in book.likes.all %} <p style="color:#065FD4;display: … -
Pushing and maintaining backend(Django) and frontend(Angular) folder in one repo
I have searched in google about this many says we can do this in two ways : creating the main repo and having one .gitignore file in there and pushing all in one repo. Maintaining separate git repo i.e for backend separate repo and frontend separate repo. So, I chose second-way i.e maintaining and pushing separate repo and I have structure projects with the backend(Django) and frontend (Angular) folders. But doing that creates a separate GitHub repo and I don't want to have a separate Github repo. What I want: I want to create in one repo with the folders backend and frontend but they should be maintained separately. My questions: How do I maintain and push in GitHub repo with separate backend and frontend folders in one repo? Is there any best practices? Please let me know how can I do it? -
Why is the foreign-key item not connected?
What is wrong with the setup of the models that foreign-key item ('Comment') doesn't seem to be connected? I am working on the Assessment part of Mozilla's Django tutorials and set up a blog-with four models: Post, Author, Comment, Commenter. While I can create posts and posts with comments, comments created separately aren't connected with posts. My code is here and this is following the Mozilla Django tutorial: class Post(models.Model): post_title = models.CharField(max_length=100) author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True) description = models.TextField(max_length=1000) comment = models.ForeignKey('Comment', on_delete=models.CASCADE) commenter = models.ForeignKey('Commenter', on_delete=models.CASCADE) class Author(models.Model): author_first_name = models.CharField(max_length=30) author_last_name = models.CharField(max_length=30) author_username = models.CharField(max_length=20) class Comment(models.Model): comment_title = models.CharField(max_length=100) comment_text = models.TextField(max_length=1000) commenter = models.ForeignKey('Commenter', on_delete=models.SET_DEFAULT, default=None, null=True) class Commenter(models.Model): commenter_username = models.CharField(max_length=20) -
Django JSONField query on a list of values where at least 1 value is in the filter list
I have this model: class Movie(models.Model): genres = models.JSONField(default=dict, null=False, blank=False) The data inside this column contains a list of genres e.g.: ["biography", "comedy", "crime", "drama", "romance"] When I try and execute the following code, I get empty: wanted_genres = ['action', 'adventure', 'animation', 'biography', 'comedy', 'crime', 'documentary', 'drama', 'family'] Movie.objects.all().distinct().filter(genres__contains = wanted_genres) I want to get results where at least 1 genre of wanted_genres is found in the column genres. I have tried a lot of filter techniques but I can't find a good array to array comparison method. Need help. Thanks. -
Nested Serializer Fields Django Rest Framework
I have two models (User and Province) and serializers. The user creates a province and in the province model I have the user id. The challenge is when creating nested serializers, I only want the first_name and last_name from the user but is is giving me everything including the password. Below are the serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['first_name', 'last_name'] class ProvinceSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Province fields = ['id', 'province_uid', 'province_name', 'date_created','created_by','user' ] read_only_fields = ('id','province_uid', 'date_created') depth = 1 -
Ajax POST method return None in Django
I use ajax to send data from template to view in Django. The javascript get the right value, but in my view function, when I get the value by request.POST.get(), it return None Here is my javascrip code $(".assests_list").on("submit",function(e) { e.preventDefault(); var form = $(this); var data = new FormData($(this).get(0)); var url = form.attr('action'); var host_id=$("#host_id").val(); $.ajax({ type: "POST", url: url, data: { form_data:data, host_id: host_id }, contentType: "multipart/form-data", dataType: "json", processData: false, contentType: false, success: function(data){ } }); }); Here is my view code: def get_id(request): if request.is_ajax and request.method == "POST": host_id=request.POST.get('host_id') print('host id: ',host_id) return HttpResponse("") When I print "host id" in view is return None, but in javascript it return a correct value -
Running Django and Postgres inside Docker causes : django.db.utils.OperationalError: could not connect to server: No such file or directory
After running docker-compose up, it seems to be spinning my postgres container but my django container raises an exception. The application runs fine outside docker. Postgres is running and on port 5432 django | Watching for file changes with StatReloader django | Performing system checks... django | django | System check identified no issues (0 silenced). django | Exception in thread django-main-thread: django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection django | self.connect() django | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner django | return func(*args, **kwargs) django | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect django | self.connection = self.get_new_connection(conn_params) django | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner django | return func(*args, **kwargs) django | File "/usr/local/lib/python3.9/site- packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection django | connection = Database.connect(**conn_params) django | File "/usr/local/lib/python3.9/site-packages/psycopg2/init.py", line 122, in connect django | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django | psycopg2.OperationalError: could not connect to server: No such file or directory django | Is the server running locally and accepting django | connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? django | django | django | The above exception was the direct cause of the following exception: django | django | Traceback … -
Django Viewset retrieve not working with Default Router
I am trying to access a specific comment using the retrieve method in Django View sets. I am using a default router in order to route my urls. I am able to list all comments at api/posts/, but am unable to get a single comment at api/posts/1. I am getting a type error: Field.init() got an unexpected keyword argument 'pk' when trying to access the URL. Any ideas as to why? urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from posts.views import PostsViewSet, CommentsViewSet router = DefaultRouter() router.register(r"comments", CommentsViewSet, basename='comments') urlpatterns = [ path("", include(router.urls)), ] views.py class CommentSerializer(serializers.ModelSerializer): id = serializers.IntegerField(label='commentID') comment = serializer.CharField() created_at = serializers.DateTimeField(required=False) updated_at = serializers.DateTimeField(required=False) posts = serializers.SerializerMethodField() class Meta: model = Comments # fields = "__all__" fields = ['id', 'comment','created_at', 'updated_at', 'posts'] def to_representation(self, instance: Comment) -> dict: '''Pass for now''' ret = super().to_representation(instance) return ret def get_queryset(self) -> QuerySet: qs = Comment.objects.all() return qs def create(self, validated_data: dict) -> Comment: return Comment.objects.create(**validated_data) def update(self, instance: Comment, validated_data: dict) -> Comment: '''Pass post-validation errors silently''' for field in validated_data: setattr(instance, field, validated_data.get( field, getattr(instance, field))) instance.save() return instance class CommentViewSet(viewsets.ViewSet): def list(self, request): queryset = Comment.objects.all() result = CommentSerializer(queryset, many=True) if … -
tinymce and vuejs integeration
I have this content, from the backend using Django and tinymce: I want to show this on a vuejs app savely, how can I do it "content":"Rather than having all of its functionality built into its core, Python was designed to be highly <a title="Extensibility" href="https://en.wikipedia.org/wiki/Extensibility">extensible (with modules). This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum's vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with <a title="ABC (programming language)" href="https://en.wikipedia.org/wiki/ABC_(programming_language)">ABC, which espoused the opposite approach.<sup id="cite_ref-venners-interview-pt-1_39-1" class="reference"><a href="https://en.wikipedia.org/wiki/Python_(programming_language)#cite_note-venners-interview-pt-1-39">[39]\r\nPython strives for a simpler, less-cluttered syntax and grammar while giving developers a choice in their coding methodology. In contrast to <a title="Perl" href="https://en.wikipedia.org/wiki/Perl">Perl's "<a class="mw-redirect" title="There is more than one way to do it" href="https://en.wikipedia.org/wiki/There_is_more_than_one_way_to_do_it">there is more than one way to do it" moenter code heretto, Python embraces a "there should be one— and preferably only one —obvious way to do it" design philosophy.<sup id="cite_ref-PEP20_69-1" class="reference"><a href="https://en.wikipedia.org/wiki/Python_(programming_language)#cite_note-PEP20-69">[69] <a title="Alex Martelli" href="https://en.wikipedia.org/wiki/Alex_Martelli">Alex Martelli, a <a title="Fellow" href="https://en.wikipedia.org/wiki/Fellow">Fellow at the <a title="Python Software Foundation" href="https://en.wikipedia.org/wiki/Python_Software_Foundation">Python Software Foundation and Python book author, writes that "To describe something as 'clever' is not considered … -
Design Decision - Should Django tests be state-less or state-full?
So, I am facing this dilemma of designing Django unit tests. I can either make the tests so that they do not depend on each other but this would either mean 2 things: I undo what I did in the test itself and for all the tests. I design the tests in such a way that they don't depend on each other. The second options is I can make the tests state-full as in a real use case scenario. A real user generally never undoes what was done before before performing another operation on the database right? Although I agree, state-less tests are in general better due to the fact that more things can be tested in CI as each test is an independent unit, I think for the database tests, state-full might be a better option. Please share your opinion. Thanks A Fellow StackOverflower -
django cross site redirection crsf token security
Ive been trying to integrate a payment method for my website, it requires verification from an external webpage (bank), it requires a response_url, from which the status and dat wil be posted back on my site, when it operates django gives me an error requiring a csrf token for posting a form, I found a workaround setting @csrf_exempt, but I asume its not the optimal solution, since is less secure, what is the correct solution for csrf token solicitaiton when posting from an external page? def pay_started(request): usu = CuentaUsusario.objects.get(usuario=request.user) response_url = 'http://xxx.xxx.x.xx:8000/cuentas/pay_inscr_finish/' if request.method == 'POST': username = request.POST.get('user_name') email = request.POST.get('email') response_url = request.POST.get('response_url') req = request.POST resp = MallInscription.start(user_name=username,email=email,response_url=response_url) return render(request,'c_cuentas/pay_started.html',{'usu':usu,'resp':resp,'req':req}) return render(request,'c_cuentas/pay_started.html',{'usu':usu,'response_url':response_url}) @csrf_exempt def pay_inscr_finish(request): if request.method == 'POST': req = request.POST token = request.POST.get('TBK_TOKEN') resp = MallInscription.finish(token=token) ttoken = resp.transbank_user authoriz_code = resp.authorization_code tarjeta = resp.card_type ult_dig = resp.card_number return render(request,'c_cuentas/pay_inscr_finish.html',{ 'utl_digit':utl_digit, 'tarjeta':tarjeta, 'ttoken':ttoken, 'authoriz_code':authoriz_code}) -
Is there a way to set a context variable's value within js or html when using Django?
I'm working on a website using python django as a back end, and am currently trying to pull values from a HTML form and pass it to a django form. This is due to only certain fields needing access to data from the database and needing JS on the page to show/hide based on the values of certain selects in the HTML. What I need to do is to set the value of an object's attribute that is passed in from the views.py <script> output = document.getElementById("example"); {{ form.fieldImChanging.value }} = output.value; </script> ... <form action="" method="POST" class="row gy-2 gx-3 align-items-center"> <label for="example">TestField</label> <input type="text" name="example" maxlength="16" size=20 required=""> ... <input class="btn btn-success col-3 mt-2" type="submit" value="Submit"> <a href="{% url '*snipped url*' *snipped vars* %}" class="btn btn-secondary col-3 mt-2">Back</a> </form> Where the trouble lies is in getting that context variable to set, because as of right now that will just create a variable named after whatever the default value of fieldImChanging is in the django form. Is there a way to do this with django at all?