Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to return a global variable for access in different functions
I have a function that returns a render of a html (function 1). I want to change a global variable using formula 1 and the access this edited global variable in another formula (formula 2). In order to do this I think I have to return the global variable in formula 1, so the edited version can be accessed in formula 2. My problem is that function 1 already returns a render request. global_variable = 0 def function1(request): global_variable = 10 return render(request, 'index.html', {}) def function2(request): print(global_variable) excel = open(path, 'rb') response = HttpResponse(excel.read(), content_type="app/vnd.openxmlformat.spreadsheetml.sheet") response['Content-Disposition'] = 'attachment; filename=' + os.path.basename("Excel.xlsx") return response I have tried to just add in the global variable at the end of the function like so: def function1(request): global_variable = 10 return render(request, 'index.html', {}), global_variable except it causes the error 'tuple' object has no attribute 'get' -
How to increase response time in Django rest framework with Celery?
I am trying to increase the ability of the Django rest framework to handle more requests. I wrapped my Django rest framework with Celery. Any suggestions on how to further increase the handling of the number of RPS? Here is my code from celery import current_app from rest_framework.decorators import api_view class SomeViewSet(viewsets.ModelViewSet): queryset = SomeModel.objects.all() serializer_class = SomeSerializer @api_view(('POST',)) def some_post_request(request): serializer = serializer_class(data=request.data) if serializer.is_valid(): address = serializer.validated_data['somedata'] file_path = "usr/" with open(file_path, 'wb+') as fp: for chunk in address: fp.write(chunk) result = some_function.delay(file_path, address) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) @api_view(('GET',)) def some_get_request(request, task_id): task = current_app.AsyncResult(task_id) context = {'task_status': task.status, 'task_id': task.id} if task.status == 'PENDING': return Response({**context}, status=status.HTTP_200_OK) else: response_data = task.get() print(response_data) return Response({**context, **response_data}, status=status.HTTP_201_CREATED) I would appreciate complete answers on how to further improve the performance of the celery and Django rest framework by either modifying the above code or suggesting libraries you have used. For example, I tried using the following and it dropped my RPS from 800 to 450. from asgiref.sync import sync_to_async @sync_to_async @api_view(('POST',)) def some_post_request(request): -
A simple database connection failure in an Angular-Django-MongoDB app
I am just trying to establish a simple database connectionin an Angular-Django-MongoDB application, with a real MongoDB database called myDB that conatins a cluster called consumers. I know my connection string is mongodb+srv://MyUser2021:TestMe@cluster0.j9jz1.mongodb.net/test Just to see if I can get it all to communicate, I have written the following in views.py: @csrf_exempt def consumers(): print("consumers") with its correspondence in urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), # http://localhost:8000/admin/ url(r'^consumers/', consumers), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] In my Angular app, I have written a simple service script for it: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Post } from '../models/post.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { consumersMongodbApiUrl = "http://localhost:8000/consumers"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions); } } When I call some function somewhere else that invokes the addConsumerMongodb method in this service class, I get POST http://localhost:8000/consumers 403 (Forbidden) in my webpage dev console. I have looked at lots and lots of posts on this particular error message, but nothing has helped me so far... Could it be that the consumersMongodbApiUrl should … -
When running the command to make migrations it throws a GenericForeignKey error in django
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.auth.models import User class LikedItems(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_Type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() This is the model that I've created and when I run the following command it give an error. python manage.py makemigrations ERROR: ERRORS: likes.LikedItems.content_object: (contenttypes.E002) The GenericForeignKey content type ref erences the nonexistent field 'LikedItems.content_type'. -
Filling a MultipleWidget from database
I'm trying to get a list of weekday options into a PositiveSmallIntegerField in Django and back to the form. I found a very similar question from the year 2011 which covers the process of having a MultiSelect widget with weekday options, Representing a multi-select field for weekdays in a Django model. Also, there has been an additional question regarding the reverse process, Custo widget based on CheckBoxMultipleSelect for weekdays in Django by user gabn88, which sadly has been deleted since. I tried the approach with the BitChoices class in the first post, and the class itself seems to work. However, I fail to put the selection back to something I can fill the form with. At least that's what I think judging from the error message on my view: Select a valid choice. ['2', '16', '128'] is not one of the available choices. Can anybody help me out, please? -
Populate dropdown using data from firebase database and Django?
Iam creating a web app that displays registered user in a dropdown menu,i have a firebase databse that constain the details but i dont know how to populate dropdown menu using the data,iam new to django and web devolopment.I have seen many article on populating the dropdown from local databse but i cannot find any article which uses data from firebase,So please help. url.py from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), ] view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request,'vl.html') Thanks In Advance! -
Django redirect() doesn't redirect but rather refreshes the same page
view.py @login_required(login_url='index', redirect_field_name=None) def new_character(request): if request.method == 'POST': character_form = CharacterForm(request.POST) if character_form.is_valid(): new_character = character_form.save(commit=False) new_character.creator = request.user new_character.save() # If new_character has a primary key (pk) then it # means it was saved to the database. if new_character.pk: # TODO: For some reason this doesn't work. redirect('list_characters') else: character_form = CharacterForm() return render(request, 'characters/new-character.html', {'character_form': character_form}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.list_characters, name='list_characters'), path('new/', views.new_character, name='new_character'), ] I checked and new_character.pk is coerced to True. However, the redirect doesn't happen and instead the same page is simply refreshed. -
how to change merging two queries to josnResponse - django
i'm trying to merge two queries , i did this models.py class MyDateTimes(models.Model): deadline = models.DateTimeField() class ModelA(models.Model): title = models.CharField(max_length=30) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class ModelB(models.Model): post = models.ForeignKey(MyPosts,on_delete=models.PROTECT) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class MyPosts(models.Model): article = models.CharField(max_length=30) i've to merge ModelA with ModelB , here is what i did from itertools import chain modelA = ModelA.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) modelB = ModelB.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) my_query = list(chain(modelA, modelB)) my_listA = [] my_listB = [] i have to return json response of my_query for i in modelA: item={ 'title':i.title, 'dead_line':i.deadline.deadline, } my_listA.append(item) for i in modelB: item={ 'title':i.post.article, 'dead_line':i.deadline.deadline, } my_listB.append(item) note : because i need to use ForeignKey and OneToOne data thats i couldn't use serialiser function i want to do it into one list to return JsonResponse , in order to callable into ajax call ! thank you in advance , please let me know the most efficient way to achieve that -
How to add custom page for 403 error django
Question as in title. How to set custom page for an error in django. I tried using just in templates new file like '403.html' but it did not work. I tried also this: def handler404(request, exception, template_name="404.html"): response = render_to_response(template_name) response.status_code = 404 return response but I can not import render_to_response -
How to disable "?next=" parameter for Django Admin to avoid Page Enumeration Attacks?
I'd like to disable the ?next=... parameter that Django Admin automatically sets if you try to access a page that's protected by the admin panel. I haven't been able to find a solution to do this so far. Does anyone know how to achieve this? The reason why I want to do this is to avoid page enumeration attacks. -
Django How to refactor duplicate method
I'm using django 2.2 and in my view I have two functions that do the same thing but only one element changes. I would like to try to improve my code so that I don't repeat the same thing more times, basically do what the vm_schedule_power_on_vm function does and vm_schedule_power_off_vm into one function. The only thing that will change is the call of vmware_poweron in the vm_schedule_power_on_vm function and vmware_poweroff in the vm_schedule_power_off_vm function. path('vm/schedule/<int:pk>/powered_on/', vm.vm_schedule_power_on_vm, name='vm_schedule_power_on_vm'), path('vm/schedule/<int:pk>/powered_off/', vm.vm_schedule_power_off_vm, name='vm_schedule_power_off_vm') def vm_schedule_power_on_vm(request, pk): sch = VmSchedule.objects.get(pk=pk) mylistvm, mylist = list(), list() mydate = time.strftime("%d/%m/%Y") for i in sch.vms.all(): if i.lock: return 'locked' # here the order has importance because # I try to have the start time and at the end the end time. mylist.append(mydate) mylist.append(time.strftime("%H:%M:%S")) mylist.append(i.name) mylist.append(i.vmware.hostname) # only this line changes each time mylist.append(vmware_poweron(i)) mylist.append(time.strftime("%H:%M:%S")) mylist.append(sch.schedule) mylistvm.append(mylist) mylist = list() vm_logs_export(mylistvm) return HttpResponse(json.dumps(mylistvm)) def vm_schedule_power_off_vm(request, pk): sch = VmSchedule.objects.get(pk=pk) mylistvm, mylist = list(), list() mydate = time.strftime("%d/%m/%Y") for i in sch.vms.all(): if i.lock: return 'locked' mylist.append(mydate) mylist.append(time.strftime("%H:%M:%S")) mylist.append(i.name) mylist.append(i.vmware.hostname) # only this line changes each time mylist.append(vmware_poweroff(i)) mylist.append(time.strftime("%H:%M:%S")) mylist.append(sch.schedule) mylistvm.append(mylist) mylist = list() vm_logs_export(mylistvm) return HttpResponse(json.dumps(mylistvm)) # Example result of vm_schedule_power_on_vm or vm_schedule_power_off_vm ['09/12/2021', '13:54:33', 'API1VTEST11', 'ste1vvcsa', '13:54:33', … -
WEASYPRINT M1 MAC MINI
I am running weasyprint but system cannot find the package: (env) andrestemmett@Andres-Mac-mini MicrocareERP % weasyprint --info Traceback (most recent call last): File "/Users/andrestemmett/Desktop/MicrocareERP/env/bin/weasyprint", line 5, in from weasyprint.__main__ import main File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/__init__.py", line 322, in from .css import preprocess_stylesheet # noqa isort:skip File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/css/__init__.py", line 27, in from . import computed_values, counters, media_queries File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/css/computed_values.py", line 16, in from ..text.ffi import ffi, pango, units_to_double File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/text/ffi.py", line 380, in gobject = _dlopen( File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/text/ffi.py", line 377, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': dlopen(gobject-2.0-0, 2): image not found. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' I have tried to change my symlinks to link to hombrew because i read that weasy print relies on dependencies pango libffi. However when I try that: sudo ln -s /opt/homebrew/opt/glib/lib/libgobject-2.0.0.dylib /usr/local/lib/gobject-2.0 sudo ln -s /opt/homebrew/opt/pango/lib/libpango-1.0.dylib /usr/local/lib/pango-1.0 sudo ln -s /opt/homebrew/opt/harfbuzz/lib/libharfbuzz.dylib /usr/local/lib/harfbuzz sudo ln -s /opt/homebrew/opt/fontconfig/lib/libfontconfig.1.dylib /usr/local/lib/fontconfig-1 sudo ln -s /opt/homebrew/opt/pango/lib/libpangoft2-1.0.dylib /usr/local/lib/pangoft2-1.0 Then i get this error: ln: /usr/local/lib/gobject-2.0: No such file or directory … -
How to get select value in flask?
I'm trying to get the value of select tag but it returns none, how can I get the value of it using flask? I tried request.form.get but still not working, It says the value is none. Here's the HTML of my select tag <select name="channels" id="channels" method="POST"> <option value="1">Channel 1</option> <option value="2">Channel 2</option> <option value="3">Channel 3</option> <option value="4">Channel 4</option> <option value="5">Channel 5</option> <option value="6">Channel 6</option> <option value="7">Channel 7</option> <option value="8">Channel 8</option> </select> Here's my flask code: def updatedecimal(): con = sqlite3.connect('/home/tim-rtc/Randomizer/tmonitor.db') con.row_factory = sqlite3.Row channel = request.form.get('channels') cur = con.cursor() cur.execute("""SELECT * FROM monitors where CHANNEL = ? ORDER BY id DESC limit 1""", (channel, )) rows = cur.fetchall() row1 = [row[1] for row in rows] row2 = [row[2] for row in rows] row3 = [row[3] for row in rows] return jsonify( row1 = row1, row2 = row2, row3 = row3) Newbie in flask here. Thank you! -
Why is a security issue Entry.objects.all ? Django
I'm using Checkmarx tool to scan my code for security issues. For getting all objects from database I used the following code entries = Entry.objects.all() But checkmarx raises an error for this and it consider this code as secord order sql injection. Can someone explain? -
Django import-export, only export one object with related objects
I have a form which enables a user to register on our website. Now I need to export all the data to excel, so I turned towards the import-export package. I have 3 models, Customer, Reference and Contact. The latter two both have a m2m with Customer. I also created Resources for these models. When I use Resource().export() at the end of my done() method in my form view, it exports all existing objects in the database, which is not what I want. I tried googling this and only got one result, which basically says I need to use before_export(), but I can't find anywhere in the docs how it actually works. I tried querying my customer manually like: customer = Customer.objects.filter(pk=customer.id) customer_data = CustomerResource().export(customer) which works fine but then I'm stuck with the related references and contacts: reference_data = ReferenceResource().export(customer.references) gives me an TypeError saying 'ManyRelatedManager' object is not iterable. Which makes sense because export() expects an queryset, but I'm not sure if it's possible getting it that way. Any help very appreciated! -
Angular-Django-MongoDB simple connection failure
I have set up an Angular-Django-MongoDB application, with a real MongoDB database with a cluster called consumers. I am just trying to establish a simple connection between the app and the database. I know my connection string is mongodb+srv://MyUser2021:TestMe@cluster0.j9jz1.mongodb.net/test Just to see if I can get it all to communicate, I have written the following in views.py: @csrf_exempt def consumers(): print("consumers") with its correspondence in urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), # http://localhost:8000/admin/ url(r'^consumers/', consumers), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] In my Angular app, I have written a simple service script for it: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Post } from '../models/post.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { consumersMongodbApiUrl = "http://localhost:8000/consumers"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions); } } When I call some function somewhere else that invokes the addConsumerMongodb method in this service class, I get POST http://localhost:8000/consumers 403 (Forbidden) in my webpage dev console. I have looked at lots and lots of posts on this particular error message, but nothing has helped me so far... Could … -
Questions with multiple choices database schema design
Let's say we want to create a quiz application, where a user can create a quiz with the following characteristics: Users can select questions for their quiz from a set of predefined questions. Each question can have multiple options (choices); 2, 3, 5, 6, 9, it doesn't matter. The questions and it's choices are added by the admins (through Django Admin API) I have come up with a fairly simple schema design: This is what's happening in the schema design above: Each Question can have multiple choices The QA maps the question to the answer selected by the user who did/took the quiz Each submitted quiz can have multiple questions together with their answers I am using Django for this particular project. -
DJANGO migrate big database from SQLite3 to PostgreSQL
I have a relatively bid database with around 50 model classes in DJANGO and I would like to migrate it from SQLite3 to PostgreSQL. I set up a dummy local PSQL for testing. I read on multiple other posts to do the following: dump the db Change SQL credentials in setup.py migrate load the db I was able to dump the DB into a json file. After I changed my settings to look like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db_name', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', } } I created the DB by hand, because I was getting errors that it does not exists. After this if I run python3 manage.py migrate I got a bunch of errors, that tables dont exists, so it is not doing what I wanted. End of the long error: django.db.utils.ProgrammingError: relation "gympro_gymclasstype" does not exist LINE 1: ...."type", "gympro_gymclasstype"."description" FROM "gympro_gy... I also saw on other posts that I should reset the migratons, so I tried python3 manage.py --fake appname zero. This also failed, so what I tried is I put the old SQLite3 cretendials back, made the fake reset, I check with showmigrations that the current status … -
ModuleNotFoundError: No module named 'users' from dj-rest-auth
I am trying to run celery on a Django application that has dj-rest-auth already configured but, I get the following error when I run - "celery -A config worker -l info" but, it works perfectly fine without errors when I do "python manage.py runserver". The application has several apps under the folder /apps and within the settings.py, it is imported as "apps.<app_name>". It does have an app called "users" so, it's imported as "apps.users". Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.10/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.10/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/celery/bin/worker.py", line 343, in worker worker = app.Worker( File "/usr/local/lib/python3.10/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/usr/local/lib/python3.10/site-packages/celery/loaders/base.py", line 111, in init_worker self.import_default_modules() File "/usr/local/lib/python3.10/site-packages/celery/loaders/base.py", line 105, in import_default_modules raise response File "/usr/local/lib/python3.10/site-packages/celery/utils/dispatch/signal.py", line 276, … -
"message": "Error: You do not have permission to perform this action. 'Traceback (most recent call last):\\n File \"/opt/dev-application/django-app
I am getting this msg error almost every second on my AWS cloudwatch log "message": "Error: You do not have permission to perform this action. 'Traceback (most recent call last):\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 483, in dispatch\\n self.initial(request, *args, **kwargs)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 401, in initial\\n self.check_permissions(request)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 336, in check_permissions\\n request, message=getattr(permission, \\'message\\', None)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 177, in permission_denied\\n raise exceptions.PermissionDenied(detail=message)\\nrest_framework.exceptions.PermissionDenied: You do not have permission to perform this action.\\n'", "customer": { "userId": null, "accountId": null }, "requestId": "65ecb0b6-a114-4dd3-9153-ad43c045a378", "data": {}, "dateCreated": "2021-12-09T11:36:33.998168", "level": "WARNING", "app": { "name": "frontend_api", "threadName": "DummyThread-781" } } ``` -
How to override list function of ModeViewSet to filter multiple value of same parameters in Django?
Currently this how my code looks - class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer def list(self, request): query_dict = QueryDict(request.META['QUERY_STRING']) query_dict = query_dict.dict() self.queryset = MyModel.objects.filter(**query_dict) return super().list(reuqest) Now if I invoke the endpoint with the api like /api/url/?param1=79&param2=34 it works fine. Assuming param1 and param2 are two fields present in MyModel. But if try to do this - /api/url/?param1=79&param2=34&param1=45&param2=576 it returns the result of param1=45 AND param2=576. Which is understandable since I am using dict to parse query params. But I want the results of param1=79&param2=34&param1=45&param2=576 combination. How to achieve that? -
whitenoise.storage.MissingFileError: The JS file 'drf-yasg\redoc\redoc.min.js' references a file which could not be found
I tried collecting static files on an API project I am working with Django/Django REST Framework and I got this error on my console. What could be the cause of the error? raise processed whitenoise.storage.MissingFileError: The file 'drf-yasg/redoc/redoc.standalone.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000002DEED19E050>. The JS file 'drf-yasg\redoc\redoc.min.js' references a file which could not be found: drf-yasg/redoc/redoc.standalone.js.map Please check the URL references in this JS file, particularly any relative paths which might be pointing to the wrong location. enter image description here -
Python/Django ORM: Return result only if there is no more recent date out of range filter
I need to do a query where I have a table in the following format: fk_customer overdue_date Basically I have a query that filters a monthly range of overdue_date. However, I only need to show some date if there isn't a newer date outside of this customer's range. IE. Customer1 - 2021-10-01 Customer1 - 2022-01-02 If I use the range for the month of October, it shouldn't show because there is a more recent date. How can I do this? In raw sql I use IN with a subquery looking for MAX DATE. -
when i run migrate the uuid is field is updating always will it give me some perfomance issue is anyone can explain me the reason and solution
class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True) activate_token = models.CharField(max_length=200,default=str(uuid.uuid4())) forget_password_token = models.CharField(max_length=200,default=str(uuid.uuid4())) first_name = models.CharField(max_length=100,blank=True,null=True) last_name = models.CharField(max_length=100,blank=True,null=True) status = models.CharField(max_length=100,blank=True,null=True) email = models.CharField(max_length=100,blank=True,null=True) gender = models.CharField(max_length=50,blank=True,null=True) city = models.CharField(max_length=100,blank=True,null=True) country = models.CharField(max_length=100,blank=True,null=True) Accounts\migrations\0010_alter_customer_activate_token_and_more.py - Alter field activate_token on customer - Alter field forget_password_token on customer Migrations for 'Store': Store\migrations\0004_product_shipping_charges_alter_product_price.py - Add field shipping_charges to product - Alter field price on product I have a model of customer i am storeing two things there one is user activation token and the other is forgot password token i want it random so i used uuid but when ever i am running migrate this migration always happening by the way i am not facing any functional error everything working fine but i have a feeling it might give me a error -
Running nginx and gunicorn in the same docker file
I have a Dockerfile which at the end runs run.sh. I want to run gunicorn on port 8000 and proxy requests on 80 to 8000 with nginx. The problem is running server is a blocking command and it never executes nginx -g 'daemon off;'. What can I do to handle this situation? Here is the run.sh file: python manage.py migrate --noinput gunicorn --bind=0.0.0.0:8000 bonit.wsgi:application & nginx -g 'daemon off;' And this the Dockerfile: FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y nginx supervisor build-essential gcc libc-dev libffi-dev default-libmysqlclient-dev libpq-dev RUN apt update && apt install -y python3-pip python3-cffi python3-brotli libpango-1.0-0 libpangoft2-1.0-0 RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY nginx.conf /etc/nginx/nginx.conf RUN python manage.py collectstatic --noinput ENTRYPOINT ["sh", "/usr/src/app/run.sh"]