Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to install and import explainx library from explainX.ai (Artificial intelligence) in python or django
Is there a way to import explainx from explainX.ai the library in django framework , i am facing some problem in installing this library in python 3.7(32-bit), python 3.9.1(64-bit), but I have installed it into python 3.7.4(64-bit) but when i import explainx library from explainX.ai it gives me errorlike this :- ImportError: DLL load failed: The specified module could not be found. i will share whole it for reference ------------------------------------------------------------------------------ Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved. C:\Users\Ayush>pip show explainx Name: explainx Version: 2.406 Summary: Explain and debug any black-box Machine Learning model. Home-page: https://github.com/explainX/explainx Author: explainx.ai Author-email: muddassar@explainx.ai License: MIT Location: c:\users\ayush\appdata\local\programs\python\python37\lib\site-packages Requires: jupyter-dash, dash-bootstrap-components, dash, dash-core-components, dash-html-components, plotly, dash-table, pandas, numpy, dash-bootstrap-components, cvxopt, scikit-learn, scipy, pandasql, tqdm, dash-editor-components, shap, dash-daq, pytest, pyrebase Required-by: C:\Users\Ayush>python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import explainx Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\__init__.py", line 1, in <module> from explainx.explain import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\explain.py", line 16, in <module> from dashboard import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\lib\dashboard.py", line 3, in <module> from protodash import * File "C:\Users\Ayush\AppData\Local\Programs\Python\Python37\lib\site-packages\explainx\lib\protodash.py", line … -
How to structure models in Django?
I'm working on a project using Python(3.7) and Django(3) in which I have to create some models to store reports. There are 4 different models to represents each type of report with only 2 common fields(RequestId, InstCode) but the rest of the fields are different. In the end, I have to display the 10 recent reports (mixed from all models) on the home page. Here's how I have implemented my models at the moment: From models.py: class DistributionReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) Currency = models.CharField(max_length=3, blank=False) Denomination = models.IntegerField(blank=False, default=0)decimal_places=2) date = models.DateField(default=datetime.date.today) class Meta: verbose_name = 'Distribution Report' def __str__(self): return self.RequestId class ExpenditureReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) StaffExpenditure = models.DecimalField(max_digits=12, decimal_places=2) Month = models.IntegerField(blank=False, default=0) Quarter = models.IntegerField(blank=False, default=0) Year = models.IntegerField(blank=False, default=0) class Meta: verbose_name = 'Expenditure Report' def __str__(self): return self.RequestId class StorageReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) Currency = models.CharField(max_length=5, blank=False) Denomination = models.IntegerField(blank=False, default=0) date = models.DateField(default=datetime.date.today) class Meta: verbose_name = 'Processing Report' def __str__(self): return self.RequestId class AssetsReport(models.Model): RequestId = models.CharField(max_length=256, blank=False, default=0) InstCode = models.CharField(max_length=3, blank=False) AssetClassificationId = models.IntegerField(blank=False, default=0) VaultCapacity = models.DecimalField(max_digits=10, decimal_places=2) Year = models.IntegerField(blank=False, default=0) … -
I have problem with AutoField in my model and seqence in oracle database
I use Legacy database oracle 11g and there are a seqences. If I remove number_mymodel field from my model i have an error: ORA-00904: "MYMODEL"."ID": invalid identifier if i try class MyModel(models.Model): number_mymodel = models.AutoField(primary_key=True ,auto_created=True) ... it's work, but if I want add in my django admin panel number_Mymodel is NULL so I can't add it. What should I do with my sequence in database or in my model? I want that, if I'm adding in django panel it will be autoincrement number_mymodelin my database. -
I want to edit SizeProductMapping model using Django forms but The form is not rendering - Django
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made. My models are as shown below. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) This is the form I used to add and edit the model. forms.py from django import forms from user.models import SizeProductMapping class SizeProductMapForm(forms.ModelForm): class Meta: model = SizeProductMapping fields = ['size_id', 'prod_id'] Here is the view I created to add ,update and delete the record. views.py def sizeProductMap(request): form = SizeProductMapForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() return redirect("/admin1/sizeProductMap/") else: sizeProductMap_show = SizeProductMapping.objects.all() # start paginator logic paginator = … -
getaddrinfo: xxURL get result from proxy gai_error = 0
Im building a flutter application which uses django ad back-end. using signup api endpoint. the api shows error 200 from the logs but signup doesnt go through. the logs D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 D/libc-netbsd( 8600): getaddrinfo: hookie-twitter.herokuapp.com get result from proxy gai_error = 0 I/flutter ( 8600): 200 sign up service Future<int> authUserSignup(String username, String password, String email) async { http.Response response = await http.post( signUpUrl, body: { "username": username, // "phone":phone, "password": password, "email": email, } ); print(response.statusCode); return response.statusCode; } on signup onClicK _pressCreateAccountButton(){ //TO DO: MOVE TO VERIFY PHONE SECTION var signMeUp = connectSigninApi.authUserSignup(editControllerName.text, editControllerEmail.text, editControllerPassword2.text); if(signMeUp == 200){ if(_globalformkey.currentState.validate() && matchesEmail.hasMatch(editControllerEmail.text)){ if(editControllerPassword1.text == editControllerPassword2.text){ print("User pressed \"CREATE ACCOUNT\" button"); print("Login: ${editControllerName.text}, E-mail: ${editControllerEmail.text}, " … -
What is the POST equivalent for requesting GET parameters?
I want to request the paths through the POST method because the request lines are too large in the url created by the GET method. Is there any alternatives for request.GET.getlist('paths') if the paths are very long, then it shows Bad Request, Request Line too large. I also know how to use Post in templates too. views.py def test_download(request): paths = request.GET.getlist('paths') context ={'paths': paths} response = HttpResponse(content_type='application/zip') zip_file = zipfile.ZipFile(response, 'w') for filename in paths: zip_file.write(filename) zip_file.close() response['Content-Disposition'] = 'attachment; filename='+'converted files' return response templates <a href ="{% url 'test_download' %}?{% for path in paths %}paths={{ path|urlencode }}&{% endfor %}">Converted Files</a> -
How to use list as queryset for select filed django
Is there any way that list value can be used as a query set? I want to show the SKU return shown at the bottom as the data of the select field. I'm really new to Django. Any help would be greatly appreciated. Model Form: class PurchaseOrderDetailsForm(forms.ModelForm): product = forms.ModelChoiceField(label=('Product'), required=True, queryset=Product.objects.all(), widget=Select2Widget()) product_attr = forms.CharField(label=('Attributes'), widget=Select2Widget()) order_qnty = forms.DecimalField(label=('Order Qnty'), required=True) class Meta: model = PurchaseOrder_detail exclude = () def __init__(self, *args, **kwargs): super(PurchaseOrderDetailsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields['product'].widget.attrs.update({'class': 'setprice product', 'style': 'width:100%', 'required': 'true'}) self.fields['product_attr'].widget.attrs.update({'class': 'setprice product_attr', 'style': 'width:250px'}) self.fields['order_qnty'].widget.attrs.update({'class': 'setprice order_qnty', 'min': '0', 'required': 'true'}) self.fields['product_attr'].queryset = ProductAttributes.objects.none() if 'product' in self.data: product_id = int(self.data.get('product')) attrs = ProductAttributes.objects.filter(product=product_id).values('product', 'size__name', 'colour__name', 'cupsize__name') sku = [] for attr in attrs: att = {'id': '-'.join([str(attr['product']), str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])]), 'text': '-'.join( [str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])])} sku.append(att) try: self.fields['product_attr'].queryset = sku except (ValueError, TypeError): pass sku return: [{'id': '108-32-B-Grey', 'text': '32-B-Grey'}, {'id': '108-32-C-Grey', 'text': '32-C-Grey'}, {'id': '108-32-B-White', 'text': '32-B-White'}, {'id': '108-32-C-White', 'text': '32-C-White'}, {'id': '108-34-B-Grey', 'text': '34-B-Grey'}, {'id': '108-34-C-Grey', 'text' : '34-C-Grey'}, {'id': '108-34-B-White', 'text': '34-B-White'}, {'id': '108-34-C-White', 'text': '34-C-White'}] -
Django Error: ValueError at /new_bid/1 Cannot assign "1": "Bid.listingid" must be a "Listings" instance
I am getting the error: ValueError at /new_bid/1 Cannot assign "1": "Bid.listingid" must be a "Listings" instance." I am still learning about Foreign Keys so I may have used it wrong? I'm also using 'listingid' in both the models 'Listings' and 'Bid.' I'm wondering if this is part of the issue, but it makes sense to have both to me. I am just learning about how 'self' works also, so I think part of the problem is in the Listings model at the very bottom: In the Listings model if I do: return self.last_bid I get the error "'>' not supported between instances of 'int' and 'Bid'" and if I keep it as is now, I get the error in the title of this Stack Overflow post. Any help is appreciated, I'm having trouble understanding the error. views.py def new_bid(request, listingid): if request.method == "POST": listing = Listings.objects.get(pk=listingid) response = redirect("listingpage", listingid=listingid) try: bid = int(request.POST["bid"]) except ValueError: response.set_cookie( "message", "Please input something before submitting the bid", max_age=3 ) return response if bid > listing.current_price(): response.set_cookie("message", "Your bid was accepted", max_age=3) Bid.objects.create(bid=bid, listingid=listingid, user=request.user) else: response.set_cookie( "message", "Your bid should be higher than the current bid", max_age=3 ) return response … -
Serialize Django Model and return GET Response
I am trying to serialize the queryset objects I created when retrieving all jobs from my model. Basically I want an endpoint that lists all jobs that are currently created in the database. Anyone has permissions to view the jobs. However you need to be authenticated to POST, DELETE, or EDIT new jobs. My problems is just making the jobs viewable at the endpoint i created using APIView. I was getting an error before that says the object is not in JSON format. views.py class RetrieveJobsView(APIView): """Retrieves all job postings""" serializer_class = serializers.JobSerializer def get(self, request, format=None): """ Return a list of all jobs""" queryset = Job.objects.all() queryset = serializers.JobSerializer(queryset) return Response(queryset) serializers.py class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" user = self.context['request'].user print(self.context['request']) if not user: msg = _('Unable to POST job request. A valid user must be logged in.') raise serializers.NotAuthenticated(msg, code=None) validated_data[user] = user return validated_data models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() … -
Django API responding slow and not returning Images on Heroku
I'm trying to host my Django Rest API to heroku for free so that my flutter mobile app can communicate with it. But the server response is extremely slow. Besides, it doesn’t returns images for user profile. Moreover, I'm using Image recognition at API to check image objects and return the checked image to client end. But the API fails to return the result. What could be the possible solution. I've applied migrations to server's end. N.B: it’s my University final project which needs to be hosted, so that I can show it for getting jobs. -
Foreign key of models should refer to a particular filed in db - Django
class UserModel(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'password'] email = models.EmailField(unique=True) profile_image = models.ImageField(upload_to='user/profile_image', null=True, blank=True) phone = models.CharField(max_length=12, unique=True, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) emp_id = models.CharField(max_length=20, unique=True, blank=True, null=True) class IndividualWorkAnalysis(models.Model): user_id = models.ForeignKey(UserModel, to_field="emp_id", on_delete=models.CASCADE, null=True, related_name="user_id") Here above I need to access 'emp_id' from 'UserModel'. All my migrations went correct, but not able to fetch the 'emp_id' on the admin panel of Django. There it just lists the usernames. -
How to write data to a Django temp file?
Hello Community! I have a small application that allows you to download certain multimedia content from an HTML template. To save resources, I want this file to be stored only on the PC of the users who visit the eventual website, which is why I will use a temporary file NamedTemporaryFile that the FrameWork Django provides. Part of the code consists of: HTML TEMPLATE: ... <input type = "button" value = "Download" onclick = "window.open('download')"> ... urls.py: from django.urls import path from ProjectApp import views urlpatterns = [ ... path('download', views.download), ... ] views.py: import os from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper from django.http import HttpResponse from django.core.files.temp import NamedTemporaryFile def download(request): newfile = NamedTemporaryFile (suffix='.txt', mode='w+b') file_path = os.path.join(MEDIA_ROOT, 'test.txt') # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') filename = os.path.basename('archive_test.txt') chunk_size = 8192 response = StreamingHttpResponse( FileWrapper(newfile, chunk_size), content_type="application/octet-stream") response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = f'attachment; filename={filename}' return response It should be noted that as I show it, it works as I wish, since a download dialog appears in the browser with the archive_test.txt file in a "starting" state. What I want is that from that moment on, the information that it will contain begins to be written to said … -
Heroku app successfully deploying, but receiving application error when loading site. But I can seem to find an error
When loading my site it displays the error message; Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail With an application log of; 2021-01-21T10:56:36.186139+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=afternoon-retreat-21879.herokuapp.com request_id=b50977ff-d8c6-4b2f-b633-34965f253af3 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T10:56:36.841645+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=afternoon-retreat-21879.herokuapp.com request_id=b1224d5b-75d2-4aa3-8411-b5875124475e fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T11:06:56.778335+00:00 app[api]: Starting process with command `python manage.py migrate` by user juniornkiangmatiah@gmail.com 2021-01-21T11:07:05.370028+00:00 heroku[run.9335]: State changed from starting to up 2021-01-21T11:07:05.735946+00:00 heroku[run.9335]: Awaiting client 2021-01-21T11:07:05.789615+00:00 heroku[run.9335]: Starting process with command `python manage.py migrate` 2021-01-21T11:07:29.264945+00:00 heroku[run.9335]: Process exited with status 0 2021-01-21T11:07:29.316386+00:00 heroku[run.9335]: State changed from up to complete 2021-01-21T11:11:12.413411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=afternoon-retreat-21879.herokuapp.com request_id=eea06fd9-83d9-49c9-93ae-80c64af88963 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https 2021-01-21T11:11:13.160682+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=afternoon-retreat-21879.herokuapp.com request_id=839aa9c7-f433-4e82-9fa3-a65fec8530d0 fwd="129.0.78.202" dyno= connect= service= status=503 bytes= protocol=https Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect... Connection to log stream failed. Please try again later. And below we … -
Where do i need to locate .well-known/pki-validation/xxxxxxx.txt/ file in Django project?
I using sslforfree to create a free SSL cert online and now i in the mid of verifying my host. How it works is: After creating , it need to verify my domain ownership before installing my certificates Verification method : HTTP File Upload First , i have download Auth file(xxxxxxyyyyzzzz.txt) Second , i have to upload my Auth file to my Http server under /.well-known/pki-validation/xxxyyyzzz.txt I just put a path in my urls.py in Django_Project as below: from core.views import read_file urlpatterns = [ path('.well-known/pki-validation/xxxyyyzzz.txt', read_file), ] Then my read_file function in djangoapp(core/view.py) just simply return the file with def read_file(request): f = open('.well-known/pki-validation/xxxyyyzzz.txt', 'r') file_content = f.read() f.close() return HttpResponse(file_content, content_type="text/plain") I have no idea where should i locate .well-known/pki-validation/xxxyyyzzz.txt in my django project in order to locate the file . when i runserver <domain.name>/.well-known/pki-validation/84F3E6FA7EADE957CBDBA27A78C8BAF0.txt it say filenot found (no such file or directory ) Please help . i really appreciate your help . -
Heroku Django app deployment fails after trying to install python requirement
I installed django-user-visit with pip install django-user-visit , tested it in my local environment and everything seems to work fine, but when i try to deploy my app to production with Heroku i get the following error : remote: Collecting django-cors-headers==3.6.0 remote: Downloading django_cors_headers-3.6.0-py3-none-any.whl (12 kB) remote: ERROR: Could not find a version that satisfies the requirement django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) (from versions: none) remote: ERROR: _No matching distribution_ found for django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed Does anyone know why Heroku can't find the package and if i can fix this ? My packages are being installed by running the libraries indicated in my requirements.txt file: asgiref==3.3.1 Django==3.1.5 django-cors-headers==3.6.0 django-user-visit==0.4.1 djangorestframework==3.12.2 gunicorn==20.0.4 psycopg2==2.8.6 pytz==2020.5 sqlparse==0.4.1 ua-parser==0.10.0 user-agents==2.2.0 whitenoise==5.2.0 What i've tried so far is to change the version to 0.4 and to not specify a version at all -
How can I use regex in django's Replace function
I'm trying to update all urls in my query by using django's update and Replace function using regex. Here's what I've tried so far but it seems like django's Value expression did not recognize my regex. from django.db.models import Value from django.db.models.functions import Replace Foo.objects.filter( some_url__iregex=r'^\/some-link\/\d+\/').update( some_url=Replace( 'some_url', Value(r'^\/some-link\/\d+\/'), Value('/some-link/'))) My goal is to remove all numbers after /some-link/ (e.g. /some-link/55/test to just /some-link/test) -
Django - Cannot get console.log to output in VSCode Terminal
I'm new to using Javascript with django and am trying to use console log to test my Javascript code but am having trouble getting it to work. I check the terminal, outpout, problems, and Debug console but none show the output of console.log. I know my javascript is working because the ui dropdown menu is populated when I use the ajax code below and it displays nothing if I remove it. However, I cannot tell if the event listener is working.. here is my html: <div class="ui selection dropdown" id = "cars"> <input type="hidden" name="car"> <i class="dropdown icon"></i> <div class="default text">Choose a car</div> <div class="menu" id = 'cars-data-box'> </div> </div> Here is my Javascript const carsDataBox = document.getElementById('cars-data-box') const carInput = document.getElementById('cars') $.ajax({ type: 'GET', url: '/cars-json/', success: function(response){ console.log(response) const carsData = response.data carsData.map(item=>{ const option = document.createElement('div') option.textContent = item.name option.setAttribute('class', 'item') option.setAttribute('data-value', item.name) carsDataBox.appendChild(option) }) }, error: function(error){ console.log(error) } }) carInput.addEventListener('change', e=>{ const selectedCar = e.target.value console.log(response) }) urls.py urlpatterns = [ path('', page), path('cars-json/', get_json_car_data), ] views.py def page(request): qs = Car.objects.all() return render(request, 'testenv/home.html', {'qs' : qs}) def get_json_car_data(request): qs_val = list(Car.objects.values()) return JsonResponse({'data' : qs_val}) -
heroku[router]: at=error code=H14 desc="No web processes running" (Deploying Docker Image)
So trying to deploy a docker image, these are my setting, and these are the errors i keep getting. I keep getting the error heroku[router]: at=error code=H14 desc="No web processes running". I've installed posgres plugin on heroku and also have a dynos active. docker-compose.yml: version: "3" services: {redacted}: build: context: . ports: - "8000:8000" volumes: - .:/{redacted} command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST={redacted} - DB_NAME={redacted} - DB_USER={redacted} - DB_PASS={redacted} depends_on: - db db: image: postgres:12-alpine environment: - POSTGRES_DB={redacted} - POSTGRES_USER={redacted} - POSTGRES_PASSWORD={redacted} Dockerfile: FROM python:3.8-alpine MAINTAINER {redacted} ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /{redacted} WORKDIR /{redacted} COPY . /{redacted} RUN adduser -D user USER user requirements.txt: asgiref==3.2.10 beautifulsoup4==4.9.1 bootstrap4==0.1.0 certifi==2020.6.20 chardet==3.0.4 dj-database-url==0.5.0 djangify==1.0.0 Django==3.1 django-bootstrap4==2.2.0 django-crispy==1.8.1 django-filter==2.4.0 django-heroku==0.3.1 django-i18n==1.0.4 djangorestframework==3.12.1 djangorestframework-simplejwt==4.6.0 flake8==3.8.4 gunicorn==20.0.4 heroku==0.1.4 idna==2.10 mccabe==0.6.1 psycopg2==2.8.5 psycopg2-binary==2.8.6 pyclean==2.0.0 pycodestyle==2.6.0 pyflakes==2.2.0 PyJWT==2.0.1 python-dateutil==1.5 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 slugify==0.0.1 soupsieve==2.0.1 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 settings.py: from pathlib import Path from datetime import timedelta import django_heroku import os # Build paths inside … -
Django saving the registration extends AbstractBaseUser
Good day SO. I am new to Django and having troubles with something basic. When I click on sumbit, the template returns my Account(the OneToOneField) This field is required. Though my methods might be not aligned with good practice, but I hope that you can help me with this. I have been trying to check with other resources for two days but I can't seem to find the solution to my concern. Here is my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Account, CompanyAccount class AccountCreationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text="Required") class Meta: model = Account fields = ("email", "username", "password1", "password2", "account_type") class CompanyAccountForm(forms.ModelForm): class Meta: model = CompanyAccount fields = "__all__" my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, account_type, password): if not email: raise ValueError("Users must have an Email Address") if not username: raise ValueError("Users must have an Username") if not account_type: raise ValueError("Users must have an Account Type") user = self.model( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, account_type, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.is_admin = True user.is_staff … -
Flask or Django Framework Livestream
how can i get livestream on yt etc. with API with on flask or django to my website i want to add livestream for example tv stream, i researched but i didnt find anything on google. how can i get this can u help me ? For example I reserved a certain area for live broadcast on my website, I add live broadcast stream to that area, but I want to broadcast live broadcast on my site, for example youtube or twitch api on the internet, not webcam broadcast. #!/usr/bin/env python from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) This is not what I want. -
composite key not displaying orrecyl on django admin
I have an intermediary model betwen "estados" e "listaflor", the flora2estado uses a composite key- and a primary key to trick django not to throw errors at me-. When i click in one object at django admin i get this error: MultipleObjectsReturned at /admin/accounts/flora2estado/99/change/ get() returned more than one Flora2Estado -- it returned 5! my models.py class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'estados' class Familia(models.Model): familia_id = models.AutoField(primary_key=True) familia_nome = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'familia' class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, ) especie_id = models.IntegerField() flora2estado_id = models.AutoField( primary_key=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) admin.py admin.site.register(Flora2Estado) -
How to make a variable number of fields in django models?
I want to make a model of Grades of students and this model has a variable number of fields that I can change from the admin page. -
django: FileField model - 404
This is my first Django project and I have one problem. file1 is saved to media folder\files however when I try to download the file I'm getting 404. Any help is appreciated! 127.0.0.1:8000/about/files/2021/01/22/pyqt_tutorial_EB2ZapN.pdf models.py class Links(models.Model): file1 = models.FileField(upload_to = 'files/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html {% for link in links %} <div class="links1"> <h3><a href = "{{ link.file1 }}">Download Link</a></h3> <p>{{ link.publish_date }}</p> </div> {% endfor %} urls.py> urlpatterns = [ path('admin/', admin.site.urls), path('about/', about, name = 'about') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py> # Media Folder Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Update: from the admin panel if I click on the link I can see it. Maybe In the {{ link.file1 }} url something need to be changed? -
How do I import a model from another app in Django?
So in my project book_letter, I have an app named contents. Inside it, I have a model named Book. As below. class Book(models.Model): objects = models.Manager() title = models.CharField(max_length = 30) author = models.CharField(max_length = 20) def __str__(self): return self.title And I have another app named recommendation, with a model named Recommendation. As below. from book_letter.contents.models import Book class Recommendation(models.Model): objects = models.Manager() source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE) However, when I run python manage.py runserver, I get an error saying ModuleNotFoundError: No module named 'book_letter.contents' I don't see what I've done wrong. Any ideas? Thanks :) -
Django: Group by foreign key then get max id from group
I'm looking to grab the latest message in a conversation. My conversation model has attributes id (primary key) and user1 and user2, which are both foreign keys to a User model. My message model consists of a conversation(foreign key) and message primary key. These both just return only the very latest message. Message.objects.values('conversation').latest('id') Message.objects.order_by('conversation').latest('id') Any recommendations for getting this query?