Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Managemengt Command Logging Buffers Messages
When I issue log statements from a Django management command, they always get joined into one big log statement for the whole command execution. Instead, I want them to be issued individually line by line like usual application logs. That way log aggregation can pick them up properly and not as one extremely large message. LOGGING_ROOT_HANDLERS = ['prometheus', 'console'] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'json': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', 'fmt': '%(levelname)s %(levelno)s %(pathname)s %(funcName)s %(asctime)s %(message)s', }, }, 'filters': { 'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue'}, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'json', }, 'prometheus': { 'level': 'WARNING', 'class': 'app.logging_handlers.PrometheusHandler', }, }, 'loggers': { '': {'level': 'INFO', 'handlers': LOGGING_ROOT_HANDLERS}, 'myapp.management.commands': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'WARNING', 'propagate': False, }, 'django.request': { 'handlers': LOGGING_ROOT_HANDLERS.copy(), 'level': 'INFO', 'propagate': False, }, }, } import logging from django.core.management.base import BaseCommand logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logger.info("Message %s", "1") logger.info("Message %s", "2") Current output: {"levelname": "INFO", "levelno": 20, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,497", "message": ""} {"levelname": "WARNING", "levelno": 30, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,498", "message": "{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 … -
How to compile single python scripts (not to exe)?
I know there is a lot of debate within this topic. I made some research, I looked into some of the questions here, but none was exactly it. I'm developing my app in Django, using Python 3.7 and I'm not looking to convert my app into a single .exe file, actually it wouldn't be reasonable to do so, if even possible. However, I have seen some apps developed in javascript that use bytenode to compile code to .jsc Is there such a thing for python? I know there is .pyc, but for all I know those are just runtime compiled files, not actually a bytecode precompiled script. I wanted to protect the source code on some files that can compromise the security of the app. After all, deploying my app means deploying a fully fledged python installation with a web port open and an app that works on it. What do you think, is there a way to do it, does it even make sense to you? Thank you -
Django urlpatterns when a category is included into URL
Django 3.0.6 urlpatterns = [ path('', HomeView.as_view(), name='home'), path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons. path('image/', include(('image.urls', 'image'), namespace="image")), path('polls/', include(('polls.urls', 'polls'), namespace="polls")), path('applications/', include(('applications.urls', 'applications'), namespace="applications")), ] def _get_categories_url_pattern(): """ Organize urls with posts categories. URL format: <category>/<post_slug> Example: linux/how_to_install_ubuntu/ """ categories = Category.objects.all().values_list("slug", flat=True) for category in categories: urlpatterns.append(path('{}/'.format(category), include('post.urls'))) urlpatterns.append(path('draft/{}/'.format(category), include('post.urls'))) _get_categories_url_pattern() Please, concentrate your attention on how categories in urls are handled. Problems with this code: When a new category is added in the admin site, Django project has to be relaunched (at least with the built in dev server). When last time I did python manage.py makemigrations it blew up. I had to comment out anything having anything to do with _get_categories_url_pattern. Then it made migrations. Now I can't reproduce this error anymore. But there seems to be some danger in this code. Could you help me understand how to refactor this code for it to work at least without restarting the dev server when a new category is added. -
function in views not called while sending POST request to django
I am beginner to Django and I am working to store input form data to database with using HTML forms.But whenever the request generated, the register function isn't called. My login form and registration form are in a single web page.My webpage consists a scroll down animation effect on opening of registration form. Here is my code : Login.html (with Javascript(jQuery)) <strike> <!DOCTYPE html> <html lang="en"> <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.7/holder.min.js" rel = "stylesheet" type="text/css"> <link rel="stylesheet" href="jQuery/slick-1.8.1/slick/slick.css" type="text/css"> <link rel="stylesheet" href="jQuery/slick-1.8.1/slick/slick-theme.css" type="text/css"> <link type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!--<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>--> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Login | Register</title> </head> <body> <script> $(document).ready(function(){ $('#lgcollapse').collapse('show'); $('#reg-uncollapse').hide(); $('#register-form-opener').click(function(){ $('#lgcollapse').slideUp(500); setTimeout(function(){ $('#reg-uncollapse').fadeIn(1000); $('#lgcollapse').hide(); },800); }); $('#login-opener').click(function(){ $('#lgcollapse').slideDown(500,function(){ $('#reg-uncollapse').hide(); }); /*setTimeout(function(){ $('#lgcollapse').fadeIn(1000); },800);*/ }); }); </script> <style> .nmp{ background: #ffffff; transition: 1s ease; box-shadow: 5px 5px 10px #bfc2c4, -5px -5px 10px #ffffff; } .nmp:hover{ box-shadow: none; } </style> <body style="background-color: #e9ecef!important;"> <div class = "row my-5" id="lgcollapse" style="background-color: #ffffff!important;box-shadow: inset 5px 5px 18px -2px #000000;margin-right: 0px!important;"> <div class = "container"> <div class = "row"> <div class = "col-md-12"> <div class = "card my-5" style="background-color: #e9ecef!important;"> … -
Translation fails in django-simple-menu
I'm using django-simple-menu in my header navigation and the application has multiple languages. When switching language, the language is stored within the user preferences and everything is translated correctly except the django-simple-menu. When I stop the application and restart, the translation is also applied to simple-menu. I don't know which part of my code to publish here in order to solve the problem, but any help will be appreciated. -
Create directory as service account not the computer
I am struggling with an issue that I do not know how to solve. I am trying to make a directory with python as a different user/under the different credentials. I will explain why. Since I am not able to use internal storage on server/virtual machine but I can use a mapped drive which is on a different machine and make directory there. This will not be an issue if I will make the directory but since I am using the Django and web view the command which is started will be executed with permissions of computer which is not allowed due to the security access the mapped drive and make directory/folder. Is there any option on how to access the mapped drive with different credentials and create the directory/folder? Keep in mind that I am executing the scrip through the website so everything executed is as computer/VM. Thanks -
How to fix the " has no attribute 'objects' " error in django?
I have an attribute error with the line block = Block.objects.filter(chain=chain) in my views.py. I have two models, Chain and Block, as shown here, in my models.py. class Chain(models.Model): """ This model class enables us to save each blockchain separately per user in the database. """ name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) year = models.CharField(max_length=10, default="20XX") sem = models.CharField(max_length=30, default="Default Semester") code = models.CharField(max_length=10, default="SUB-CODE") slot = models.CharField(max_length=10, default="EX+EX") last_updated = models.DateTimeField(auto_now=True) objects = models.Manager() class Block(models.Model): """ This model class enables us to save each block in the database. """ index = models.IntegerField() chain = models.ForeignKey(Chain, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) data = models.TextField() prev_hash = models.CharField(max_length=500) block_hash = models.CharField(max_length=500) objects = models.Manager() This is the function in my views.py. @login_required(login_url='/') def course_view(request, chain_id): try: chain = Chain.objects.get(pk=chain_id) block = Block.objects.filter(chain=chain) except ObjectDoesNotExist: return render(request, 'create_block.html', {'announcements':"You have no attendances marked in this course. Mark attendance for a class to view it."}) return render(request, 'course_view.html', {'blocks':blocks}) What I'm trying to do basically is have two models, where each "Chain" object has multiple "Block" objects and list them in one page. I'm unable to do so because the view function consistently shows AttributeError at /create_block/1 type object 'Block' has no … -
class import : ImproperlyConfigured: The SECRET_KEY setting must not be empty
I have this error whenever I try to import model class from another app. in a helper file helper.py. Project structure: project_dir - main_project_dir - helpers - helper.py - malakar_app - models.py <- contains RunDate model class Now in helper.py: from django.conf import settings from project.models import RunDate def get_run_date_id_from_rundate_field(ac_id, run_date): try: run_date = RunDate.object.get(file_run_date=run_date, client_id=ac_id) return run_date.id except RunDate.DoesNotExist: return None I read something similar about circular dependency but have no idea how to proceed. How can I import the model class in the helper file? -
int() argument must be a string, a bytes-like object or a number, not 'Xray'
I'm trying to create a db entry from two nested serialisers: Here are the Serializers: class BboxSerializer(serializers.ModelSerializer): xray = serializers.IntegerField(required=False) class Meta: model = Bbox fields = ('id', 'xmin', 'ymin', 'xmax', 'ymax', 'xray') class XrayBboxSerializer(serializers.ModelSerializer): bboxes = BboxSerializer(many=True) class Meta: model = Xray fields = ('id', 'bboxes', 'picture', 'pic_name') def create(self, validated_data): bboxes = validated_data.pop('bboxes') xray = Xray.objects.create(**validated_data) for bbox in bboxes: Bbox.objects.create( xray=xray) return xray Here are the models: class Xray(models.Model): picture = models.ImageField(upload_to='xray', blank=True) pic_name = models.CharField(max_length=50, unique=True) expert_check = models.BooleanField(default=0) def __str__(self): return self.pic_name class Bbox(models.Model): xray = models.ForeignKey(Xray, related_name = "bboxes", on_delete=models.CASCADE) xmin = models.FloatField(default=0) ymin = models.FloatField(default=0) xmax = models.FloatField(default=100) ymax = models.FloatField(default=100) def __str__(self): return self.xray.pic_name now when I send this json as request I get this error: int() argument must be a string, a bytes-like object or a number, not 'Xray' My Xray obj gets created but not the Bbox obj for some reason. -
Django: Sort given results of method on model
In Django, how can I sort the results of a method on my model? class Flashcard(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) deck = models.ForeignKey(Deck, on_delete=models.CASCADE) question = models.TextField() answer = models.TextField() difficulty = models.FloatField(default=2.5) objects = FlashcardManager() def __str__(self): return self.question def number_of_questions(self): return self.question.count(deck=deck.id) def get_avg_diff_user(self): avg_diff = Flashcard.objects.filter(owner=self).aggregate(Avg('difficulty'))['difficulty__avg'] return avg_diff So with get_avg_diff_user, I get each user's average difficulty rating. Which I can then use in my leaderboard template as follows: <ol> {% for user in leaderboard_list %} <li>{{user.username}}: {{user.profile.avg_diff_user|floatformat:2}}</li> {% endfor %} </ol> But it's not sorted - how can I sort by avg_diff_user? I've read many similar questions on SO, but to no avail. I've tried a different method on my model: def avg_diff_sorted(self): avg_diff_sorted = Flashcard.objects.all().annotate(get_avg_diff_user=Avg(Flashcard('difficulty'))['difficulty__avg'].order_by(get_avg_diff_user)) return avg_diff_sorted Which I don't think is right and unsurprisingly it didn't return any results in my template. I also tried the following, as suggested in https://stackoverflow.com/a/930894/13290801, which didn't work for me: def avg_diff_sorted(self): avg_diff_sorted = sorted(Flashcard.objects.all(), key = lambda p: p.avg_diff) return avg_diff_sorted -
Unhandled rejection error from fetch in Javascript
I am trying to fetch some JSON file from one Rest API, which can be accessed via http://0.0.0.0:8888/model/?sentence=querys. The response essentially looks like {"out": "Test string"} Now I am starting a Django application, which resides on localhost:8000. I have a Javascript inside which is supposed to fetch the JSON and the relevant code snippet looks as follows: fetch("http://0.0.0.0:8888/model/?sentence=querys") .then(response => response.json()) .then(result => { let responseText = result.out; console.log(responseText); }); Now when I try to fetch the JSON the following error shows up: ERROR Got error: context: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 details: unhandledrejection, Failed to fetch, TypeError: Failed to fetch However, when I change the Url to something from the Github API, everything works as desired. Do you know how to make it work here as well? -
asyncio task hangs midway
So i am building a scrapper which takes a bunch of urls, a success function that will run via celery if that url was fetched successfully and if any error occurs just return and collect the bunch of urls that were not successfull and send them to be scheduled again to a celery function. Below is the code. class AsyncRequest: def __init__(self, urls_batch, callback, task_name, method, finish_callback=None, *args, **kwargs): """ :param urls_batch: List of urls to fetch in asycn :param callback: Callback that process a successfull response """ self.tasks = [] self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } self.urls_batch = urls_batch self.task_name = task_name self.callback = callback self.finish_callback = finish_callback self.args = args self.kwargs = kwargs self.proxy = kwargs["proxy"] if "proxy" in kwargs.keys() else None self.finish_callback = finish_callback self.successfull_urls = [] self.verify_ssl = kwargs["verify_ssl"] if "verify_ssl" in kwargs.keys() else True async def fetch(self, session, url, time_out=15, retry_limit=3, *args, **kwargs): try: for i in range(retry_limit): try: async with session.request(self.method, url, headers=self.headers, timeout=ClientTimeout(total=None, sock_connect=time_out, sock_read=time_out), verify_ssl=self.verify_ssl, proxy=self.proxy) as response: if response.status in [200, 203]: result = await response.text() self.successfull_urls.append(url) self.callback.delay(result, url=url, *self.args, **self.kwargs) return else: logger.error( "{} ERROR===============================================>".format(self.task_name)) logger.error("status: {}".format(response.status)) except … -
How to replace the DefaultRouter functionality for function based views
I like the way DefaultRouter in DRF lists all the endpoints. However I dislike the use of ViewSets and prefer using function based views. I can't seem to find a way to list all my function based views in api/v1 any easy way. Seems like you can only use DefaultRouter with ViewSets Is there any quick way and neat way to list all endpoints the same way DefaultRouter does with function based views? -
Read-the-Docs Local Instance: Docs are built successfully but cannot be found (404)
I have successfully installed an instance of Read-the-Docs locally and integrated with the public instance of Gitlab. I have successfully imported and built three projects (even a private one after some minor code alterations, though it is not normally supported). One of these projects is the default template project that RTD suggests for testing. I can view the docs in the machine where the RTD instance is installed. However, when I press the green "View Docs" button a 404 status code occurs. Supposedly, the docs should be under /docs/template/en/latest. As you can see there is no docs prefix in the available URLs: My assumption was that the endpoints regarding the docs are updated dynamically and the Django application reloads, yet I have been searching the code and I have not found anything to support this assumption. My question is, if anyone has ever come upon this issue and how / if it was resolved? -
How to store response of a Django filter in a variable which can be used in a Django template?
Below is my custom filter related code: @register.filter(name="get_quantity") def quantity(item, user_id): try: id = int(user_id) order_item = models.OrderItem.objects.filter(item=item,user__id=id) if order_item.exists(): return order_item[0].quantity except: return False Now I want to use the returned value (quantity) of the filter in my template file: template.html: {% if item|get_quantity:user_id == False %} <input class="text-center qty" value="0" style="width:30px; display: none;"></input> {% else %} <input class="text-center qty" value="{{ item|get_quantity:user_id }}" style="width:30px;"></input> {% endif %} So, I want to store the returned value of the get_quantity filter in some variable in the if condition so I can use it in the else part of code instead of calling the custom filter again in order to reduce complexity. Can someone guide me how to achieve this? -
Run django development webserver when machine is rebooted or turned on
Is there any way we can run the development webserver through may be cronjob or some service provided by django or any libraries? I am in need of running it when laptop or EC2 server reboots. I am open to nginx as solution, but the default development server is what I need at the moment. -
DRF Serializer Update Says Reverse Foreign Key Field is Null even though it has data
I am trying to update a model, but the serializer is saying that my reverse foreign key field is null even though it has data (and it returns the data when I run a get request). Models: Match Team Model class MatchTeam(models.Model): captain = models.ForeignKey( User, on_delete=models.CASCADE, related_name='match_teams_captained' ) teammates = models.ManyToManyField( User, blank=True, related_name='match_teammates' ) match = models.ForeignKey( MatchModel, on_delete=models.CASCADE, related_name='teams' ) Match Model class MatchModel(models.Model): TYPES = ( (1, "Ex1"), (2, "Ex2"), (3, "Ex3"), (4, "Ex4"), ) is_available = models.BooleanField() is_started = models.BooleanField() is_finished = models.BooleanField() is_deleted = models.BooleanField() type = models.IntegerField(choices=TYPES) team_size = models. PositiveSmallIntegerField() num_teams = models. PositiveSmallIntegerField() created_at = models.DateTimeField(editable=False) # Foreign Keys host = models.ForeignKey( User, related_name='matches_hosted', on_delete=models.CASCADE, ) winning_team = models.OneToOneField( 'MatchTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='+' ) def save(self, *args, **kwargs): if not self.id: self.created_at = timezone.now() return super(MatchModel, self).save(*args, **kwargs) I'm trying to update the MatchTeam model in my serializer, but when I get my MatchModel by pk, it says that 'teams' is null even though it has data when I check the db or run a get request. view.py def put(self, request, pk, format=None): match = self.get_object(pk) serializer = MatchModelSerializer(match, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) … -
JqueyUI autocomplete suggestions showing up outside input field
I have set up an autocomplete form with JqueryUi in a Django project. Autocomplete is working fine. Problem is, suggestions are not displayed under my form but on the right side of the screen. I need the suggestion to appear just under my search field as it should and to display only the 10 first products that matches my search. My HTML: <div class="ui-widget"> <input id="prod" class="form-control mr-sm-2" type="text" name="query" placeholder=""> </div> My AJAX: $(function() { $("#prod").autocomplete({ source: "/finder/search_auto", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); });$( "#prod" ).autocomplete({ position: { my : "right top", at: "right bottom" } }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } My views.py: $(function() { $("#prod").autocomplete({ source: "/finder/search_auto", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); });$( "#prod" ).autocomplete({ position: { my : "right top", at: "right bottom" } }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } -
Is there a way to convert video with open-cv in django file-field?
I'm working on django project and I met a problem with handling videos. In the project, if user upload an image then server handles it with OpenCV and save it. This is how I did. _, out_img = cv2.imencode('.jpg', np.asarray(result_image)).tobytes() out_file = ContentFile(out_img) out_path = '/path/to/save' filemodel.file_field.save(out_path, out_file) filemodel.save() I did try with video, but it wasn't easy. Is there anyone who did the same process? Thanks. -
Deploy Django App serverless on GCP cloud functions
I have a Django webapp (a forum) which have few screens like login, profile, posts, replies, etc.. A regular deployment on dedicated instances (with scalability, performance in mind) seems to be expensive. I have come across serverless deployment of Django apps on AWS Lambda. Here is one such example on AWS. But I couldn't find anything similar on GCP. Is a similar thing possible using GCP cloud functions (GCF)? In other words, can GCF be used to deploy any of the following: a web app which can serve dynamic pages a microservice with multiple rest endpoints -
Dynamically add new ckeditor on page - Django
I am trying to dynamically add a new CKEditor after clicking the button since I want to use dynamic formset. I successfully added the CKEditor but I am not able to write in it. Once I for example try to make something bold, cause I can click on the button in the new one, the change is done only in the first CKEditor which is not a clone. And I do not know, where could be the problem. Can someone help me or show me how to handle CKEditors in dynamic forms in Django? Here is my Javascript code which I use for adding new CKEditor and updating the values. {% block custom_js %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total-1) + '-', '-' + (total) + '-'); var id = 'id_' + name; … -
Login with single role if user have multiple roles? [closed]
A user is assigned multiple roles.Suppose, If the user is a student he will have access to student dashboard and if the user is a teacher he will have his own dashboard. The problem is when the user have both roles and he logins both of the dashboards are loading. I want the user to see only one dashboard when he logins. And he will be able to switch between the roles only after he logins. class A(APIView): def get(self, request): if user.student: //some code class B(APIView): def get(self, request): if user.teacher: //some code -
Session ID getting changed on redirect django & docker
I have a Django and react project. I'm using Nginx and Gunicorn to run the application. To run all these I'm using docker. So in a Django view, I'm setting a session variable and then redirecting to another view after this. So in that redirected view when I'm trying to access the session variable it's not getting fetched. I'm using the default session to store the session in the django_session table. I checked there as well but I'm not sure why it's not able to fetch the session. The wired part is here that in firefox it's working but not in chrome. But in Firefox I'm getting the below error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1/api/user/user-info/. (Reason: CORS request did not succeed). The same project is working in my local (without docker) by running the django's runserver command. Below is how my docker-compose.test.yml file looks like version: "3.8" services: db: image: postgres:12.3 ports: - "5432:5432" env_file: - ./env/.env.dev.db volumes: - postgres_data:/var/lib/postgresql/data/ networks: - backend app: build: context: . dockerfile: ./docker/test-env/app-docker/Dockerfile args: - REACT_APP_API_URL=http://127.0.0.1:8000 volumes: - app_static_files:/app/static - favicon:/app/front_end/app-frontend/build/favicon.ico command: > /bin/sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn … -
Django - Pass two Models into one view, and display both models
I'm trying to pass two models into a create view, where i am trying to get the the primary key from the URL to retrieve the details from a food truck model so it can be displayed in the page, and where a user can write a review about food truck. Also, I'd like a list of the reviews to be displayed on the page. views.py class TruckReviewView(CreateView): model = Review template_name = 'truckReviews/detail.html' fields = ['speedOfService', 'qualityAndTaste', 'valueForMoney', 'comment'] def get_queryset(self): self.pk = self.kwargs['pk'] queryset = super(TruckReviewView, self).get_queryset() return queryset def get_context_data(self, **kwargs): context = super(TruckReviewView, self).get_context_data(**kwargs) context['truck'] = FoodTrucks.objects.get(truckID=get_queryset()) context['reviews'] = Review.objects.get(truckID=get_queryset()) return context urls.py urlpatterns = [ path('', TruckListView.as_view(), name='reviews-home'), path('truck/<int:pk>/', TruckReviewView.as_view(), name='truck-detail'), path('about/', About.as_view(), name='reviews-about'), ] models.py class FoodTrucks(models.Model): truckID = models.IntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=25) category = models.CharField(max_length=20) bio = models.TextField() avatarSRC = models.TextField(default=None) avatarALT = models.CharField(max_length=20, default=None) avatarTitle = models.CharField(max_length=20, default=None) coverPhotoSRC = models.TextField(default=None) coverPhotoALT = models.CharField(max_length=20, default=None) coverPhotoTitle = models.CharField(max_length=20, default=None) website = models.TextField(default=None) facebook = models.CharField(max_length=100, default=None) instagram = models.CharField(max_length=30, default=None) twitter = models.CharField(max_length=15, default=None) class Review(models.Model): reviewID = models.AutoField(primary_key=True, unique=True, serialize=False, null=False) truckID = models.ForeignKey(FoodTrucks, on_delete=models.CASCADE) userID = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) speedOfService = models.IntegerField() qualityAndTaste = models.IntegerField() valueForMoney … -
How to search in a JSONField for a key with spaces in Django with Postgres?
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following - { "name": "John", "email": "johndoe@foo.bar", "last name": "Doe" } I need to write a queries of the following form - self.objects.filter(data__name="John") How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done. I've not real control over the data in the JSONField. So, I can't really change the name of the key.