Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get 5 quotes from page?Bs4
there is my script: @shared_task() def parser(): flag = True url = 'https://quotes.toscrape.com' suffix = '' while flag: responce = requests.get(url + suffix) soup = BeautifulSoup(responce.text, 'html.parser') quote_l = soup.find_all('span', {'class': 'text'}) q_count = 0 for i in range(len(quote_l)): if q_count >= 5: flag = False break quote = soup.find_all('span', {'class': 'text'})[i] if not Quote.objects.filter(quote=quote.string).exists(): author = soup.find_all('small', {'class': 'author'})[i] if not Author.objects.filter(name=author.string).exists(): a = Author.objects.create(name=author.string) Quote.objects.create(quote=quote.string, author_id=a.id) q_count += 1 else: a = Author.objects.get(name=author.string) Quote.objects.create(quote=quote.string, author_id=a.id) q_count += 1 next_page = soup.find('li', {'class': 'next'}) if not next_page: flag = False break suffix = next_page.a['href'] I need to get 5 new quotes in one run of the program, but I get 5 only on the first run, and on the other 10.tried to change the nesting nothing helped.what do you advise? -
pandas set_index not working as expected for multiple columns
df = pd.DataFrame( [[21, 'Amol', 72, 67], [21, 'Amol', 78, 69], [21, 'Kiku', 74, 56], [22, 'Ajit', 54, 76]], columns=['rollno', 'name', 'physics', 'botony']) print('DataFrame with default index\n', df) Then when we do this: df = df.set_index(['rollno','name']) print('\nDataFrame with MultiIndex\n',df) The output we get is: DataFrame with MultiIndex physics botony rollno name 21 Amol 72 67 Amol 78 69 Kiku 74 56 22 Ajit 54 76 What I want is: physics botony rollno name 21 Amol 72 67 78 69 Kiku 74 56 22 Ajit 54 76 So the set_index is grouping the first column of 'rollno' but not the second column of 'name' how can I get this? Context: I'm doing this to covert pandas df to html with rowspans for first 2 columns -
Pass jquery variable to img src static in Django template
I am getting a list of file names (they are .jpg images) from a django view as an Ajax response. I want to append each image to a div (with id grid). Below is the code: success: function(response) { var state = response.state; var piclist = response.pics.toString(); var pics = piclist.split(','); // alert(pics); for (var i=0; i < pics.length; i++) { // alert(pics[i]); // var fname = state + '/' + pics[i]; // var fpath = "{% static '" + fname + "' %}"; // alert(fpath); $('#grid').append( "<div class='col-md-2 mb-2 posr'>" + "<input type='checkbox' class='custom-control-input chk pos-ab'>" + "<img src='{%static fpath %}' class='img-thumbnail'>" + "</div>" ); } } I am unable to pass the file path variable ts/pics[i] to img src static. I tried Jquery template literals too but that also didnt work. How to pass the filepath variable? -
uvicorn access denied to run django server
I'm just trying run the server via uvicorn package. installed it with pip and fire this command to run that : uvicorn my_project.asgi:application --reload but it's not working and return access denied error here is full error message : Program 'uvicorn.exe' failed to run: Access is deniedAt line:1 char:1 + uvicorn my_project.asgi:application --reload At line:1 char:1 + uvicorn my_project.asgi:application --reload + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed Note: I run this command in both vscode and git bash. the result is the same! any point? -
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile:
I'm doing a personal full-stack project just for practice but I keep getting this error for the docker commands after I try to run these docker commands as I am trying to build some microservices in separate containers. I run these commands: docker volume create tren-data docker compose build and I get this error. failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount3296053497/Dockerfile.dev: no such file or directory docker error message This is what I wrote for my docker.yaml file. I would like to know and understand where I am going wrong with this. I had already premade each of the microservices already with the django and I believe it's with how I am making my docker file. volumes: ghi: external: true tren-data: external: true services: react: image: node:lts-bullseye command: /bin/bash run.sh working_dir: /app volumes: - ./ghi:/app ports: - "3000:3000" environment: HOST_OS: ${OS} NODE_ENV: development HOST: "0.0.0.0" NUTRITION_APP_API_KEY: ${NUTRITION_APP_API_KEY} WORKOUT_APP_API_KEY: ${WORKOUT_APP_API_KEY} REACT_APP_NUTRITION_HOST: http://localhost:8091 REACT_APP_WORKOUTS_HOST: http://localhost:8080 REACT_APP_ACCOUNTS_HOST: http://localhost:8090 REACT_APP_GYMS_HOST: http://localhost:8081 database: build: context: ./relational-data dockerfile: ./Dockerfile.dev volumes: - tren-data:/var/lib/postgresql/data environment: - POSTGRES_MULTIPLE_DATABASES=accounts,gyms,nutrition,workouts - POSTGRES_PASSWORD=test-databases ports: - 15432:5432 workouts-api: build: context: ./workouts/workouts_rest dockerfile: ./Dockerfile.dev ports: - "8080:8000" volumes: - … -
Unable to get activation E-mail in django
I am trying to get an activation email from Django but have not received any email. Now less secure app access is now banned from google so I created an app password which was advised by the youtube channel but I still not get the output here are my tables: Views.py from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.shortcuts import redirect, render from django.utils import timezone from django.core.mail import send_mail, EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_encode , urlsafe_base64_decode from .tokens import generate_token def Register(request): if request.method=='POST': # username=request.POST.get('Username') username=request.POST['Username'] password=request.POST['Password'] Fname=request.POST['Fname'] Lname=request.POST['Lname'] Email=request.POST['Email'] PhoneNo =request.POST['PhoneNo'] Age=request.POST['Age'] if User.objects.filter(username=username): messages.error(request,"Username already exits! Please try some other username.") if User.objects.filter(email=Email): messages.error(request,"Email ID already exits! Please try some other Email ID.") myuser =User.objects.create_user(username,Email,password) myuser.first_name=Fname myuser.last_name=Lname myuser.save() messages.success(request,"Your Account has been successfully created. We have sent you a confirmation email, please confirm your email to activate your account.") #Welcome Email subject ="Welcome to the largest Community of art" message="Hello there!! "+ Fname+"\nWelcome to some place where you can share your art ,learn about different forms of art and teach your creative … -
how to add variable in django url in a loop so for each entry the url changes
im new to django i created a loop which lists all entries on a page. but i can't add a variable which will link the name of the entry to it's html page without having to hardcode it. index.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href= "{% url "{{entry}}" %}">{{entry}}</a></li> {% endfor %} </ul> {% endblock %} my views.py from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def html(request): return render(request, "encyclopedia/html.html") def css(request): return render(request, "encyclopedia/css.html") -
Pass select element to json
How do I make it pass the selected element to javascript. I managed to make it appear to select but when saving it is not going. Appedit.html <div class="modal fade edit-modal1" id="modaledit1" tabindex="-1" role="dialog" aria-labelledby="modaledit1label" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modaledit1label">Update Appointment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="updateappointment" action=""> <div class="modal-body"> {% csrf_token %} <label for="doc" >Doctor</label> <select class="select_doctor" name="select_doctor"> {% for user in users %} <option id="form-doc" value="{{user.id}}" name="formDoc" class="form-control">{{user.username}}</option> {% endfor %} <label for="date" >Date</label> <input class="form-control" id="form-date" type="date" name="formDate"/> <label for="time">Time</label> <input class="form-control" id="form-time" type="time" name="formTime"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary" id="saveappointment">Save</button> </div> </form> </div> </div> </div> script.js function updatepatielement(element){ element.addEventListener("click", function(event) { event.preventDefault(); $('#modaledit1').on('show.bs.modal', () => { var saveButton = document.querySelector(".modal-footer > #saveappointment"); tr_id1 = null; date = null; time = null; id = element.getAttribute("idappointment"); if (id) { tr_id1 = "#appointment" + id; doc1 = $(tr_id1).find(`#DocName${id}`); date1 = $(tr_id1).find(`#AppoiDate${id}`); time1 = $(tr_id1).find(`#AppoiTime${id}`); $('#form-doc').val(doc1); $('#form-date').val(date1); $('#form-time').val(time1); } saveButton.addEventListener("click", () => { var docselect = $('option[name="formDoc"]').val(); var dateInput = $('input[name="formDate"]').val(); var timelInput = $('input[name="formTime"]').val(); console.log(docselect) $('#modaledit1').modal('hide'); fetch('/updateappointme/'+ id, { method: "POST", body: JSON.stringify({ doctor: docselect, date: dateInput, time: timelInput, }), … -
Django : One to Many serializer attribute error
Hello i have one to many model serializer but when I try to make request on it it says attribute error. Got AttributeError when attempting to get a value for field `project` on serializer `clientserializers`. The serializer field might be named incorrectly and not match any attribute or key on the `Client` instance. Original exception text was: 'Client' object has no attribute 'projectname' My model : # client structure class Project(db.Model): project_name = db.CharField(max_length=50, unique=True) def __str__(self): return self.project_name class Reason(db.Model): reason_name = db.CharField(max_length=50, unique=True) def __str__(self): return self.reason_name class Client(db.Model): name = db.CharField(max_length=100) project = db.ForeignKey(Project, on_delete=db.CASCADE, related_name="projectname") reason = db.ForeignKey(Reason, on_delete=db.CASCADE, related_name="reasonname") timestamp = db.DateTimeField(default=timezone.now()) Serializer both for project and reason: class projectserializers(serializers.ModelSerializer): class Meta: model = Project fields =('id', 'project_name') class reasonserializers(serializers.ModelSerializer): class Meta: model = Reason fields =('id', 'reason_name') class clientserializers(serializers.ModelSerializer): project = projectserializers(source="projectname", many=True) reason = reasonserializers(source="reasonname", many=True) class Meta: model = Client fields = ('id', 'name', 'timestamp', 'project', 'reason') -
How do I merge and sort JSON objects using its counts?
I got two json objects that I need to combine together based on ID. here is the first object comments: and here is the second object: { { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, { "userId": 1, "id": 4, "title": "eum et est occaecati", "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit" }, } this is second json object: { { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": … -
How can I have a query set in the DetailView?
Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x1024f3c70>. This is the error message and class ProductDetail(DetailView): model = Product def get_context_data(self, **kwargs): context = super(ProductDetail, self).get_context_data() context['related_products'] = Product.objects.filter(category=Product.category) context['categories'] = Category.objects.all() context['no_category_post_count'] = Product.objects.filter(category=None).count return context This is my views.py. A page that shows a product and related items is what I want to present. My questions are 1. Am I not allowed to bring a query set in the DetailView? 2. Then should I use ListView to do so? -
Overwrite/replace instead of update MySql table in a Django Project
Let's say I have df1 which is pulled from a MySql database in a django project: import pandas as pd df1 = pd.DataFrame({'Name': ['John', 'Jim'] ,'City': ['A', 'B'],'Project_id': 1}) df1 Then my function within django adds two rows: line_insert = pd.DataFrame({'Name': ['Jack', 'Jill'] ,'City': ['C', 'D']}) df1 = df1.append(line_insert).reset_index(drop=True) df1 Now i would like to save this dataframe back to the table in the database. My current code updates the sql table row by row (where Project_id = 1) but i am wanting to replace the dataframe with the same Project_id My current code to update the table is (for simplistic sake i have defined some variables first): proj_id = 1 iincreament_id = 1 for index, df_series in df1.iterrows(): dict_df = df_series.to_dict() """ Insertig dataframe into dict """ dict_df['Projectid_id'] = proj_id """ updating SQL DB """ sql_db.objects.filter(id=iincreament_id,Project_id=proj_id).update(**dict_df) iincreament_id += 1 So what this does is updates row 1 & 2 values with their new values but does not replace the sql table with the new table to bring in rows 3 & 4. Is there any ideas on a replace function using the .objects functions with python/django? Thanks very much! -
Why is Django Rest Knox token don't have three sections?
I am new to JWT and integrated django-rest-knox to my project. When I test it in postman, i get a token like b0073060117223714a3405ad7c1516ba61f7216b2165a40cb44b43b2c54d8dd4, but I know that JWT must have 3 sections. Why it don't have ones? -
How do I subtract from exiting model if a request is sent from another model?
Am trying to create a withdrawal request, the request sent successfully as expected but it doesn't subtract from the existing balance. Here's my model. def withdrawals(request): if request.method == 'POST': Input_Amount = request.POST['Input_Amount'] username = request.POST['username'] input_password = request.POST['password'] total = Users_Balanc.objects.get(user=request.user) if Withdrawal_password.objects.filter(username=request.user).exists(): password = Withdrawal_password.objects.get(username=request.user) if password.password3 == input_password: if int(Input_Amount) > 100: if (total.Amount >= float(Input_Amount)): New_Request = Request.objects.create(Wallet_Address=password.Wallet_Address, Amount=Input_Amount, user = username) New_Request.save messages.success(request, 'Successful') return redirect('withdrawals') else: messages.warning(request, 'Insufficient funds') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal is below 100TRX') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal password is not correct') return redirect('withdrawals') else: messages.warning(request, 'Sorry, you haven\'t create a withdrawal password yet.') return redirect('withdrawals') else: balance = Users_Balanc.objects.filter(user=request.user) return render(request, 'withdrawals.html', {'balance': balance}) Even when I add total.Amount - Input_Amount just after if (total.Amount >= float(Input_Amount)) Please what's the way around this? -
Django - Reset all filters
I am trying to clear all filters on button click at once. This is what I have on filters.py file and filters class: class Filters(django_filters.FilterSet): id = django_filters.NumberFilter(label=_("ID")) name = django_filters.TextFilter(label=_("Name")) And in base template: <form id="filters-filters-form" action="javascript:;" onsubmit="onSubmit(this)" class="form form-inline main-filter"> {% bootstrap_form filter.form layout='inline' %} <div> <button class="btn ml-auto mr-2" onclick="resetFilters()">Clear all</button> {% trans "Apply" as button_text %} {% bootstrap_button button_text button_class="btn-primary" %} </div> </form> resetFilters() function: var resetFilters = function() { let formId = document.getElementById('filters-form') let formChildren = formId.childNodes; Array.from(formChildren).forEach(formChild => { formChild.val(null).trigger('change') }); } Is there any easy way to reset all filters? P.S: I need to reset these filters without any id of form-control because it will be reusable base template -
Forward reference must be an expression -- got 'postgresql
I am getting this error Forward reference must be an expression -- got 'postgresql Here is the complete log Traceback (most recent call last): File "/usr/local/lib/python3.9/typing.py", line 528, in __init__ code = compile(arg, '<string>', 'eval') File "<string>", line 1 postgresql+asyncpg://postgres:postgres@db:5432/blog ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/asgi.py", line 3, in <module> from api.app import create_app File "/code/api/app.py", line 2, in <module> from api.database import create_db_and_tables File "/code/api/database.py", line 3, in <module> from api.config import settings File "/code/api/config.py", line 8, in <module> class Settings(BaseSettings): File "/usr/local/lib/python3.9/site-packages/pydantic/main.py", line 179, in __new__ annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) File "/usr/local/lib/python3.9/site-packages/pydantic/typing.py", line 395, in resolve_annotations value = ForwardRef(value, is_argument=False, is_class=True) File "/usr/local/lib/python3.9/typing.py", line 530, in __init__ raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") SyntaxError: Forward reference must be an expression -- got 'postgresql+asyncpg://postgres:postgres@db:5432/blog' Here is how I am using it class Settings(BaseSettings): PROJECT_NAME: str = f"SQLModel API - {os.getenv('ENV', 'development').capitalize()}" DESCRIPTION: str = "A FastAPI + SQLModel production-ready API" ENV: str = os.getenv('ENV', 'development') VERSION: str = "1" SECRET_KEY: str = secrets.token_urlsafe(32) # DATABASE_URI: Optional[PostgresDsn] = None DATABASE_URI: os.environ.get("DATABASE_URL") # sql Where env variable is being set like … -
Html code is not working in django block content
i understand the basic tag blocks but it didn't works well on my page. i have page called base.html and home.html **base.html !DOCTYPE html> <html> <body> {% include 'component/models.html' %} {% include 'component/header.html' %} {% block content %} inside this my code is not comming {% endblock %} {% include 'component/footer.html' %} </body home.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>This code working <h1> <section> <h1>Rahul guptaa1</h1> <div> <h1>Rahul guptaa 2</h1> <div> <h1>Rahul guptaa 3</h1> <div> <h1>Rahul guptaa4</h1> </div> <div> <h1>Rahul guptaa5</h1> </div> </div> </div> <div> <h1>Rahul guptaa6</h1> </div> </section> {% endblock content %} **my output below but Rahul guptaa4 Rahul guptaa6 is not showing ... Rahul guptaa5 Learn On Your Schedule Technology Is Bringing A Massive Wave Of Evolution On Learning Things In Different Ways. ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa5 *** i am not beginner in django but i face problem here i try so many times if you want to know my folder structure below myproject -myproject -App -templates -base.html -main -home.html ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa4 Rahul guptaa5 Rahul guptaa6 ** -
Redirect non authenticated user to login page (for all views)
I am looking to redirect my user to login page, if they have not logged in. I initally looked at the decorator @login_required(login_url='/accounts/login/'). But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth. I am sure this is solvable, but I am looking for a solution that could apply to all views. I found something using authmiddleware(doc: https://pypi.org/project/django-authmiddleware/). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything. Can someone see what I am doing wrong? base.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'AuthMiddleware.middleware.AuthRequiredMiddleware', ] AUTH_SETTINGS = { "LOGIN_URL" : "login_user", "DEFAULT_REDIRECT_URL" : None, "REDIRECT_AFTER_LOGIN" : False, } views.py from django.shortcuts import render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.urls import reverse class AuthRequiredMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login_user')) return None -
django: unable to login after successful registration
login reporting wrong username or password, after a new user is registered successfully. I am sure the there is no typo! below is my code and I guess the problem is to do with the hash code related to the password setup? @csrf_exempt def api_register(request): data = json.loads(request.body) username = data['username'] password_1 = data['password_1'] password_2 = data['password_2'] # 1,check if two pw is same if password_1 != password_2: return JsonResponse({"code": 0, "msg": "pw not consistant"}) else: m = hashlib.md5() m.update(password_1.encode()) password_m = m.hexdigest() # 2 check if username exists users = User.objects.filter(username=username) if users: return JsonResponse({"error": "username already exists"}) else: try: user = User.objects.create_user(username = username, password = password_m) user.set_password(password_m) user.save() user.is_active = True user.success = True ret_data = {"username": user.username, 'uid': user.id, 'password': user.password} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code": 1, "msg": ret_data} except Exception as e: print('--create user error is %s' % e) return JsonResponse({"error": "username already exists"}) return JsonResponse(ret) below is login function @csrf_exempt def api_login(request): data = json.loads(request.body) user = authenticate(**data) #same as authenticate(username=data['username'],password=data['password'] if user: ret_data = {"username":user.username,'uid':user.id} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code":1,"msg":ret_data} print("ret ", ret) else: ret = {"code":0,"msg":"username or password wrong!" } return JsonResponse(ret) -
"No module named manage" error when trying to debug a Werkzeug Django app in VSCode
As the title says. I have a Django app, which uses Werkzeug to enable https. I have the following launch.json set up: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "python": "${workspaceFolder}/venv/Scripts/python.exe", "program": "${workspaceFolder}\\appname\\manage.py", "args": [ "runserver_plus", "--cert-file", "${workspaceFolder}/certs/cert.pem", "--key-file", "${workspaceFolder}/certs/key.pem" ], "justMyCode": false, "django": true } ] } When I run this through the VSCode debugger it immediately quits in the get_wsgi_application() function with "No module named manage". I tried googling around, but no answer proved to be useful. Any ideas what I am doing wrong? -
MultiValueDictKeyError at /"" when uploading empty file
I have a django 4 application and if a a user try to upload a empty file, then this error occurs: MultiValueDictKeyError at /controlepunt140 'upload_file' I searched for that error. But it seems that the template is oke. Because the enctype is set correct: enctype="multipart/form-data" <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group">{% csrf_token %} {{form}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> </form> and views.py: def post(self, *args, **kwargs): filter_text = FilterText() extract_excel_instance = ExtractingTextFromExcel() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(self.request.POST, self.request.FILES) content = '' content_excel = '' if self.request.POST.get('form_pdf') is not None: if submitted_form.is_valid() and self.request.POST: uploadfile = UploadFile( image=self.request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(self.request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(self.request, "main/controle_punt140.html", { "form": submitted_form, }) and forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField(required=False) So how to tackle this? -
DJANGO - Unique records via ORM
I'm new to DJANGO and was hoping to get some help achieving this. I've been stuck on this for a few weeks trying out multiple answers found in StackOverflow, but no luck... Any help or guidance will be appreciated. Issue: As a business case, I need to collect all raw data (order updates). Because daily updates of the same order are provided daily and stored; we start accumulating a lot of duplicate data with different import dates. Objective: To create a table view that displays only the changes per order via ORM if possible. Disclaimer: I have achieved the desired result by handling the dataset through pandas. not in a postgres thus, thus distinct() doesn't work models.py OrderUpdates(models.Model): import_date = models.DateField(auto_now=False, auto_now_add=False) order_number = models.CharField(max_length=15,unique=False) field1 = models.CharField(max_length=25,unique=False) Sample Expectation: *RAW DATA* import_date order_no field1 10/30/22 A raw 10/30/22 B raw 11/01/22 A raw 11/01/22 B raw 11/02/22 A updated 11/03/22 B raw 11/03/22 A updated 11/03/22 B raw *UNIQUE VIEW* import_date order_no field1 10/30/22 A raw 11/02/22 A updated 10/30/22 B raw Approach: My current approach is as follows: Query the object > create a composite key > order by composite key and import date > get a count … -
Apache doesn't allow access to media files
I'm trying to set up my Apache so it can serve media files saved inside a Django Backend. Django is already in production mode (DEBUG=False) and I have SSL set up. I have one domain with a reverse proxy serving my frontend and a subdomain (api.domain) serving my Django backend. I'm now trying to serve my media files in backend/app/media/ from apache. My subdomain ssl .conf file in sites-available contains the following code inside the <VirtualHost *:433>: Alias /media/ /home/backend/main/media/ <Directory /home/backend/main/media> Options Indexes MultiViews AllowOverride None Require all granted Order allow,deny Allow from all </Directory> I tried this code block also inside my apache2.conf file but that didn't work either. Also worth mentioning, I don't get the default Apache "Service Unavailable" error when trying to access the files via the browser. I get (only if the Django Server runs) the Django production "Not Found" view. Therefore I guess it handles my request via Django which is expectable since I'm accessing the api subdomain serving Django. How can I manage to access my files served by Apache? When trying to access my domain, I get forwarded to my frontend and when trying it via the subdomain, I get forwarded to … -
How to automatically get user in django admin through form
I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves. Here's the model.py file: class Requestpayment (models.Model): username= models.ForeignKey(User, on_delete= models.CASCADE, null=True) useremail= models.CharField(max_length=100) accountmail= models.CharField(max_length=100) accountphonenumber=models.CharField(max_length=15) coinsrequested=models.ForeignKey(Requestamount, on_delete= models.SET_NULL, null=True) created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.accountmail the forms.py: class Requestpaymentform (ModelForm): class Meta: model = Requestpayment fields = '__all__' and the views.py: @login_required(login_url='login') def redeemcoins (request): form = Requestpaymentform if request.method =='POST': form = Requestpaymentform(request.POST) if form.is_valid(): form = form.save(commit=False) username = request.user form.save() return redirect ('home') I am pretty sure something is wrong but i don't know what it is (I'm very new at django) anyway the form always shows all the users in the website for the current user to pick who they are. enter image description here I also tried excluding that part of the form but it didn't work it just shows up empty in the admin. thank you. -
How to ADD registration email verifiction to my Django app
How to ADD registration email verifiction to my django app? I want to add an email registration verification and email and password reminder? my big problem solving