Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API Django Rest Framework on Cloud Run shutting down
I have implemented an API DRF on Cloud Run. The Dockerfile is the following: # Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.7-slim # Allow statements and log messages to immediately appear in the Cloud Run logs ENV PYTHONUNBUFFERED True # Prevents Python from writing pyc files to disc (equivalent to python -B option) ENV PYTHONDONTWRITEBYTECODE True ARG REQFILE=base.txt ENV REQFILE ${REQFILE} # install dependencies RUN pip install --upgrade pip # Copy application dependency manifests to the container image. # Copying this separately prevents re-running pip install on every code change. COPY requirements/*.txt ./ # Install production dependencies. RUN pip install -r ./${REQFILE} # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app It is the same as described in the documentation : https://codelabs.developers.google.com/codelabs/cloud-run-django#6 But since a few days, without any significative change on my code, I have … -
onclick how to toggle button and fa icons?
Here I have a post detail view ,where i want to toggle the color of like button, <li> <button style='margin-top:-20px' class="btn btn-link text-dark p-0 border-0 btn-outline-light" id="like-button" value="{{post.id}}">{% csrf_token %} <i class="fa fa-heart"></i> <span class="" id="like_count">{{post.likes.count}}</span> </button> </li> jscript: $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "posts:like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> I simply want to change the color of heart icon ; on click heart filled with red color and onclick heart become blank or white. -
Cannot Import Include From Django
After running the command from django.urls import include I get the error freduah@freduah:~/Desktop/DjangoReactTodo/todo$ ./manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fd1e13a4a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/freduah/Desktop/DjangoReactTodo/todo/todo/urls.py", line 18, in <module> from django.urls import include ImportError: cannot import name include Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f2db9839a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check … -
Report building in Django
I am trying to build a system which will enable my users to create their own reports based on the model of their choosing without me having to code them every time they need updating. In order to do this, I've come up with the following models:- from django.db import models from django.contrib.contenttypes.models import ContentType class ReportField(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_method = models.CharField(max_length=100) def get_value_for(self, object): return getattr(object, self.data_method) class Report(models.Model): name = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_fields = models.ManyToManyField(ReportField) The idea is that users can create a Report based on the model they're interested in. They can then add any number of ReportFields to that report and, when the report runs, it will call the data_method (the name of a property) on each instance of the model in the db. The bit I'm having trouble with is defining which properties the users can have access to. I need to have a way of creating a load of ReportFields with certain data_methods for each model. But I don't want to create them by hand - I want it to work in a similar way to the way Permissions work in Django, if that's possible, like this:- class MyModel(models.Model): … -
Handling database connection errors / operational error exceptions in Python / Django?
I am running multiple databases and I need to handle this exception. How can I do it either in the view or a more general approach ? I am using PostgreSQL. It's a bit ugly to wrap my whole code like below. import psycopg2 def Main(request): try: myqs = customers.objects.all() except psycopg2.OperationalError as e: print('operational error, handle this') return render(request, 'core/main/main.html', {'qs': myqs}) -
Calling a python function via AJAX in Django
I am sending a request via AJAX upon a button (whose id="transcript") click to trigger a function called transcript. AJAX document.querySelector('#transcript').addEventListener('click', () => { fetch(`transcript/${CNIC}`); views.py def transcript (request, cnic): form = TranscriptForm() return render (request, "certificates/transcripts.html", { "form": form, "cnic": cnic }) The fetch request works fine, but the new page i.e. transcripts.html does not render. I have to manually type the URL to update the view. Why is it happening, can anybody please explain? The output in console: views.js:62 Fetch finished loading: GET "http://127.0.0.1:8000/transcript/1530660001979". -
How create a project in Django path
I would like create my first project in Django. I have installed Python (Version 3.7.2) and Django (Version 3.1.2). In my PC I run a command py -m django startproject mysite, however there is no mysite file in C:\Users\misak\AppData\Local\Programs\Python . The mysite file has been created in C:\Users\misak . How can I create mysite file by default in C:\Users\misak\AppData\Local\Programs\Python , please? Because than I want to run the sever using a command py manage.py runserver, which is not possible now, because of an error "C:\Users\misak\AppData\Local\Programs\Python\Python38\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory" Thanks a lot! -
Storing File in Json Field, Django
I'm working on a project which requires users to submit posts of various forms. There are posts that require images and others that require videos. To deal with this and other complexities, I was thinking of using jsonfields. My current issue is handing files, that is images and videos. I was hoping to be able to store the file url in a field in the json field but I haven't come across anything like that on the internet. Is it possible or advisable to go on with this approach? If so, how can it be done? -
Main matching query does not exist
enter image description here main.models.Main.DoesNotExist: Main matching query does not exist. -
How to slice in django template by a string
I just want to slice a string on django in two parts, passing a caracter like "|" Example: 2007-007134|10003L Part 1: 2007-007134 Part 2: 10003L I tried somethings but without success Someone can help me? -
Django channels testing weird database behaviour
Django/channels newbie: I'm trying to write unit tests for my application, but I'm getting some weird behaviour from tests. I suspect it has something to do with either asynchronous code or django testing database but I'm lost. My consumer has this kind of structure: class GameConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['gameID'] self.room_group_name = 'game_%s' % self.room_name # check something from database to decide if this connection should be rejected if not await self.does_game_exists(): await self.close(4001) else: await self.accept() await self.channel_layer.group_add( self.room_group_name, self.channel_name ) # insert data into db await self.add_player_to_game() @database_sync_to_async def does_game_exists(self): .... @database_sync_to_async def add_player_to_game(self): .... This works when using the application normally; the data is inserted in the db. Now the unit test: class WSConsumerTest(TransactionTestCase): fixtures = ['test-data.yaml'] @database_sync_to_async def get_num_players(self): ... @database_sync_to_async def create_test_game(self): ... async def test_player_is_added_on_successful_connection(self): game = await self.create_test_game() application = URLRouter([ url(r'ws/game/(?P<gameID>[a-zA-Z0-9]{6})', consumers.GameConsumer), ]) communicator = WebsocketCommunicator(application, f"/ws/game/{game.gameID}") connected, _ = await communicator.connect() player_count = await self.get_num_players() self.assertEqual(player_count, 1, "Player is not added in database after successful connection") communicator.disconnect() This fails. get_num_players returns the number of player in the game instance created by create_test_game. I'm sure this two functions are correct, they are standard django ORM queries. I tried running test … -
Django rest framework, empty request.data when using UUID as id
I'm working on an API which can allow user to remove Project belonging to some specific Workspace. I used to do it by calling this URL with this JSON as data and it worked pretty fine. URL : .../my_api/workspaces/[workspace_id]/projects JSON : { "id": [project_id_to_remove] } But since I've replaced the default generated id to models.UUIDField, the same call raise a KeyError because request.data turn out to be an empty dict. I cannot figure what goes wrong since my others use cases works correctly even with the use of UUID as id. models.py: class Workspace(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) class Project(models.Model): workspace = models.ForeignKey('Workspace',related_name='workspace_projects',on_delete=models.CASCADE,blank=True, null=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) serializers.py class ProjectSerializer(serializers.ModelSerializer): def __custom_validator__(self, data): method = self.context['request'].method if method in ['DELETE']: projects_id = [project.id for project in self.instance] if data['id'] not in projects_id: raise serializers.ValidationError( "Action canceled: Not a Workspace project.") def validate(self, data): data = super().validate(data) self.__custom_validator__(data) return data class Meta: model = Project fields = ['id', 'workspace'] views.py class WorkspaceProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer def destroy(self, request, pk): instances = Project.objects.filter(workspace=workspace) serializer = self.get_serializer(instances, data=request.data) serializer.is_valid(raise_exception=True) # Perform deletion. project = get_object_or_404( Project, pk=serializer.validated_data['id']) self.perform_destroy(project) return self.__get_response__(workspace) -
How to best update the Django website from version 1.10 to the latest 3.1?
I'm just considering an update of an old website based on an old Django's wedding, still written in Python 2. It's a simple landing page with a couple of subpages. I would like to make an upgrade to the latest version 3.1. Unfortunately, the attempt to upgrade to version 2 failed (the previous developer created the site using so many additional modules that I don't see the possibility of meeting all the dependencies, because some of them are no longer expandable and supported. Is there any faster way to upgrade than to move the front-end to the latest version and write back-end again ? -
Django and snipcart product crawling
I'm using django and I've managed to implement dynamic discounts like this: Http request contacts the endpoint -> endpoint checks the request object to see if the user is authenticated -> if the user is authenticated, the view function checks the corresponding User object in the database to see if the user is eligible for a discount -> If he is, it takes the discount rate from the User object and uses it to change the price(s) in the queryset without touching the actual price in the database -> this queryset is then sent as a context to the template where it is rendered and picked up by snipcart's javascript. My question is this: When snipcart then crawls the URL, will it not do so with a different set of Http headers which would change the execution flow of the view function to display undiscounted prices as the request object that snipcart sends to crawl the URL would be un-authenticated? I suppose my question could be generalized like this: how does snipcart crawl protected URLs? https://docs.snipcart.com/v3/security -
What is the best practice while renaming Django Models? [Database: MySQL, PostgreSQL or SQLite]
I really want to know what is the best practice that could be done while renaming Django Models and Models Fields. Is there are preferred method or we should directly rename and migrate each FIELD or MODEL inside Django. -
Working with different Bokeh components from server_document() in Django View
I have a bokeh server running containing a graph and dropdown menu. I displayed these components in a Django app using server_document("url to the bokeh app") in the view. I managed to display the figure and the dropdown in the html through {{ script | safe }}, but I would like to split the dropdown menu from the graph for styling purposes. I tried {{ embed(roots.graph) }} but Django doesn't allow this. How do I split the different components, so I can display them separately?? Maybe process the script returned by server_document() in the view?? Many thanks in advance! Django View: def BokehView(request): context = dict() # server_document connects to bokeh server and returns a <script> tag with the components context['script'] = server_document("http://localhost:5006/visualization") return render(request,'map.html',context) HTML: <div class="container-fluid"> {{ script | safe }} </div> -
Django/PyCharm cannot open pickle file
I am using Django 3.1.2 Python 3.8 and PyCharm Professional on Ubuntu. I am at: djangoProject/djangoApp/views.py something.pickle is in the same directory I am trying to read it with "open('something.pickle', 'rb')" Response - no such file or directory. I am trying the same approach through the terminal - it reads it. Is it something with Django or PyCharm Professional?> Thanks, guys! Cheers -
Own method in CreateView
I want to use my own method, which will return JsonResponse, but this method isn't called in this View by default. So maybe i need to rewrite another method or? views.py: class CreatePostJS(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('post_message', 'post_image') model = models.Post select_related = ('user',) template_name = 'posts/post_list.html' template_name = 'posts/post_form.html' response_data = {} response_data['text'] = model.post_message response_data['posted'] = model.posted_at response_data['user'] = model.user def create_post(request): if request.method == 'POST': return JsonResponse(serializers.serialize('json', response_data), safe = False) def form_valid(self, form): self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
Django template for many to many relationship with additional information
in my model i have services which has a many to many relation with articles plus the extra value amount where i store how many of the article instances are attributed to the services. My question regards the template: has anyone seen some sort of form that can show such a relationship or might even dedicated to such a relationship? I'm also open to suggestions on how to represent such a relationship? Currently i just used a MultiSelect Field widget where I can choose which articles to pass to the service and set the default amount to 1. I would have to go to the admin panel, and edit the amounts there which is not that cool. -
Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/']
I am a novice in Dejango and I want to have a shopping cart, but whatever I do, this error will not be fixed. and give me following eror. please help me. Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P[\w-]+)/'] cart model.py class Cart (models.Model): products=models.ManyToManyField("seabookapp.Book",null=True,blank=True) total=models.IntegerField( default=0) timestamp=models.DateTimeField(auto_now_add=True,auto_now=False) updated=models.DateTimeField(auto_now_add=False,auto_now=True) active=models.BooleanField(default=True) def __unicode__(self): return "Cart id : %s"%(self.id) book model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE) Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE) slug=models.SlugField(unique=True) GenerName=models.ForeignKey('category',on_delete=models.CASCADE) Price= models.IntegerField(null='true',blank='true') Discount= models.IntegerField(null='true',blank='true') AfterDiscount= models.IntegerField(null='true',blank='true') veiw.py def show_Book(request,BookID): template_name = 'showBook.html' showBook=get_object_or_404(Book,BookID=BookID) commentss = showBook.comments.filter(active=True) comments = showBook.comments.filter(active=True).order_by('-Created_on')[0:4] new_comment = None name = None book =None is_favorite=False if showBook.favorit.filter(id=request.user.id).exists(): is_favorite=True # Comment posted if request.method == 'POST': comment_form = BookCommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = comments # Save the comment to the database comment_form.instance.name = name comment_form.instance.book = request.book new_comment.save() else: comment_form = BookCommentForm() return render (request , 'showBook.html', { 'showBook':showBook , 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'commentss':commentss, 'book':book, 'is_favorite':is_favorite, }) def view (request): cart=Cart.objects.all()[0] products=Book.objects.all() context={"cart":cart,'products':products} template="view.html" return render (request,template, context) def update_cart(request,slug): cart=Cart.objects.all()[0] try: product=Book.objects.get(slug=slug) except Book.DoesNotExist: pass except: pass if … -
Password: "This field may not be blank." Error with React, ant design and django
Hi I just started learning react and decided to use ant design (version 3), so I created an API (Django Rest Framework) and I got it up an running, my login and sign up page was working fine, so I decided to upgrade ANT Design to Version 4, I had to read the documentation because somethings changed and managed to get it looking go but now when I fill the login form to submit, I get "Request failed with status code 400"... then checked the network and i see a response: {"password":["This field may not be blank."]} I tried to login from the API and it works perfectly, but keeps showing Request failed with 404 when i try to use the form. this is the Form.Js class LoginForm extends React.Component { state = { username: "", password: "" }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; onFinish = values => { console.log(values); // values.preventDefault(); const { username, password } = this.state; this.props.login(username, password); }; render() { const { error, loading, token } = this.props; const { username, password } = this.state; if (token) { return <Redirect to="/" />; } return ( <Layout> <Layout> <Layout style={{ padding: '0 … -
How to receive get parameter in viewset in django restframe work?
For the part of developing an API using restframe work and DJango, I need to receive few parameters through get method in 'list' function of my Viewset. In client side they are sending data as query prams, I somehow managed to get the data using 'request.query_params.get()' but received data is text format instead of bool, I had to convert this to boolean . see the code how I did this if 'status' in (request.query_params): """receiving input argument is string need to convert that to boolean for further processing""" input_status=(request.query_params.get('status', None)=='true') is there any better way to getting data without losing datatype. is it possible to receive 'bool' or 'int' values directly in get parameter? My model and view set classes are given below class ModuleType(models.Model): """ This module type class used to represent each module of the application. It is inherited from django content type which holds the complete model informations """ #this active field is true this module will be active on our user controller content_type = models.OneToOneField( ContentType, on_delete=models.CASCADE, related_name='status', null=True ) active=models.BooleanField(default=False) class Meta: db_table = 'module_types' My Viewset class ContentTypeViewSet(viewsets.ModelViewSet): """ This api deals all operations related with module management You will have `list`, `create`, `retrieve`, … -
Can i install specific sub package (logistic regression) from python package such as sklearn
I am developing a Django app, where I need TfidfVectorizer and LogisticRegression only. But I have to install the whole scikit-learn for this purpose. This take space and I want to make the app as light as possible. So is there a way to install TfidfVectorizer and LogisticRegression only) -
Save method conflict when using Django Admin feature
My model uses custom save method to add my own "primary key": class Z(models.Model): author = models.ForeignKey(K, on_delete=models.PROTECT) my_id = models.CharField(max_length=60, unique=True) ... def save(self, *args, **kwargs): counter = Z.objects.filter(author=self.author).count() + 1 self.my_id = str(counter) + "/" + self.author.name super(Z, self).save(*args, **kwargs) But when I'm trying to edit anything in Django Admin panel it still uses my save method- which causes a lot of problems (when I'm editing multiple items it gives it the same ID, etc). Is there any way that I can force Admin panel editing to not use my save method? -
Run one off commands via SSH in Elastic Beanstalk and Django
I'm trying to solve this problem for a while now and can't seem to solve it. There are various scenarios in which I would want to be able to run a custom command on Elastic beanstalk. I want to use this command after the server started (.ebextensions does not work here). E. g. python manage.py send_pending_emails_via_cronjob The problem here is that I'm not able to run any commands without the environment variables set. My app needs e. g. DJANGO_SECRET_KEY, RDS_DB_NAME... Out of the box, these variables are only available when the server starts up. They are not available when I enter the EC2 instance via eb ssh - they are also not present in the virtual python environment on the instance. I tried: finding the file that contains the variables at /opt/elasticbeanstalk/env to source it. But read access to the file is restricted to the root user (I haven't yet figured out how to access the server as root) - however, this feels very complicated and like an unintuitive thing to do. I suspect there to be a more elegant solution. Did someone solve this already?