Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to use ProxyPass to replace certain pages of static site
I have a legacy static site that I host on apache. Over time I have needed to add dynamic features to that site so I installed Django and configured it via WSGIDaemonProcess but my understanding was that it would need to be in a subfolder (ie. /django-stuff/*). But now there are some legacy pages (ie. /legacy-important-page.html) that were in the root folder that I would like to replace with a dynamic route. I know that I can use ProxyPass to reroute a single url (ie. ProxyPass "/legacy-important-page.html" "https://www.example.com/django-stuff/legacy-important-page") or use a redirect. But is there a way to have Apache configured to check if a static file exists, otherwise use a dynamic route? Or another way to accomplish what I'm looking for? If there is another web server that accomplishes it I would be open to that as well. -
How to set StaticLiveServerTestCase to work with websockets
I am currently creating a test using behave and StaticLiveServerTestCase to spin up a runserver, and for some reason I can't connect to my websocket url I am not sure if channels are supported in StaticLiveServerTestCase and if there is a manual way to do this. This is my current codebase: import os import django from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.shortcuts import resolve_url from django.test.runner import DiscoverRunner os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings_test" django.setup() def before_all(context): context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() context.test = StaticLiveServerTestCase context.test.setUpClass() context.base_url = context.test.live_server_url def after_all(context): context.test.tearDownClass() del context.test context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() -
How to create a table from json data?
I have a json format data and I want to create a table from that. I can take values and display them correctly. But when I create a table it is not working as what I want. My data returns as rows but I want to every array should be column. It is my table: And this is like what I want: Here are my codes: views.py def test_fin(request): data_test = json.loads(json_bss_test) test_data = [] test_1 = data_test['Assets'] test_2 = data_test['Unnamed: 1'] test_3 = data_test['Unnamed: 2'] test_4 = data_test['Unnamed: 3'] test_5 = data_test['Unnamed: 4'] test_6 = data_test['Unnamed: 5'] test_data.append(test_1) test_data.append(test_2) test_data.append(test_3) test_data.append(test_4) test_data.append(test_5) test_data.append(test_6) table_headers = [] column_1_bss_header = data_bss_header["Unnamed: 1"] column_2_bss_header = data_bss_header["Unnamed: 2"] column_3_bss_header = data_bss_header["Unnamed: 3"] column_4_bss_header = data_bss_header["Unnamed: 4"] column_5_bss_header = data_bss_header["Unnamed: 5"] for i in range(0, 1): table_headers = [column_1_bss_header, column_2_bss_header, column_3_bss_header, column_4_bss_header, column_5_bss_header] context = { 'test_data': test_data, 'table_headers': table_headers, } return render(request, 'fin_test.html', context) fin_test.html <table id="basic-datatables" class="display table table-bordered"> <thead style="background-color: #d9f6ef"> <th>in Millions USD</th> {% for data in table_headers %} {% for x,y in data.items %} <th>{{ y }}</th> {% endfor %} {% endfor %} </thead> <tbody> {% for data in test_data %} <tr> {% for k,v in data.items %} <td>{{ … -
django raw sql in optimization?
I think my code is not very pythonnic ,How to optimize? code lamp_keys=["ids"] if len(lamp_keys) == 1: rsql = f""" SELECT * from brelation where source_key = '{lamp_keys[0]}' and target_concept='aaa' """ else: rsql = f""" SELECT * from brelation where source_key in {tuple(lamp_keys)} and target_concept='aa' """ robjs = RelationModel.objects.raw(rsql) if lame_keys length is 1,if use in must be error,for example: SELECT * from `brelation` WHERE source_key in ('xx',) and target_concept='aa' -
Why some data are missing in postgres database while working with django?
In views.py of django_project I've defined the following, def register(request): uname = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] user = User.objects.create_user(username=uname, first_name=fname, last_name=lname, email=email, password=pass1) user.save() And the template goes as, <form method="POST"> <div> <input type="text" name="username" id="username" required=""/> </div> <div> <input type="text" name="fname" id="fname" required=""/> </div> <div> <input type="text" name="lname" id="lname" required=""/> </div> <div> <input type="text" name="email" id="email" required=""/> </div> <div> <input type="password" name="pass1" id="password" required=""/> </div> <div> <input type="submit" formaction="register" value="Register" /> <a href="/login/">Back to Login Page</a> </div> </form> This only saves username, password and first_name in the database, the rest (last_name,email) are ignored. How to store all the data in the postgres database. -
How to call function in another python project from django views?
I have a python project which will open connection, and will update database forever until connection is closed (will run in infinite loop as long as connection is alive). Now this has to be initialized from django views once the user lets say clicks start in the UI. It works perfect if I just import those functions in the views. But the problem is if django is stopped it destroys all the objects as well meaning it stops background database update work as well. How make the background work independent of django but the initialization should happen from UI ? Flow is like this : Start the Django Server Ask User to Initiate by clicking start button Call the function which will run forever to update database (independent of django server) Even django is closed background update should happen Help me to solve the above problem. Thanks -
django.template.library.InvalidTemplateLibrary: Invalid template library specified in Django3.2
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning' from 'django.utils.deprecation' (C:\Users\Gokul\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\deprecation.py) I'm getting this error, after i update django to 3.2! Any possible solutions would be helpful. Thanks in advance! -
Django related model not updating on form submission
How do I update a non existing related object through Django model forms ? I have two objects: Participant and Emergency. Emergency is a child of participant like if run the query: participant = ParticipantInfo.objects.get(pk = prk) I can access emergency = participant.emergency. I cannot update emergency with data from a form using a POST request. Can anyone help me please. Thanks Here's my models.py for clarity. models.py class EmergencyInfo(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=50) email = models.EmailField(max_length=100, blank=True, verbose_name="Emergency Contact Email") relationship = models.CharField(max_length=100) class ParticipantInfo(models.Model): first_name = models.CharField(max_length=100) middle_initial = models.CharField(max_length=1, blank=True) emergency = models.ForeignKey(EmergencyInfo, on_delete = models.CASCADE, editable= False, null=True, blank=True) views.py def update_participant(request, pk): # this function comes after update_specific if request.method == "GET": forms = get_participant_form_data(pk) context = {'forms': forms, 'pk': pk} return render(request, 'core/participantinfo_update_form.html', context) if request.method == "POST": return update_specific_form(request, pk) def update_specific_form(request, pk): participant = ParticipantInfo.objects.get(pk = pk) # if the object didn't exist create it like normal if participant.emergency is None: emergencyform =EmergencyForm(request.POST) if (emergencyform.is_valid): emergencyform.save() messages.success(request, 'saved') return redirect(request.path_info) # if the object exists, update it if participant.emergency is not None: emergencyform = EmergencyForm(request.POST, instance = participant.emergency) if (emergencyform.is_valid): emergencyform.save() messages.success(request, 'saved') return redirect(request.path_info) -
Why "pipenv install requests" command on windows powershell is showing error?
I have already installed python's latest version and pipenv on Windows Powershell. When I try to install requests it is showing this error: FileNotFoundError: [WinError 2] The system cannot find the file specified ValueError: Not a valid python path: 'C:/ProgramData/Anaconda3/python.exe' Full error code: Traceback (most recent call last): File "C:\Python39\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 618, in parse_executable result_version = get_python_version(path) File "C:\Python39\Lib\site-packages\pipenv\vendor\pythonfinder\utils.py", line 105, in get_python_version c = subprocess.Popen(version_cmd, **subprocess_kwargs) File "c:\python39\lib\subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "c:\python39\lib\subprocess.py", line 1420, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python39\Scripts\pipenv.exe\__main__.py", line 7, in <module> File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 782, in main rv = self.invoke(ctx) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\decorators.py", line 73, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 610, in invoke return … -
Nginx Bad Request (400) only with domain name not with IP (gunicorn and django)
I know many others have asked the same question, but I haven't found any answers that are relevant or work for me. If you do know of a duplication, feel free to direct me to it.. I'm getting lost in the maze of nginx threads! I am new to this and used the following tutorials to set up my django site with gunicorn and nginx: https://vahiwe.medium.com/deploy-django-and-flask-applications-in-the-cloud-using-nginx-gunicorn-and-systemd-centos-7-4b6aef3a8578 https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 My website works if I access it via the IP address but I get a Bad Request error when I try by the domain name. In nginx.conf my server block looks like: server { listen 80; server_name 123.456.78.910 mywebsite.com www.mywebsite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/userf/website; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/var/www/userf/website/website.sock; } } My gunicorn.service file is: [Unit] Description=gunicorn daemon After=network.target [Service] User=ssej91D Group=nginx WorkingDirectory=/var/www/ssej91D/pwebsite ExecStart=/var/www/userf/website/env/bin/gunicorn --workers 3 --error-logfile - --bind unix:/var/www/userf/website/website.sock website.wsgi:application EnvironmentFile=/var/www/userf/website/.env [Install] WantedBy=multi-user.target And my ALLOWED_HOSTS in django's settings.py: ALLOWED_HOSTS = ["mywebsite.com", "www.mywebsite.com", "123.456.78.910"] I have not added any SSL related settings to the Django settings file yet. To test the domain name, I've tried making a test index.html … -
Django model post_save
How do I insert new data to another models if the system detects the field is updated? for example i have two models FmCustomerEmployeeSupplier and TrCustomerEmployeeSupplierSubmittedRecords, this is the model //FmCustomerEmployeeSupplier class FmCustomerEmployeeSupplier(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] fmCustomerID = models.ForeignKey('FmCustomer',on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") email = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(null=True, blank=True) employee_number = models.CharField(max_length=500, blank=True, null=True) inputdate = models.DateField(auto_now_add=True) inputBy = models.CharField(max_length=500, blank=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def clean_name(self): return self.cleaned_data["employee_number"].upper() def save(self, force_insert=False, force_update=False): self.employee_number = self.employee_number.upper() super(FmCustomerEmployeeSupplier, self).save(force_insert, force_update) @property def is_past_due(self, *args, **kwargs): return date.today() > self.modifyDate //TrCustomerEmployeeSupplierSubmittedRecords class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] fmCustomerID = models.ForeignKey('FmCustomer',on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") email = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(null=True, blank=True) employee_number = models.CharField(max_length=500, blank=True, null=True) inputdate = models.DateField(auto_now_add=True) inputBy = models.CharField(max_length=500, blank=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) Storyline: the user updated the body temperature in FmCustomerEmployeeSupplier, i just want that in my models, i have a trigger when the system detect that the FmCustomerEmployeeSupplier updated, the record will insert in TrCustomerEmployeeSupplierSubmittedRecords. -
Django HttpOnly Cookies Not Persisting on Mobile Devices
My Django HttpOnly cookie is not persisting on mobile devices. I am creating the cookie like this: response.set_cookie( key=settings.SIMPLE_JWT['AUTH_COOKIE'], value=data["access"], expires=settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure=settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly=settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite=settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) with these settings: SIMPLE_JWT = { 'AUTH_COOKIE': 'access_token', # Cookie name. Enables cookies if value is set. 'AUTH_COOKIE_SECURE': True, # Whether the auth cookies should be secure (https:// only). 'AUTH_COOKIE_HTTP_ONLY': True, # Http only cookie flag.It's not fetch by javascript. 'AUTH_COOKIE_PATH': '/', # The path of the auth cookie. 'AUTH_COOKIE_SAMESITE': 'Strict', # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', or None to disable the flag. 'ACCESS_TOKEN_LIFETIME': timedelta(days=28) } This works perfectly fine on desktop browsers but these cookies don't persist for more than a few minutes on mobile browsers. How do I get the cookies to persist for 28 days on mobile devices? -
Behave failed on websocket test
I am currently working on test with behave, everything is working as intended but when I try to connect to a websocket I can't seem to connect and it returns 404. I have read at [https://github.com/behave/behave-django/issues/16][1] that I have to set up a channel backend. I tried using channels ChannelLiveServerTestCase instead of StaticLiveServerTestCase but all I got is connection refused as the error. I am not sure if I am doing it right since I'm just new to behave and channels. Below is my environment.py import os import django from django.contrib.staticfiles.testing import StaticLiveServerTestCase from channels.testing import ChannelsLiveServerTestCase from django.shortcuts import resolve_url from django.test.runner import DiscoverRunner os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings_test" django.setup() def before_all(context): context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() context.test = BehaviorDrivenTestCase() context.test.setUpClass() # This starts a transaction context.test() context.base_url = context.test.live_server_url class BehaviorDrivenTestCase(ChannelsLiveServerTestCase): serve_static = True """ Test case attached to the context during behave execution This test case prevents the regular tests from running. """ def runTest(*args, **kwargs): pass def test(self): self.live_server_url def after_all(context): context.test.tearDownClass() del context.test context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() -
Django Admin Theming
My Django admin dashboard is loading with a dark theme. I don't have any extensions for dark themes installed into my browser. How can I revert it to the light theme? Currently, my admin area is in this state: django admin image Any help would be greatly appreciated -
how can correct this to render list of data in page reactjs?
import axios from "axios"; import React, { Component } from "react"; class ArticleHome extends Component { constructor(props) { super(props) this.state = { articles: [], errorMessage: '', } } componentDidMount() { axios.get('http://127.0.0.1:8000/article/') .then(response => { console.log(response) }) .catch(error => { console.log(error) this.setState({ errorMessage: 'error retriving Data' }) }) } render() { const { articles, errorMessage } = this.state return ( list porps { articles.length ? articles.map(a => {a.id}{a.title}{a.slug}{a.updated_on}{a.content}) : null } {errorMessage ? {errorMessage} : null} ) } } export default ArticleHome; -
How to filter by nested field in Django
I'm working on a small project using Django Rest Framework, i have two models class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title This is my serializers : class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' class StatusSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True) class Meta: model = Status fields = '__all__' This is my view code : def list(self, request): objectSerializer = StatusSerializer(Status.objects.all(), many=True) return Response(objectSerializer.data) Until the moment I'm happy with the data structure that I have created, I would like now to create another function in my views to filter by the (contact) which is a foreign key as you can see -
Problem listing out 3rd level of data from my models effectively (Django)
I need to create a monitoring/summary view for the last 7 days of assurance data we collect on a daily basis. I have 3 models: Customer Equipment (The Customer's equipment) Stats (Daily data on performance, i.e. uptime percentage) In the views I'm filtering out the active customers and passing this to the template based on active equipment (remotes), and I'm also passing on the calculated date range (today's date -7 days). In the view I was easily able to list out the customer (name, parent's name) and the equipment data (serial number, installation date). But for the next level I'm really banging by head against the wall how to retrieve the Stats (uptime percentage) based on date and serial number of the equipment without some ugly nested for loops that runs the same query multiple times and makes the load take very long. The solution so far: for remote in remotes</br> # remotes bassed from the view <tr> <td>{{remote.parent}}</td> <td>{{remote.serial}}</td> <td>{{remote.install_date}}</td> for date in dates # dates passed from the view for stat in remote.stat_set.all|dictsortreversed:"date"|slice:":8" if date == stat.date: <td>Output the {{stat.percentage}} value</td> endif endfor endfor </tr> endfor I've made a hack with combining django and javascript in the template/html, … -
Django and Javascript - Like Button Not Working
I am new to Django and Javascript - I am making a project that has posts on a site, and I want to create a 'like' button on each post. So far here is my code - I am not getting any errors at all. No console errors in the browser either. But nothing happens. When you click the heart image, if it is liked, it should be a red image. When it is not liked, it is the white heart image. Currently when I click the image, it just stays white. It is always defaulting to that white image. The code doesn't work. Any help is appreciated. views.py for the like button: @csrf_exempt def like(request): if request.method == "POST": post_id = request.POST.get('id') is_liked = request.POST.get('is_liked') try: post = Post.objects.get(id=post_id) if is_liked == 'no': post.like.add(request.user) is_liked = 'yes' elif is_liked == 'yes': post.like.remove(request.user) is_liked = 'no' post.save() return JsonResponse({'like_count': post.like.count(), 'is_liked': is_liked, "status": 201}) except: return JsonResponse({'error': "Post not found", "status": 404}) return JsonResponse({}, status=400) views.py for the page to show all the posts: def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() paginator = Paginator(list_of_posts, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "list_of_posts": list_of_posts, "page_obj": page_obj }) Javascript … -
How send data from javascript-datatable to Django and after redirect to other url, People says ajax but i dont know use it very well
Please help, I have a Jquery datatable with checkable options, which are displayed through a List View, and I would like to send the selected options to Django and change the current URL after this, most people tell me to send the data by ajax, but I don't know how to do that part This is my table <table class="table display" id="table_selecting_formularios"> <thead> <tr> <!-- <th scope="col">#</th> --> <th></th> <th scope="col">Nombre</th> <th scope="col">Descripcion</th> <th scope="col">Subsistema</th> </tr> </thead> <tbody> {% for formulario in formularios %} <tr> <td></td> <td style="text-transform: uppercase;"> {{formulario.nombre_formulario}} </td> <td>{{formulario.descripcion_formulario}}</td> <td>{{formulario.subsistema_estadistico}}</td> </tr> {% endfor %} </tbody> </table> This is my class based view where in the post method i'd like grab the checked data from the table and then redirect to other url class SelectingFormulariosView(LoginRequiredMixin, generic.ListView): #? Y que modelo pongo aqui model = Formulario template_name = 'forms/publicacion/selecting_formularios.html' @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get_queryset(self): return Formulario.objects.all() def get(self, request, *args, **kwargs): context = self.get_context_data() return self.render_to_response(context) def post(self, request, *args, **kwargs): # print(request.POST['formularios[]']) # names = request.POST['formularios[]'] # # data = Indicador.objects.filter(formulario__nombre_formulario__in=names) # request.session['formularios'] = names # return HttpResponseRedirect('/handler/seleccionar-indicadores/') return reverse_lazy('handler:seleccionar-indicadores') def get_context_data(self, **kwargs): self.object_list = super().get_queryset() context = super(SelectingFormulariosView, self).get_context_data(**kwargs) try: … -
Deploy django app in heroku with poetry environment
I've been using poetry for a while for many practice projects but haven't deployed anything until now, and when I try to do it in heroku I get this error. -----> Installing python-3.9.1 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Processing /home/santi/.cache/pypoetry/artifacts/9c/90/26/d9fa1dfd567d8ba46faa44b741eb6442f3b97eb9f10a40bc1ad7a7f10e/asgiref-3.3.1-py3-none-any.whl ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/santi/.cache/pypoetry/artifacts/9c/90/26/d9fa1dfd567d8ba46faa44b741eb6442f3b97eb9f10a40bc1ad7a7f10e/asgiref-3.3.1-py3-none-any.whl' ! Push rejected, failed to compile Python app. ! Push failed I can't seem to find anything specific to this django-poetry-heroku issue so maybe I can find some help over here, I have my petry.lock and .toml files, also a requirements.txt since heroku requires it, here they are... pyproject.toml [tool.poetry] name = "Team Wool Capstone App" version = "0.1.0" description = "News app with likes, and user submission feature" authors = ["Joseph Dubon <josephdubon@pm.me>"] [tool.poetry.dependencies] python = "^3.9" Django = "^3.1.7" flake8 = "^3.9.0" Pillow = "^8.2.0" whitenoise = "^5.2.0" django-environ = "^0.4.5" gunicorn = "^20.1.0" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" -
Django - How to run consecutive forms?
I have a user registration form that asks for user information and also asks a question: "Are you a PSMC member?" The options are: rank = [ ('Supporter', 'Supporter (non-member)'), ('Anak', 'Anak'), ('Uso', 'Uso'), ('Chief', 'Chief'), ] If Supporter is selected, then the registration form proceeds and saves user info, etc. This part works fine. However, if Anak is selected, I want it to take the user to another form that asks additional questions. In my forms.py, I have class RegisterForm which is the main registration form for all users. I also have class AnakRegisterForm which is what I want it to continue on to. I used Django's AuthenticationForm based off what I read from their website (but I could be wrong). I know the issue is in views.py register function. Specifically: if rank == 'Anak': anak_register(response) During my debug session, after it moves response to anak_register function, it gets a bunch of scrambled information. I'm pretty lost, any help would be appreciated. Here is my code: forms.py class RegisterForm(UserCreationForm): email = forms.EmailField( initial='', required=True, help_text='Please enter a valid email address' ) rank = forms.ChoiceField( label='Are you a PSMC member?', choices=SavBlock.models.User.rank, initial=False, required=True, help_text='Member accounts will be validated with your … -
ValueError: logout didn't return an HttpResponse object. It returned None instead
I realize that this question has been asked before, but I'm struggling for explanation as to why I'm getting the following error: ValueError: The view django.contrib.auth.logout didn't return an HttpResponse object. It returned None instead. I'm following exactly what Django has in their docs here when it comes to logging out: https://docs.djangoproject.com/en/3.2/topics/auth/default/#how-to-log-a-user-out class LoginPage(TemplateView): template_name = "users/login_page.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['login_form'] = LoginUserForm(data=self.request.POST or None) return context def get(self, request): context = self.get_context_data() return self.render_to_response(context) def post(self, request): context = self.get_context_data() form = context['login_form'] if form.is_valid(): user = form.get_user() login(request, user) return HttpResponseSeeOther(reverse("questions:mainpage")) return self.render_to_response(context) def logout_user(request): logout(reqeust) return HttpResponseSeeOther(reverse("users:login")) user_urls = ([ path("register/", uv.RegisterPage.as_view(), name="register"), path("login/", uv.LoginPage.as_view(), name="login"), path("logout/", uv.logout, name="logout") ], 'users') urlpatterns = [ path('admin/', admin.site.urls), path("", include(question_urls)), path("users/", include(user_urls)), ] -
Serving static images in Django development
this is a commonly asked question so I am not sure why I can't get this to work. Foremost, here is the file structure of my project: -blog -templates - - about.html -media -static - -css - -img - - profile_pic - -js ... I have gone through the process of configuring my settings.py to serve static files during development by adding the following: STATIC_URL = '/static/' and STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static',), ] into my settings.py file. In my about.html, I place the {% load static %} tag at the top of the page, then I attempt to load my image by calling the tag like so: <img class = "card-img-top" src="{% static 'img/profile_pic'%}" alt="My profile picture"> Nothing appears. The logs state "GET /static/img/profile_pic HTTP/1.1" 404 1671 So the file isn't loading at all. Could this be a problem with my filepaths? -
How to specify the user in the blog post in django?
I'm quite new in django, and here is my question: I have a django model (like posts in blog with a form) -> class Product(models.Model): asset_name = models.CharField(verbose_name='Название актива', max_length=50) asset_sector = models.CharField(verbose_name='Отрасль', max_length=50) asset_price = models.DecimalField(verbose_name='Цена', max_digits=10, decimal_places=2) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and here is field called author, I have an authorization and i need the next: when the user add his post, the post would automatically choose the author (current user) Now my model don't add anyone, just give the possibility to choose here to see the screenshot of django admin imports: from django.db import models from backend import settings model of User class CustomUser(AbstractUser): balance = models.DecimalField(max_digits=10, decimal_places=1, null=True, default=0) email = models.EmailField(blank=True, null=True) username = models.CharField(unique=True, max_length=150) USERNAME_FIELD = 'username' def __str__(self): return self.username form of adding the post class ProductForm(ModelForm): class Meta: model = Product fields = ['asset_name', 'asset_sector', 'asset_price', ] widgets = { "asset_name": TextInput(attrs={ 'class':'form-control', 'placeholder': 'Название актива', }), "asset_sector": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Отрасль', }), "asset_price": NumberInput(attrs={ 'class': 'form-control', 'placeholder': 'Цена', }), } -
Building django web app which uses algorithms running on google colab
i wanted to create a Django web application on where i will put some ML algorithms and a user interface to make easy to upload pictures and videos ,and these algorithms gonna run on google colab. but the problem is that i don't know how to make my app interacts with google colab mostly that there is no api for this google service. if you have any idea which can help me , please don't hesitate