Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Serialize a ManyToMany relationship with a through argument via a related OneToOne model
So the subject may or may not be contextually accurate but what I do know is it involves all of the above and I'm hitting a wall... I'm looking to get a Workspace model's owner URL directly on the Workspace something like: Desired Output { "url": "http://127.0.0.1:8000/api/workspaces/1/", "id": 1, "name": "Ws 1", "slug": "ws-1", "users": [ "http://127.0.0.1:8000/api/users/2/", "http://127.0.0.1:8000/api/users/4/" ], "owner": "http://127.0.0.1:8000/api/users/2/" } Models class Workspace(models.Model): name = models.CharField(max_length=80) users = models.ManyToManyField(UserModel, through="workspaces.WorkspaceUser", related_name="workspaces") class WorkspaceUser(models.Mode): user = models.ForeignKey(User, related_name="user_workspaces", on_delete=models.CASCADE) workspace = models.ForeignKey( Workspace, related_name="workspace_users",on_delete=models.CASCADE) class WorkspaceOwner(BaseTimeStampedModel): workspace_user = models.OneToOneField(WorkspaceUser, on_delete=models.CASCADE) workspace = models.OneToOneField(Workspace, related_name="owner", on_delete=models.CASCADE) Serializers class WorkspaceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Workspace fields = ["url", "id", "name", "slug", "users", "owner"] class WorkspaceUserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = WorkspaceUser fields = ["url", "id", "user"] class WorkspaceOwnerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = WorkspaceOwner fields = ["url", "id", "user"] How can I best serialize the workspace.owner.workspace_user.user url for the HyperlinkedModelSerializer? Thank you! -
How to get previous saved data while editing profile page in django
while editing my profile page ,i get blank page but i want previous saved data. forms.py class UserEditForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','email'] class ProfileEditForm(forms.ModelForm): class Meta: model=Profile fields=['date_of_birth','photo'] views.py @login_required def editprofile(request): user_form=UserEditForm() profile_form=ProfileEditForm() if request.method=='POST': user_form=UserEditForm(data=request.POST,instance=request.user) profile_form=ProfileEditForm(data=request.POST,instance=request.user.profile,files=request.FILES) if user_form.is_valid() and profile_form.is_valid() : user_form.save() profile_form.save() return HttpResponse('profile saved') context={'user_form':user_form,'profile_form':profile_form} return render(request,'socialapp/editprofile.html',context) -
How to send cookie from frontend to backend?
I am using react.js as a frontend and django as backend and I need to send cookie from frontend to backend -
How to Update multiple Images in django?
I was looking for a feature for uploading multiple images and found this solution how to upload multiple images to a blog post in django but that method doesn't provide any explanation about updating those multiple images like image can be removed and added new one. how to update multiple images? -
Django rest framework token in url
How to add a token in url. Like this https://127.0.0.1/api/price?fsym=BTC&tsyms=USD,RUB&api_key=8sfeggasdfwer944bf10b6 -
Django - Not able to get specific data from Model to the View
A bit stuck on getting specific data out from the Model via "POST" to the view. only want the IP to be "POST" back to the view. Here is my function that get post data from the webpage. It gets the data fine but all i want is a single item from the specific row. It is not letting me change the html as I get the following error i change option value in html to " ipofnode.ip_address_field " from "ipofnode.id" " Field 'id' expected a number but got '192.168.1.1'. " If i keep it to "ipofnode.id" , it prints out the entire row on the webpage just fine. I only want the IP to be "POST" back to the view so i can save it as a string and pass it. 1: 192.168.0.216:R1-ISP:VMX def inventory(request): if request.method == "POST": ipnode = Nodes.objects.get(pk=request.POST["ipofnode"]) #savedip = ipnode.ip_address_field.all() listip.append(ipnode) return render(request, "hwinventory/hwinventory.html",{ "allnodesips":Nodes.objects.all()}) hwinventory.html {%extends "home/layout.html"%} {% block body%} <h1 style="text-align:center;">Inventory Check</h1> <form action="{% url 'inventory' %}" method="post"> {% csrf_token %} <select name="ipofnode"> {% for ipofnode in allnodesips %} <option value="{{ ipofnode.id }}">{{ipofnode.hostname}}</option> {% endfor %} </select> <input type="submit"> </form> <a href="{% url 'resultsinventory' %}">View Results</a> {%endblock%} MODEL class Nodes(models.Model): ip_address_field = … -
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") ) …