Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pg-crypto - How do you migrate existing fields?
In my test environment I have installed pg-crypto by running "pip install django-pgcrypto". I logged into the database manually using "sudo -u postgres psql", then I connected to the database and installed the extension using "CREATE EXTENSION pgcrypto;". I then altered a field on one of my models from "models.EmailField" to "pgcrypto.EncryptedEmailField" and then ran makemigrations and migrate. I was able to successfully create a new account by making a call to the API view. I then went onto the database using the Postgres console and could see that it had encrypted the email field for that new user, but the previous entries are the same. Now when I log onto the Django admin console, I get the error "Corrupt ascii armour". I assume that this is because the table now has a mixture of unencrypted and encrypted email fields. If I start with a new database then all the fields are encrypted and I don't get the error in the admin console. Please can someone advise how I encrypt the exiting entries or if there is a way through Django migrations so I don't have to start with a new database? -
Need help in django ORM query to return response given below
I have the below model: publish_status = {'published': 'published', 'publishing': 'publishing', 'rejected': 'rejected', 'not-updated': 'not-updated', } publishToBridgeStatus = StringField(db_field="publishBridge", required=False, choices=publish_status.keys(), default="not-updated") Response needed count of each available status in DB: { "all": 0, "published": 0, "publishing": 0, "rejected": 0, "notUpdated": 0 } -
Djangorestframework > 3.11 Incompatible with Django 1.11, breaks build
akismet==1.1 amqp==1.4.9 anyjson==0.3.3 APScheduler==3.8.1 arabic-reshaper==2.1.3 asgi-redis==1.4.3 asgiref==1.1.2 attrs==21.4.0 autobahn==21.11.1 Automat==20.2.0 backcall==0.2.0 backports.functools-lru-cache==1.6.4 backports.shutil-get-terminal-size==1.0.0 backports.zoneinfo==0.2.1 beautifulsoup4==4.10.0 billiard==3.3.0.23 cached-property==1.5.2 caniusepython3==7.3.0 celery==3.1.17 certifi==2021.10.8 cffi==1.15.0 channels==1.1.2 chardet==4.0.0 charset-normalizer==2.0.10 click==8.0.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==36.0.1 cycler==0.11.0 daphne==1.4.2 decorator==4.3.0 defusedxml==0.7.1 Deprecated==1.2.13 distlib==0.3.4 Django==1.11.17 django-admin-honeypot==1.1.0 django-allauth==0.26.1 django-appconf==1.0.5 django-bootstrap-form==3.4 django-celery==3.1.17 django-compat==1.0.15 django-compressor==3.1 django-constance==2.8.0 django-extensions==2.1.6 django-filter==1.1.0 django-helpdesk==0.2.10 django-hijack==2.1.5 django-hijack-admin==2.1.10 django-js-asset==1.2.2 django-markdown-deux==1.0.5 django-modeladmin-reorder==0.3.1 django-mptt==0.13.4 django-otp==0.7.5 django-picklefield==2.0 django-pyodbc-azure==1.11.13.1 django-rest-swagger==2.2.0 django-richtextfield==1.6.1 django-simple-history==3.0.0 django-taggit==0.23.0 djangorestframework==3.8.2 email-reply-parser==0.5.12 enum34==1.1.10 et-xmlfile==1.1.0 fonttools==4.28.5 future==0.18.2 fuzzywuzzy==0.18.0 html5lib==1.1 httpagentparser==1.9.1 hyperlink==21.0.0 idna==3.3 imageio==2.13.5 imageio-ffmpeg==0.4.5 imgkit==1.2.2 importlib-metadata==4.10.0 incremental==21.3.0 install==1.3.5 ipython==7.31.0 ipython-genutils==0.2.0 itypes==1.2.0 jedi==0.18.1 Jinja2==3.0.3 joblib==1.1.0 jsonfield==2.0.2 kiwisolver==1.3.2 kombu==3.0.37 logzero==1.7.0 Louie==2.0 lxml==4.7.1 Markdown==3.3.6 markdown2==2.4.2 MarkupSafe==2.0.1 matplotlib==3.5.1 matplotlib-inline==0.1.3 moviepy==1.0.3 msgpack-python==0.5.6 nltk==3.6.7 numpy==1.21.5 oauthlib==3.1.1 openapi-codec==1.3.2 openpyxl==3.0.9 packaging==21.3 pandas==1.3.5 parso==0.8.3 pathlib==1.0.1 pathlib2==2.3.6 pexpect==4.8.0 pickleshare==0.7.5 Pillow==9.0.0 pretty-cron==1.2.0 proglog==0.1.9 prompt-toolkit==3.0.24 ptyprocess==0.7.0 pur==5.4.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 pycrypto==2.6.1 pycryptodome==3.12.0 Pygments==2.11.1 PyJWT==2.3.0 pymssql==2.2.3 pyodbc==4.0.23 pyOpenSSL==21.0.0 pyparsing==3.0.6 PyPDF2==1.26.0 python-bidi==0.4.2 python-crontab==2.6.0 python-dateutil==2.8.2 python-keyczar==0.716 python-openid==2.2.5 python-slugify==5.0.2 python3-openid==3.2.0 pytz==2021.3 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0 pyzmq==22.3.0 rcssmin==1.1.0 redis==2.10.6 regex==2021.11.10 reportlab==3.6.5 requests==2.27.1 requests-oauthlib==1.3.0 rjsmin==1.2.0 scandir==1.10.0 scikit-learn==1.0.2 scipy==1.7.3 service-identity==21.1.0 simplegeneric==0.8.1 simplejson==3.17.6 six==1.16.0 sklearn==0.0 soupsieve==2.3.1 sqlparams==3.0.0 sqlparse==0.4.2 text-unidecode==1.3 textblob==0.17.1 threadpoolctl==3.0.0 tqdm==4.62.3 traitlets==5.1.1 twilio==7.4.0 Twisted==21.7.0 txaio==21.2.1 typing_extensions==4.0.1 tzdata==2021.5 tzlocal==4.1 uritemplate==4.1.1 urllib3==1.26.7 vaderSentiment==3.3.2 vine==5.0.0 wcwidth==0.2.5 webencodings==0.5.1 wrapt==1.13.3 xhtml2pdf==0.2.5 xlrd==2.0.1 XlsxWriter==3.0.2 zipcodes==1.2.0 zipp==3.7.0 zope.interface==5.4.0 I am trying to migrate my project from python 2.7 to 3.7 I have installed Django =1.11.17 and … -
jQuery import causing my webpage to become unresponsive
I have the following html page: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <title>Message wall</title> <style> #messages { overflow-y: scroll; border: black; height: 20em; width: max-content; } #back { position: fixed; top: 0; right: 0; margin-right: 5px; background-color: gainsboro; } #message-sender { position: fixed; bottom: 0; } form { margin-bottom: 5px; } #message-input { padding-right: 10em; } </style> </head> <body> <div id="messages"></div> <div id="back"> <h3 style="margin: 0;"><a href='http://localhost'>Main Page</a></h3> </div> <div id="message-sender"> <form> <h3>Input message: </h3> <input id="message-input" type="text"> <input id="message-send-btn" type="button" value="Send"> </form> </div> <script> function usernameExists() { user = localStorage.getItem('user') return !(user == null || user == "null" || user == '') } function promptUsername() { let input = prompt('Please enter a username: ') if (input.length <= 20 && !(input.includes(' '))) { localStorage.setItem('user', input) } else if (input.length > 20) { alert('Username must be less than 21 characters!') } else /* if (input.includes(' ')) */ { alert('Spaces are not allowed in usernames!') } } if (!usernameExists()) { promptUsername() } else { console.log(localStorage.getItem('user')) } function updateMsgs() { $.ajax({ url: "http://localhost/testing/getmsgs", success: function (response) { document.getElementById('messages').innerHTML = response } }) } updateMsgs() document.getElementById('message-send-btn').addEventListener('click', () => { while (!usernameExists()) { promptUsername() } let msg = document.getElementById('message-input').value if (msg == null) { return … -
Implement Recursive function to check whether a model has child or not
I'm trying to implement a recursive function that will check if an object has child with the parent id. If has than it will add the child to the list and will recursively call the function to check if newly added child has further children. My Current Code that works fine as expected: def get_nav_items(self, instance): childs = [] items = Content.objects.filter(parent_id=instance) for item in items: childs.append(item) for item in items: ch = Content.objects.filter(parent_id=item) if ch.count() > 0: for c in ch: childs.append(c) menu_objecs = [] for item in childs: menu_objecs.append(ContentNevItemSerializer(item).data) return menu_objecs The method that isn't returning any result now: def extract_item(self, nav_obj, nav_list = []): cont = Content.objects.filter(parent_id=nav_obj) if len(cont) == 0: return nav_list else: for ct in cont: self.extract_item(ct, nav_list) # nav_list.append(cont) return nav_list -
Django uploading large files: takes time to reach till the first line of view
I have simple view which get a file def upload_file(request): print("first line") .... Here when i upload a file of 800 MB, the printing of first line itself takes 5-10 sec or more Definitely I am expecting it to take time, when i try to access it like upload_file = request.data['file'] because it has to create a copy of the file in /tmp. But here even before that it takes lot of time. I hope its taking time to build the request object itself. Or is it time time taken from the browser to the django I just wanted to know whats taking the time -
How to edit select option values in Django Forms
models.py class Product(models.Model): product = models.CharField(max_length=50, blank=True, null=True) price = models.IntegerField(blank=True,null=True) def __str__(self): return self.product class Meta: db_table = "product" class price_list(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True) price = models.IntegerField(blank=True,null=True) value = models.IntegerField(null=True) class Meta: db_table = "pricelist" Note: the value for each option is the prduct id. I want to change that value to price(that's related to the product). forms.py class CourseCreateForm(forms.ModelForm): class Meta: model = price_list fields = ['product', 'price', 'value' ] views.py def index(request): result = Product.objects.all() form = CourseCreateForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully saved') return redirect('/') context = { 'form':form, 'title': "Add Course", 'col':result } return render(request,'index.html', context) index.html I want to edit select option value like(value={{result.price}}) i have no idea how can write. <div class="bg-light p-5 rounded"> <h1>{{title}}</h1> <div class="row"> <div class="col-sm-5"> <div class="display_table"> <form action="" method="POST"> {% csrf_token %} {% comment %} {{form.as_p}} {% endcomment %} {{form|crispy}} <br> <input type="submit" value="Save" class = "btn btn-primary" onclick="demo()"> <b style="color:green;" id="colordisplay"></b> <label for="msg"></label> </form> </div> </div> </div> -
UnboundLocalError: local variable 'mtotal_cost_price' referenced before assignment in Django 3.0
Here is my code Django = 3.0 Python = 3.7 def get_quote_margin(self): # get all items quote_item = self.quote_estimate_item.filter(quote_items__isnull=False) total_cost_price = 0 total_sell_price = 0 if quote_item: for item in quote_item: cost_price = self._convert(item.cost_currency, self.currency, item.cost_price) mtotal_cost_price += cost_price * float(item.quantity) sell_price = self._convert(item.currency, self.currency, item.unit_price) total_sell_price += sell_price * float(item.quantity) if total_sell_price: return ((total_sell_price - total_cost_price)/total_sell_price)*100 I am getting this error how could i solve it mtotal_cost_price += cost_price * float(item.quantity) UnboundLocalError: local variable 'mtotal_cost_price' referenced before assignment -
Django, Nextjs | set-cookie is not set in the browser even though the value is set
I am creating a JWT authentication with Django and Nextjs. I can implement the signup and login functionality, I can get the accessToken by logging in. However, the response header is Set-Cookie is set in the browser(chrome, safari,firefox) even though there is a cookie. What are the possible causes? response header Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://localhost:3000 Allow: POST, OPTIONS Content-Length: 715 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 11 Jan 2022 04:34:59 GMT Referrer-Policy: same-origin Server: Werkzeug/2.0.2 Python/3.9.7 Set-Cookie: jwt-auth=〇〇; expires=Tue, 11 Jan 2022 05:34:59 GMT; HttpOnly; Max-Age=3600; Path=/; SameSite=None; Secure Set-Cookie: csrftoken=〇〇; expires=Tue, 10 Jan 2023 04:34:59 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure Set-Cookie: sessionid=〇〇; expires=Tue, 25 Jan 2022 04:34:59 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Environment Django==4.0.1 Nextjs Server Domain https://127.0.0.1:8000 Front Domain https://localhost:3000 settings.py | Django CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', 'https://127.0.0.1:3000', 'https://localhost:3000', ] index.js | Next const login = async (data) => { const res = await axios.post("https://127.0.0.1:8000/api/auth/login/", data, {withCredentials: true}) }; -
How do I create an object of a Model that has a foreign key to another Model in Django?
I am pretty new to Python and Django and I am kinda struggling with a project. I am trying to build a Etsy-like website, where people can sell their things (not really like a shop, people can post everything they want to sell). I am now trying to add the "Add Item" functionality for the User, where he can post its own sale. But the problem I have stummbled upon is the following: my model Product has a foreign key to the model Customer and I don't know how to create a new product in the database because it keeps saying NOT NULL constraint failed: app_product.added_by_id. I tried something like this, but it is not working and I have no idea what I should do. https://i.stack.imgur.com/MaykE.png My classes looks like this: https://i.stack.imgur.com/LF9R6.png https://i.stack.imgur.com/f5Te7.png Anoyone has any idea what I should try? Or if I can make it automatically in the HTML part or something -
UNIt Test- How to test Viewsets create Function in DRF
I want to test create function which is inside viewsets. I have tried I got 400 error. views.py class PersonalInfoAPI(viewsets.ViewSet): permission_classes = [IsOwnerPermission] def get_object(self, pk): obj = get_object_or_404(Employee.objects.all(), pk=pk) self.check_object_permissions(self.request, obj) return obj def create(self, request): print("im in create") personal_info = JSONParser().parse(request) data = personal_info['data']['personal_info'] data['appraisal_master_id'] = personal_info['data']['appraisal_master_id'] employee = self.get_object(pk=data['employee_id']) appraisal = get_object_or_404(Appraisal, pk=data['appraisal_master_id']) employee_appraisal = EmployeeAppraisal.objects.filter(appraisal=appraisal, employee=employee).first() if employee_appraisal: personal_info_serializer = PersonalInfoSerializer(employee_appraisal, data=data) if personal_info_serializer.is_valid(): personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_200_OK) else: personal_info_serializer = PersonalInfoSerializer(data=data) if personal_info_serializer.is_valid(): employee_appraisal = personal_info_serializer.save() return Response(employee_appraisal.appraisal_info(user=self.request.user), status=status.HTTP_201_CREATED) return Response(personal_info_serializer.errors, status=status.HTTP_400_BAD_REQUEST) test.py def test_personal_info_api(self): url = reverse('employee1-list') self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key) resp1 = self.client.post(url, data={'employee_id': 1, 'appraisal_master_id': 1}, format='json') print(resp1) self.assertEqual(resp1.status_code, 200) I am newbie for django and testing as well. Any help appreciable,. -
Not able to submit data from model form with multiple files django
I am trying to add multiple files through use of two models and forms. Have tried to update but not able to make it work. On submission of form, there are no errors, but nothing is posted to database. Please help. Also, how do I define users as full name in drop downs in forms? Tried formfields approach but not working. Also, form not showing empty label models.py class Case(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name= 'caseclients' ) statute = models.ForeignKey(Statute, on_delete=models.CASCADE) financial_year = models.ForeignKey(Financialyear, on_delete=models.CASCADE) proceeding = models.ForeignKey(Proceeding, on_delete=models.CASCADE) case_title = models.CharField(max_length=200) initiated_on = models.DateField(auto_now=False, auto_now_add=False) communication_received_on = models.DateField(auto_now=False, auto_now_add=False) first_date_of_hearing = models.DateField(auto_now=False, auto_now_add=False) limitation_period = models.CharField(max_length=500, blank=True) amount_involved = models.IntegerField(null=True,blank=True) person_responsible = models.ForeignKey(User, on_delete=CASCADE, related_name = 'person_responsible') assisted_by = models.ManyToManyField(User, related_name = 'assisted_by', blank=True) brief_of_case = models.TextField(max_length=1000) status = models.CharField(choices=[('Open','Open'),('Close','Close')],default='Open', max_length=100) def __str__(self): return self.case_title class CaseFiles(models.Model): attachment = models.FileField(upload_to='casefiles/') case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name= 'casefiles') forms.py class CaseFilesCreationForm(ModelForm): class Meta: model = CaseFiles fields = ['attachment'] attachment = forms.FileField, widgets= { 'attachment': forms.ClearableFileInput(attrs={'multiple': True, 'class': 'form-control form-control-light','type': 'file',}), } class CaseCreationForm(ModelForm): class Meta: model = Case fields = '__all__' client = forms.ModelChoiceField(queryset=Client.objects.all(), to_field_name="name_of_client", empty_label="Select Client",), statute = forms.ModelChoiceField(queryset=Statute.objects.all(), to_field_name="statute", empty_label="Select Statute",), financial_year = forms.ModelChoiceField(queryset=Financialyear.objects.all(), to_field_name="financialyear", empty_label="Select Financial Year",), … -
call the function response in another function in Django RestFramework
I tried calling the another function inside the function which will return the response.I have tried this approach but couldn't able to achieve it. I'm just getting error as AssertionError at /api/Data/CurrentRunningActivity2/54 Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` views.py: @api_view(['GET']) def CurrentRunningActivityView2(request, UserID): if request.method == 'GET': CurrentRunningActivity(UserID) def CurrentRunningActivity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivity] @UserId=%s',(UserID,)) result_set = cursor.fetchall() for row in result_set: TaskId=row[0] Number=row[1] Opened=row[2] Contacttype=row[3] Category1=row[4] State=row[5] Assignmentgroup=row[6] CountryLocation=row[7] Openedfor=row[8] Employeenumber=row[9] Shortdescription=row[10] Internaldescription=row[11] Additionalcomments=row[12] TaskName = row[1] print("Number", Number) return Response({ "TaskId": TaskId, "Number":Number,"Opened":Opened, "Contacttype":Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "CountryLocation":CountryLocation, "Openedfor":Openedfor, "Employeenumber":Employeenumber , "Shortdescription":Shortdescription, "Internaldescription":Internaldescription, "Additionalcomments":Additionalcomments,"TaskName":TaskName},status=status.HTTP_200_OK) -
How to launch Django project / run server, with an exe
I have written the following .bat file: start chrome http://127.0.0.1:8000/ venv\Scripts\activate python manage.py runserver 8000 When I perform these steps myself, one by one, in prompt, it runs the server and opens the site perfectly. However, when I use iexpress to convert this file to an .exe and run it, the site just displays the "unavailable" message, as if no server were running. I'm not sure, but I think this is because the exe closes as soon as it's executed the commands, instead of keeping the server running. How do I fix this? -
Django logger is not shown that runs on Docker
logger.debug() and print() are not shown on a Django project that runs on Docker. Any other operations are correct. Is my recognition correct that the logs show up on the terminal window that runs docker-compose up? I tried outputting resolution, but it not work for me. My settings are below. directory Project ├── Service_ID │ ├── root │ ├──settings.py | ├── docker-compose.yml └── docker ├── mysql │ ├── Dockerfile │ └── my.cnf ├── nginx │ ├── default.conf │ └── uwsgi_params └── python ├── Dockerfile └── requirements.txt docker-compose.yml version: "3.8" services: ... web: image: nginx:1.21.3-alpine ports: - 8000:8000 volumes: - ./Service_ID:/workspace - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf - ./docker/nginx/uwsgi_params:/etc/nginx/uwsgi_params working_dir: /workspace depends_on: - root root: build: ./docker/python command: uwsgi --socket :8001 --module root.wsgi --py-autoreload 1 --logto /tmp/tmp.log volumes: - ./Service_ID:/workspace expose: - "8001" depends_on: - db volumes: db-store: python/Dockerfile FROM python:3.8.3 ENV PYTHONUNBUFFERED 1 RUN mkdir /workspace WORKDIR /workspace ADD requirements.txt /workspace/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt ADD . /workspace/ Service_ID/root/settings.py IS_ON_LOG_FILE = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, 'console': { 'format': '\t'.join([ "[%(levelname)s]", "%(message)s", ]) }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, … -
I get mime type error when I connect my react app(via vite.js) with django framework
recently I'm starting to make a web application with React and Django. I installed react with vite.js(because it seems so fast in the development environment). and I connected it to Django web framework and ran it. and I thought It would show basic react page(you know, dark page and favicon is revolving ) However, contrary to my expectations, It only shows blank and I checked the console.log. the error message was this : Refused to apply style from 'http://127.0.0.1:8000/assets/index.cd9c0392.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. so I googled it and figure out that is a problem with the path in most cases. but when I check the my index.html in build file, path seems fine. below is my build folder structure and index.html, can you tell me what is wrong with my code or logic or both? thx for reading , your help will be appreciated. frontend -dist => this is build folder --assets ---index.cd9c0392.css ---favicon.21sd12.js . . . --index.html -node_modules -src -index.html . . . index.html(in dist) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/assets/favicon.17e50649.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite App</title> … -
How to set up Docker image of Celery with Django using a separate container
I would like to separate my Celery Docker container from my backend (Django) Docker container. I would like the Celery container to be built without relying on the backend container. Currently, all the tutorials I am finding online are set up so that the Celery image is built using the Backend container's context like such: backend: build: context: ./backend celery: build: context: ./backend I feel that Celery relying on the backend context to build the image is not the proper way to do this as there are a lot of resources not needed from the backend context in the celery container. Currently my project docker-compose looks as such: backend: build: context: ./backend celery: build: context: ./backend dockerfile: Dockerfile.celery Project dir tree: ├── backend │ ├── Dockerfile │ ├── Dockerfile.celery │ ├── Dockerfile.prod │ ├── entrypoint.dev.sh │ ├── entrypoint.prod.sh │ ├── requirements.txt │ └── venv ├── docker-compose.ci.yml ├── docker-compose.prod.yml ├── docker-compose.yml ├── frontend │ ├── Dockerfile │ ├── Dockerfile.prod ├── nginx │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── certbot │ └── conf The Dockerfile.celery: FROM python:3.9.5-alpine WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add … -
How to use a value from a query into another query in django
I have the following code in my view: # default group view for group admins def adminGroupView(request): # get group id => group data and messages group_id = GroupUser.objects.get(username_id=request.user.id) groupdata = Group.objects.get(group_id=group_id) groupmessages = MessageBoard.objects.filter(group_id=group_id) groupmembers = GroupUser.objects.filter(group_id=group_id) form = SendMessageForm() context = { "groupdata":groupdata, "groupmessages":groupmessages, "groupmembers":groupmembers, "form":form } return render(request, 'base/group-admin.html', context) I keep getting a typeerror TypeError at /group/ Field 'group_id' expected a number but got <GroupUser: 9>. when i replace the group_id with a number, the code works just fine. How do i use the value from the other query. -
How to display django model column values horizontally on django template
my issue is displaying the model data on django template horizontally. I have a model named "Main" with 3 columns. When I display on the template it looks like this- I want to filter it by category that will look like this- Main.objects.filter(category='food') My goal is to show the category name on the template with the price horizontally on the side with plus signs. It should look something like this- food= 8+10+11 I tried for...in loop both on template and on views.py both failed. Tried something like this- print(f"{i.category}={i.price}+") with for loop. Didn't work. output+=f'{i.price}+' with a for loop, holding it in a variable and display that variable on template. Different combinations of those, all failed. Since += is mainly for integers, I tried with i.price without turning it into a string, failed. Most answers I found here on "displaying model data horizontally on Django template" are about using css to display form elements side by side,which I know how to do and not exactly my problem. Can anyone point me to the right direction? Here is my models.py class Main(models.Model): name = models.CharField(max_length = 60, blank = True) category = models.CharField(max_length = 60, blank = True) price = models.CharField(max_length … -
how to set up a docker with an existing database?
I have a project in Django, I want to configure my docker with an existing postgres database, but the tutorials I see are from a database without data. who could give me a guide, please It's my set up Docker-compose: services: web: build: . command: python3 manage.py migrate command: python3 manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code depends_on: - db db: image: postgres Docker file FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r requirements.txt File setting in django project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'postgres', 'USER': 'postgres', 'HOTS': 'db', 'PORT': 5432, } } -
I cannot understand why 3rd path is not activated
I am new to Django and I have no idea why this is not working. I am trying to add a new path to newyear/ but it looks as if it's just not accepting a new path. Heres the code: In setting.py you can see I added newyear app INSTALLED_APPS = [ 'hello', 'newyear', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: (this is where the problem supposedly is) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")) path('newyear/', include("newyear.urls")) ] urls.py(for the newyear app): from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index") ] and finally views.py: import datetime from django.shortcuts import render # Create your views here. def index(request): now = datetime.datetime.now return render(request, "newyear/index.html", { "newyear": now.month == 1 and now.day == 1 }) This is the error its marking: path('hello/', include("hello.urls")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma? Sorry if I wasn't clear enough. I've been trying to solve this for hours, any help would be appreciated. Thanks! -
Getting my backend url in verification email instead of frontend url
Like the title says, I'm receiving the wrong link in an activation email and I'm not quite sure how to change it... So far I have been able to sign users up, but when they receive the account activation email, it includes the wrong url. Right now it currently includes my backend url that I used to make the post request. I am still very much new to redux and django so I'm still trying to figure out everything. I know it likely has something to do with my .env file and I believe my auth.js actions file, but I'm not a 100%. Email: You're receiving this email because you need to finish activation process on total-weather-backend.herokuapp.com. Please go to the following page to activate account: https://total-weather-backend.herokuapp.com/activate/:uid/:token However, the link is meant to go to the front end like so: https://total-weather-frontend.com/activate/:uid/:token I'm just not sure where the email is getting this url exactly. I figured it has to be from the .env and either the signup or verify action from the post request. If it is getting it from the post request, is there a way to redirect the user to the right url? I know I was using localhost:8000 … -
How to turn django into .exe that auto launches browser?
I have made a djangoproject with a venv folder. With cmd I can launch my project by: activating the environment with: venv\Scripts\activate then inside the environment: python manage.py runserver 8000 opening my browser and going to http://127.0.0.1:8000/ I am trying to turn my django project into something my client can run without having python. And that will auto start the server and open the browser link with just one click of a button. I used pyinstaller on manage.py to turn the whole thing into windows exe's, but the problem is that now when I click on that exe, it doesn't run the server. It just gives me the same output than if I'd run manage.py directly (without 'runserver'): Type 'djangoProject.exe help <subcommand>' for help on a specific subcommand. Available subcommands: [...] How do I make it so that I get an exe which does the 'runserver' command, and launches the browser? What I've tried: I thought maybe I could create another script that runs the exe, but doing djangoProject.exe runserver in cmd just gives me the error: RuntimeError: Script runserver does not exist. And I also tried doing something like writing a python script (shown below) that would do the … -
How to address "sqlite3.OperationalError: attempt to write a readonly database" In django migration when sqlite db file is writable
This is not the usual writable file problem. With a new database on django 3.2.7, sqlite 3.31.1: I can run the django shell, create an sqlite3 db directly using sqlite (using the settings DATABASE parameters). I can even stick tables in it etc. using a cursor in the shell without any problems. However, if I run django's migrate command it gives: Traceback (most recent call last): File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/tools/cliosoft/sos/7.10.p3/sos_7.10.p3_linux64/sosmgrweb/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: attempt to write a readonly database If there is no initial sqlite3 file, the django migrate command creates a new file of zero bytes in size and gives the same error as above. The user is the same throughout and has write permission to the folder (and to the sqlite3 db file). The virtual environment is on a read only mounted volume (I'm thinking this must be somehow causing the problem) but everything else in the venv appears to be working. -
How to customize SocialAccount on django-allauth?
So, I'm integrating django-allauth on an django application. The Users table has not only email as a unique field. It has email + company, so the data might be like below: ID Email Company --------------------------------- 1 john@example.com Google 2 john@example.com Microsoft ... 9 john@example.com Apple Note that there are three accounts with the same email, but with different companies. Depending on the different interface (apple.my-app.com; google.my-app.com), John can log in to all these accounts. Now, we want to integrate SocialLogin to this app. In the current approach, django-allauth socialaccount keeps the accounts unique with unique_together = ("provider", "uid"). Each account is also linked with one single user account. See here My working approach would be unique_together = ("provider", "uid", "company"), so by that having the Social Accounts table like: User UID Provider Company --------------------------------- 1 abc GitHub Google 2 abc GitHub Microsoft 9 abc GitHub Apple Any idea how this can achieved WITHOUT FORKING THE REPO?