Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Bootstrap 5 why select options doesn't appear in every browsers?
I'm made a page where the user have to choose an options from the dropdown list where other users that matches to a criteria appears. Almost every cases it works well but some users (they are using Chrome or Edge) made a feedback that the options are in the dropdown list but the text has the same color like the background so it is appears just when they hover it like on the image below. In the most of the cases everything works fine and all the names appear. I don't used any any CSS just Bootstrap 5 and Django. <h3 class="mt-4">This is the questions label</h3> <select class="form-select" aria-label="" name="perf01a" id="perf01a"> <option id="opt">nincs</option> {% for u in related_users %} <option>{{ u.user_name.last_name }} {{ u.user_name.first_name }}</option> {% endfor %} </select> <select class="form-select" aria-label="" name="perf01b" id="perf01b"> <option id="opt">nincs</option> {% for u in related_users %} <option>{{ u.user_name.last_name }} {{ u.user_name.first_name }}</option> {% endfor %} </select> <select class="form-select" aria-label="" name="perf01c" id="perf01c"> <option id="opt">nincs</option> {% for u in related_users %} <option>{{ u.user_name.last_name }} {{ u.user_name.first_name }}</option> {% endfor %} </select> What should I do? -
Making a django site that is vulnerable to session hijacking
For a cybersecurity demo, I need to create a website that is vulnerable to session hijacking simply by sniffing a session cookie and integrating it in the attacker's requests' headers. I have tried using many implementations of jwt authentication, and also to simply steal the "sessionid" after having set SESSION_COOKIE_SECURE to "False". I was never able to steal the sessions on my website and would always get redirected to the login page. Can you think of any vulnerable public session cookie mechanism I could implement to steal a session on my django website simply by adding it to my requests' headers ? Thank you very much. -
I am having issues trying to make my first website with django
i just tried to return a Httpresponse but showed me this error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\config.py", line 206, in create mod_path, _, cls_name = entry.rpartition(".") AttributeError: module 'asyncio.events' has no attribute 'rpartition' -
How to return rendered html I received from a 3rd party api call in Django?
The frontend requests the /oauth endpoint from our backend. The backend makes a request to a third party, and they return some html to our backend. Is there a django Response method that allows me to return this html, rendered, to the frontend? Something like: url = '3rd/party/url' response = requests.get(url) return Response.render(response.content) I am somewhat new to python/django, so any advice would be lovely. Thank you! -
Django Dynamic Dropdown Menu Not Populating
I'm working on a project where the task is to implement a dynamic drop-down menu where the choices in the menu will change depending on the value that the user selects from a previous drop-down menu. I have the first dropdown menu populated with the values of the name keys in the JSON below (Network 1, Network 2, etc.). My goal is that the second dropdown will populate with a list of the zone values that correspond with the name value that the user selects in the first dropdown. So, if the user selects Network 1 from the first dropdown, the second dropdown will populate with network.1.private.zone as its only option. If the user selects Network 2 from the first dropdown, then the second dropdown will populate with network.2.private.zone as its only option, and so on. Thanks in part to this guide, I've made quite a bit of progress on this. I can see the AJAX request firing in the browser, and the url and networkId values seem to be correct when I console.log them to the browser. But I can't figure out why the dynamic dropdown menu isn't populating. Here is a screenshot of what the page looks like: … -
Django - CKEditor5Field field default font color
I've got 2 CKEditor5Fields in one of my models. I'm running into an issue in the admin panel that when the browser is in dark mode the background color of the field is staying white and the font color is changing to an off-white color making it really hard to read. The text is fine when it's rendered to the page. Is there a way to set the default font color to black so browser mode doesn't matter? Light Mode: Dark Mode : Model properties: property_short_description = CKEditor5Field('property short description', config_name='extends', blank = True, null = True) description = CKEditor5Field('description', config_name='extends') My config: CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', 'imageUpload' ], 'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable',], 'image': { 'toolbar': ['imageTextAlternative', 'imageTitle', '|', 'imageStyle:alignLeft', 'imageStyle:full', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side', '|'], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter',] }, 'table': { 'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties' ], 'tableProperties': { 'borderColors': customColorPalette, 'backgroundColors': … -
By use Django API Function without Django Rest Use, How to call API in dropdown list and display all API fields in dropdown list, below is code wrong
Use this api (url), return type of api List output, API CALL in a select dropdown list please tell me how to call api in dropdown list and display all api fields in dropdown list. <script> $('#mySelectapi').select2({ ajax: { dataType: "json", method: "GET", url: '/auto/multipleselectdjango', processResults: function (data) { // Transforms the top-level key of the response object from 'items' to 'results' return { results: $.map(data, function (payloaddata) { return { text: data.payloaddata, // results: data.payloaddata, // value: payloaddata } }), } } } }); </script> its a Wrong Scripts for call API, it display me all list data in a single row in dropdown Below is my Django function codes: def multipleselectdjango(request): # For check Get Data By url --> auto/autocompdjango/?urldata=a payload = [] # name__icontains=students--> "Use For Search with perform Matching by "icontains", # "name" is model(db) variable Name, students is above declare variable for get url data studentdata = Students_Search.objects.all() for getstudent in studentdata: # "name" is madel(DB) Name payload.append(getstudent.name) return JsonResponse({'status': 200, 'payloaddata': payload}) THIS IS RESULT OF API: MY API return a list Display THIS IS MY FINAL OUTPUT IN HTML PAGE DISPLAY DATA IN SINGLE ROW: MY FINAL OUTPUT HTML PAGE DROPDOWN LIST -
Empty reply from server\n :Running Django on Docker
i recently came across this error on Docker, how can i fix it ? {"Status":"unhealthy", "FailingStreak":56, "Log":[{"Start":"2022-05-27T16:47:50.248335918Z","End":"2022-05-27T16:47:54.375311277Z","ExitCode":52,"Output":" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n\r 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:03 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:04 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:04 --:--:-- 0\ncurl: (52) Empty reply from server\n"},{"Start":"2022-05-27T16:47:59.387363405Z","End":"2022-05-27T16:48:03.497278612Z","ExitCode":52,"Output":" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n\r 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:03 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:04 --:--:-- 0\r 0 0 0 0 0 0 0 0 --:--:-- 0:00:04 … -
Elasticsearch, what is cause of these failure logs
This is my docker container's logs. What could be the reason of these issues of elastic. It is in my Django project where I have an Advertisement model which I index with elasticsearch and show up them on my page. Some times this container fails and exits what leads to not showing up advertisements on the page. Errors: {"type": "server", "timestamp": "2022-05-27T07:43:46,335Z", "level": "WARN", "component": "r.suppressed", "cluster.name": "docker-cluster", "node.name": "9ddc4968ea4b", "message": "path: /advertisements/_search, params: {index=advertisements}", "cluster.uuid": "Gy7HxyMoRk-oSwqoC6FRWw", "node.id": "L06UoSF_TgGYDDO-APY3Dg" , "stacktrace": ["org.elasticsearch.action.search.SearchPhaseExecutionException: all shards failed", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.onPhaseFailure(AbstractSearchAsyncAction.java:663) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.executeNextPhase(AbstractSearchAsyncAction.java:384) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.onPhaseDone(AbstractSearchAsyncAction.java:696) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.onShardFailure(AbstractSearchAsyncAction.java:467) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.access$000(AbstractSearchAsyncAction.java:62) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction$1.onFailure(AbstractSearchAsyncAction.java:316) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.ActionListenerResponseHandler.handleException(ActionListenerResponseHandler.java:48) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService$6.handleException(TransportService.java:745) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService$ContextRestoreResponseHandler.handleException(TransportService.java:1290) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService$DirectResponseChannel.processException(TransportService.java:1399) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService$DirectResponseChannel.sendResponse(TransportService.java:1373) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TaskTransportChannel.sendResponse(TaskTransportChannel.java:50) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor$ProfileSecuredRequestHandler$1.onFailure(SecurityServerTransportInterceptor.java:252) [x-pack-security-7.12.1.jar:7.12.1]", "at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:28) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor$ProfileSecuredRequestHandler.messageReceived(SecurityServerTransportInterceptor.java:324) [x-pack-security-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:61) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService.sendLocalRequest(TransportService.java:908) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService.access$100(TransportService.java:68) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService$3.sendRequest(TransportService.java:140) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService.sendRequestInternal(TransportService.java:852) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor.sendWithUser(SecurityServerTransportInterceptor.java:164) [x-pack-security-7.12.1.jar:7.12.1]", "at org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor.access$300(SecurityServerTransportInterceptor.java:55) [x-pack-security-7.12.1.jar:7.12.1]", "at org.elasticsearch.xpack.security.transport.SecurityServerTransportInterceptor$1.sendRequest(SecurityServerTransportInterceptor.java:131) [x-pack-security-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService.sendRequest(TransportService.java:766) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.transport.TransportService.sendChildRequest(TransportService.java:817) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.SearchTransportService.sendCanMatch(SearchTransportService.java:112) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.CanMatchPreFilterSearchPhase.executePhaseOnShard(CanMatchPreFilterSearchPhase.java:81) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.lambda$performPhaseOnShard$3(AbstractSearchAsyncAction.java:300) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.performPhaseOnShard(AbstractSearchAsyncAction.java:337) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.CanMatchPreFilterSearchPhase.performPhaseOnShard(CanMatchPreFilterSearchPhase.java:132) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.run(AbstractSearchAsyncAction.java:226) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.executePhase(AbstractSearchAsyncAction.java:424) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.AbstractSearchAsyncAction.start(AbstractSearchAsyncAction.java:184) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.TransportSearchAction.executeSearch(TransportSearchAction.java:668) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.TransportSearchAction.executeLocalSearch(TransportSearchAction.java:489) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.search.TransportSearchAction.lambda$executeRequest$3(TransportSearchAction.java:283) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.action.ActionListener$1.onResponse(ActionListener.java:117) [elasticsearch-7.12.1.jar:7.12.1]", "at org.elasticsearch.index.query.Rewriteable.rewriteAndFetch(Rewriteable.java:103) [elasticsearch-7.12.1.jar:7.12.1]", "at … -
The view books.views.save didn't return an HttpResponse object. It returned None instead
i am trying to create a function to save favourite post to users profile, this is working fine in the database it adds and removes the favourite post but when the view is called it shows this error The view books.views.save didn't return an HttpResponse object. It returned None instead. views.py def save(request, book_slug): user = request.user book = Book.objects.get(slug=book_slug) post = get_object_or_404(Book, slug=request.POST.get('post_slug')) profile = Profile.objects.get(user=user) is_saved = False if profile.favourite_book.filter(slug=book_slug).exists(): profile.favourite_book.remove(post) is_saved = False else: profile.favourite_book.add(post) is_saved = True context = { 'book':book, 'post':post, 'is_saved':is_saved, } if request.is_ajax(): html = render_to_string('books/save_section.html', context, request=request) return JsonResponse({'form': html}) -
Why is fileChoice.value() None?
I am working in Django 3.2.13 trying to create a simple upload form for a file model with a chained foreign key. I have tried creating a form with a basic form model and a ModelForm, however, even when checking request.FILES there is no data and request_file = request.FILES['document'] if 'document' in request.FILES else Noneyields None. views.py def home(request): if handleAuth(request) is not None: return handleAuth(request) user = request.user if request.method == "POST": # if the post request has a file under the input name 'document', then save the file. form = FileSubmissionForm(user, request.POST, request.FILES) #print(request.FILES) #request_file = request.FILES['document'] if 'document' in request.FILES else None #if request_file: form.save() #else: # print("NO FILE") userFiles = [] if user.is_company_admin: temp = StorageFile.objects.filter(company_key=user.company_key) else: temp = StorageFile.objects.filter(company_key=user.company_key, profile__in=user.user_profiles.all()) temp.order_by("profile") for file in temp: userFiles.append({"name": file.getFileName(), "path": file.getMediaPath()}) form = FileSubmissionForm(user) return render(request=request, template_name="fileCloudApp/home.html", context={"userHasAdmin": user.is_company_admin, "files": userFiles, "form": form}) forms.py from django import forms from fileCloudApp.models import StorageFile from loginApp.models import UserProfile class FileSubmissionForm(forms.Form): fileChoice = forms.FileField() profileChoice = forms.ModelChoiceField(queryset=UserProfile.objects.none(), label="Choose profile") def __init__(self, user, *args, **kwargs): super(FileSubmissionForm, self).__init__(*args, **kwargs) if user.is_company_admin: temp = UserProfile.objects.filter(company_key=user.company_key) else: temp = user.user_profiles.all() temp.order_by("label") self.fields["profileChoice"].queryset = temp self.user = user def save(self): print(self["fileChoice"].value()) # None pro = … -
Django: The view books.views.save didn't return an HttpResponse object. It returned None instead
i am trying to create a function to save favourite post to users profile, this is working fine in the database it adds and removes the favourite post but when the view is called it shows this error The view books.views.save didn't return an HttpResponse object. It returned None instead. views.py def save(request, book_slug): user = request.user book = Book.objects.get(slug=book_slug) post = get_object_or_404(Book, slug=request.POST.get('post_slug')) profile = Profile.objects.get(user=user) is_saved = False if profile.favourite_book.filter(slug=book_slug).exists(): profile.favourite_book.remove(post) is_saved = False else: profile.favourite_book.add(post) is_saved = True context = { 'book':book, 'post':post, 'is_saved':is_saved, } if request.is_ajax(): html = render_to_string('books/save_section.html', context, request=request) return JsonResponse({'form': html}) -
Django custom User Model : I can't assign a user to a group in admin panel
I have created a custom User Model in my app. But, now, in the administration panel, I can't assign a user to a group or a permission because the right table doesn't appear. I don't find any solution yet, do you have any idea to solve this problem ? thanks SCREENS TO UNDERSTAND : without custom user model : see image now, with the custom user model, the right table is not : see image CODE : admin.py class UserAdmin(admin.ModelAdmin): list_display = ('username', 'email') search_fields = ('username',) fieldsets = ( (None, { 'classes': ['wide'], 'fields': ('username', 'password') }), ('Informations personnelles', { 'classes': ['wide'], 'fields': ('first_name', 'last_name', 'email', 'avatar') }), ('Permissions', { 'classes': ['wide'], 'fields': ('is_superuser', 'is_staff', 'is_active', 'groups', 'permissions') }), ('Dates importantes', { 'classes': ['wide'], 'fields': ('last_login', 'date_joined') }), ) models.py class User(AbstractUser): signup_token = models.UUIDField(primary_key=False, unique=True, verbose_name="jeton d'inscription", null=True, blank=True) avatar = CloudinaryField('image', blank=True, null=True) -
Error when importing django fixture with natural key
In context of a django project, I want to create some sample data in forme of a fixture. I have export my data with natural key to avoid any data overnight at the import but I'm not able to import data at all. The fixture has been created with the following command : python manage.py dumpdata --format yaml --natural-primary --natural-foreign conformity.policy conformity.measure > conformity/fixture/NIST.yaml I have tried to import the fixture with the following command : python manage.py loaddata conformity/fixture/NIST.yaml but I have the following error django.core.serializers.base.DeserializationError: Problem installing fixture 'conformity/fixture/NIST.yaml': ['“NIST Cybersecurity Framwork” value must be an integer.']: (conformity.measure:pk=None) field_value was 'NIST Cybersecurity Framwork' It seems to me that django don't understand data correctly and try to use natural key directly as a primary key. I haven't found any option to change this behavior. Of course YAML file don’t have any pk for the object to be imported (du to natural key), I was expected Django to automatically generate them. -
upload file with django from model
i created a form to upload a file, and also created a model like this: def get_file_path_order(request, filename): original_file_name = filename nowTime = datetime.datetime.now().strftime('%Y%m%d%H =%M%S') filename = "%s%s" % (nowTime, original_file_name) return os.path.join('services', filename) class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fname = models.CharField(max_length=150, null=False) lname = models.CharField(max_length=150, null=False, blank=False) email = models.CharField(max_length=150, null=False, blank=False) phone = models.CharField(max_length=150, null=False, blank=False) address = models.TextField(null=False) services_file = models.ImageField(upload_to=get_file_path_order, null=True, blank=True) and this is the form: {% if product.is_service == True %} <form method="POST" enctype="multipart/form-data" class="mt-3"> {%csrf_token%} <div class="custom-file"> <label class="custom-file-label" for="customFile">upload file contains all your requirenments and describe your needs</label> <input type="file" class="custom-file-input" name="sfile" id="sfile"> </div> </form> {% endif %} </div> it is working well in the admin panel which created automatically, how can I make it by my own with my form? -
How can I do redirect in DRF and pass data to a client (React JS)?
Backend: DRF Frontend: ReactJS I call a function openGoogleLoginPage if a user clicks on a button that opens a google login page and redirects to a server localhost:8000. const openGoogleLoginPage = useCallback(() => { const urlParams = new URLSearchParams(params).toString(); window.location = `${googleAuthUrl}?${urlParams}`; }); <Button onClick={openGoogleLoginPage}> Integrate Google Calendar </Button> On the server I get some JSON data and then redirect back to the client from django.shortcuts import redirect class GoogleLoginApi(APIView): def get(self, request, *args, **kwargs): data=process(request) response = redirect("http://localhost:3000", args=data) return response So I passed the data to redirect, but how can I get what I passed on the client side? Or maybe there is another way to redirect with a data? Anyway, how can I get it in my react app? -
how to send one section's field id to another section for the output
currently I'm making an 'django' app which has functionality of wizard form, in which I want output from first section of wizard form (which has dropdown list) to last section of the wizard form. To clarify more first section has only one dropdown list (sms, whatsapp, twitter, facebook, instagram, etc..), in second section also dropdown list (which has a department lists which means from which department you want to send...), in third section it should be dynamic and that will be depends on the first section of my wizard. For exaple if i select sms then in 3rd section it should show section which is specifically designed for sms and like wise. So, how should i do that?, if you still don't understand contact- captionamerica1112@gmail.com -
error: TypeError: tuple indices must be integers or slices, not str Overlapping check in Django Forms
Hi I am tring to ceate validation when the values will overlap in tuple but it not working , can anyone help or guide me. record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run') for overlap_check in (i, start_run, end_run, application_run): if overlap_check not in record: record.append(overlap_check) else: raise ValidationError( "overlapping not allowed" ) -
Aggregate/Annotate issue with OuterRef not working with non-FK relationship in Django? Is FK required?
I've got an issue with a couple models from different 'shared apps' that I have. I can't FK them together, because these apps exist in multiple projects (some without each other) so it would break other projects. This is an unmanaged model from appA - which uses a different database which we will call databaseA for this example; in a perfect world 'location_id' would be the FK but as I've described above, it cannot be. class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="locationID") grade = models.CharField(db_column="grade", max_length=10) student_count = models.IntegerField(db_column="studentCount") class Meta(object): managed = False db_table = "mytable_Enrollments" This is a managed model from appB which uses databaseB (which is the primary database used by the rest of the apps in this project); the 'pk' or 'id' of this model is what is listed in the Enrollment model under location_id class Location(models.Model): name = models.CharField(max_length=50) alternate_name = models.IntegerField() If I want to get Enrollment objects for a Location, I have to explicitly put a number in for the id like so: location = Location.objects.get(id=1) enrollments = Enrollment.objects.filter(location_id = location.id) But I'm trying to annotate the 'total_student_count' onto the Location model like so: enrollments = ( Enrollment.objects.filter(location_id=OuterRef("pk")) .order_by() .values("location_id") ) … -
Default value for JSONField
How to set the default value as {}::jsonb on JSONField in Django framework? Is it possible? default_value=dict without results. In the database, all the time null value is the default. -
django request in render to string template
I used to think, request is global variable that can always be accessed in template. until, I defined a property on model instance, and returns render_to_string template. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def card(self): return render_to_string('common/user_card.html', {'user': self.user}) user_card.html {% if request.user == user %} {% elif request.user in user.profile.follower.all %} <span href="{{ user.pk }}" class="user-follow not-followed">unfollow</span> {% else %} <span href="{{ user.pk }}" class="user-follow followed">follow</span> {% endif %} for the result, request is always None and the conditional always jump to else. the request keyword is not picked up by render_to_string, should it be global in any template since we must have a request to return something? I cannot believe it, in many other template I have things defined like: {{ user.profile.card }} I have no idea on what to do now, is there a way to make request always a keyword in any html template? this is such a bad feature that request is not available in render_to_string template which we cannot check who is requesting the page. -
Django throws an error while trying access registration page
Django throws the following at me while I try to access the signup page.. The view accounts.views.signup_view didn't return an HttpResponse object. It returned None instead. I think everything was done right but apparently django doesn't agree. Signup.html <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'signup.html', context) -
i want to learn programming but i don't choose asp.net core or django? [closed]
I want to learn programming as job , but I don't know learn django or asp.net core , and future of what are bright 🤔. I worked with c# and python before, and python is my favorite but I scared to loss my job in future, my friend is senior in .net core and say django is not trustable because a framework and maybe defeat in future (like node), but .net core is supported by Microsoft and it have great feature. Is my friend say right ? I 'm confused 😕, Anybody can help me ?! Thanks. -
Django UniqueConstraint on Distant Model
I have models like this. The basic relationship is that auth.Group can have multiple Projects, and multiple Orders can be associated with each Project. Simplified version: from django.db import models class Project(models.Model): group = models.ForeignKey("auth.Group", on_delete=models.SET_NULL, null=True) class Order(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) external_id = models.CharField(max_length=255) The Orders have external_ids that relate them to another system. Those should be unique at the auth.Group level. I know that I can do this: class Order(models.Model): group = models.ForeignKey("auth.Group", on_delete=models.SET_NULL, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) external_id = models.CharField(max_length=255) class Meta: constraints = ( models.UniqueConstraint( fields=["group", "external_id"], name="unique_external_id_per_group" ), ) But I don't want to replicate the group relationship on the order. I tried this: class Meta: constraints = ( models.UniqueConstraint( fields=["project.group", "external_id"], name="unique_external_id_per_group" ), ) and: class Meta: constraints = ( models.UniqueConstraint( fields=["project__group", "external_id"], name="unique_external_id_per_group" ), ) But I just get 'constraints' refers to the nonexistent field 'project.group'. -
Django: Append json data to Response object
New to Python/Django. I am wanting to conditionally append json data to a Response object if a particular filter is present in my request, all within the same json array. There is also standard information I want to return in every response. For example, I have: filter = request.GET['filter'] response = Response({'services': []}) if filter == 'service1': response.data['services'] = {'service1': service_data.get('service1')} response.data['connectivity'].add|append|something({'base_service_data': service_data.get('base')}) return response I can't seem to find a way of appending to this services array, only assigning and therefore overwriting what was there before. Can this be done? The goal is to allow filter to be a list, and have a number of services appended to services.