Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError even though the Module is present
I am getting a ModuleNotFoundError for a module that exists. I have a __init__.py and imported sys but I am still getting a ModuleNotFoundError error on my django error. My file structure: |-my_app |-folder1 |-__init__.py |-calc.py |-folder2 |-__init__.py |-test.py I want to import a function from test.py in calc.py. This is my code: import sys from folder2.test import func1, func2 #my code When I run this, I am getting this error: ModuleNotFoundError: No module named 'folder2.test' How can I fix this error? -
Django ModelForm Hidden Field to 'True' in only a certain situation?
I've got the following Django Form; it has a field called 'finished', that is hidden. I set the default to False because there is only one situation where I want it set to True. The problem is that it still marks it as "False" and I can't figure out how to change it in that one situation. In my views.py I have this: context["test_form"] = TestForm( instance=self.object, hide_status=True, is_finished=True ) the form looks like this: class TestForm(ModelForm): finished = forms.BooleanField( widget=forms.HiddenInput(), initial=False, required=False ) status = forms.Select(attrs={"class": "form-control"}) def __init__(self, *args, **kwargs): hide_status = kwargs.pop("hide_status", None) is_finished = kwargs.pop("is_finished", None) super().__init__(*args, **kwargs) self.fields["status"].queryset = Status.objects.filter(active=True) self.fields["status"].widget.attrs["class"] = "form-control" if hide_status: self.fields["status"].widget = HiddenInput() if is_finished: self.fields["finished"].initial = True class Meta: model = Test fields = ["finished", "status"] The HTML is super simple: <form method="post" action="{% url 'my_app:test-update' %}"> {% csrf_token %} {{ test_form.as_p }} <button type="submit" class="btn btn-primary">Finish</button> </form> The rendered HTML looks like this: <input type="hidden" name="finished" value="False" id="id_finished"> What is the best way to get that set to True in this case? -
How to properly check authentication with Vue.js (Vue router) and Django
I am trying to check if a user is authenticated on protected routes in vue-router. I have Django rest framework that sets sessionid on login. I have seen people using vuex or local storage to store session information. But, If the token was forcibly expired on the server-side a user will be allowed to navigate since localStorage still says IsAuthenticated=true. In this case, is it the best choice to make a request to the Django backend such as fetch("url/auth/authenticated")? -
Djoser is ignoring my Authenitcation Token
I set up djoser and DRF's TokenAuthentication. It works perfectly for registering users, and i get a valid token returned. When I try to access /users/me or /token/logout with header: Authorization: Token {token} (and the token itself in the body for good measure) I get the response Error 403: "Authentication credentials not provided." I've tried making the request through axios and postman. I made other accounts and tried their keys but I get the same result. I've looked on the djoser docs but there is no help there, nor anywhere else, because it seems no one else has this issue. -
Can you connect to a Django backend via a python separate file? if both are running locally
For example, when I would create a ruby and react app. I could run the ruby app on local.host:3000 and the react app on local.host:4000. With some configuration, I could fetch information from my ruby backend and send information from by react frontend. Currently, I am working on building a bot on discord, with a django frontend/backend. I need to run the python bot at the same time as the Django website. I run the bot via "python main.py". I run the django project via "python3 manage.py runserver" runs on http://127.0.0.1:8000/. They both work fine at the same time, but I want the bot to be able to send information to the django project. I don't believe its like ruby. I cant just fetch to http://127.0.0.1:8000/ bc that is not the backend. That is the frontend of the site(?). So, is there anyway for me to get the URL of the django backend, so I can send information to it via my python bot. I cannot seem to find an article on this, any help would be greatly appreciated. Thanks! -
Error response from daemon: invalid volume specification: 'D:\project\bookstore:/code:rw'
I try to run the following code, but in the end I deal with the opposite error. (venv) PS D:\project\bookstore> docker-compose up [+] Running 0/0 Container bookstore-web-1 Creating 0.0s Error response from daemon: invalid volume specification: 'D:\project\bookstore:/code:rw' -
how can I configure supervisor for celery and celery beat on django project?
I install supervisor with this command: pipenv install supervisor where is the location of the supervisor configuration file for run celery worker and celery beat? -
Hvaing some 500 (Internal Server Error) issue in my code
I am trying to call a function when there is a button click. But its showing the error that I have mentioned above. -
Getting error code 247 while deploying django app
I am trying to deploy my Django application to Digital ocean droplets, using the less expensive one, that gives me 512 mb of ram, 1 CPU and 10 gigs of SSD. Then, after I set up everything properly, I run docker-compose up --build to see if everything is fine. It launches all. In my docker compose, I use a postgres instance, a redis one and a celery one, and the django application I wrote. If that matters, here is the docker-compose file version: "3.9" services: db: container_name: my_table_postgres image: postgres ports: - 5432/tcp volumes: - my_table_postgres_db:/var/lib/postgresql/data environment: - POSTGRES_DB=my_table_postgres - POSTGRES_USER=dev - POSTGRES_PASSWORD=blablabla redis: container_name: redis image: redis ports: - 6739:6739/tcp environment: - REDIS_HOST=redis-oauth-user-service volumes: - redis_data:/var/lib/redis/data/ my_table: container_name: my_table build: . command: python manage.py runserver 0.0.0.0:5000 volumes: - .:/api ports: - "5000:5000" depends_on: - db - redis celery: image: celery container_name: celery restart: unless-stopped build: context: . dockerfile: Dockerfile command: ['python', '-m', 'celery', '-A', 'mytable' ,'worker', '-l', 'INFO'] volumes: - .:/api depends_on: - redis - my_table links: - redis volumes: my_table_postgres_db: redis_data: Then, all starts up quite slowly, but after I try to make a request from something like postman, in the terminal of docker compose, the main process … -
How to display a custom form with multiple widgets for a field in Django admin?
The Django docs say you can add a form to the admin UI: class ArticleAdmin(admin.ModelAdmin): form = MyArticleAdminForm I want a custom editing UI for a special field in my model, where I display multiple widgets. (It's not exactly the same, but an analogy might be a calendar widget where values on the calendar are editable.) Perhaps I could break the multiple values into multiple database objects and use an InlineAdmin, but I have app-specific reasons to not do that. I thought I'd use a Form object with some custom fields, but Django says it must be a ModelForm: <class 'myapp.admin.MyAdmin'>: (admin.E016) The value of 'form' must inherit from 'BaseModelForm'. Is it possible to display multiple widgets (basically a very custom form) for a single model value in Django admin? -
Django not logging in properly when custom backend and models are used
I'm trying to implement a custom authentication backend in Django but its behaving in a very strange way. The custom backend authenticate against a different model from the usual Django User model an upon successfully verifying the provided credentials the backend get or create our usual Django User instance which it returns. Login nevertheless doesn't work. From the documentation I learnt that I just needed to inherit the django.contrib.auth.backends.BaseBackend and override the authenticate() method which I did. As I've mentioned the custom authenticate() method basically verifies a set of credentials (username and password) against ones stored in the database (custom model, not django.contrib.auth.models.User) which if matched it would get or create an instance of django.contrib.auth.models.User via a proxy model which I named Profile; basically the Profile model has a reference of both django.contrib.auth.models.User and my custom model. When logging in though I keep redirected to the login page (It's like Django logs me in but doesn't set something somewhere such that when I try accessing a protected resource I'm redirected back to login). Also when I login which a django.contrib.auth.models.User object it works just fine and I can access the protected pages. Following are the reasons I opted for this … -
Model change with Celery and Json request list
I have a model and request json list of dicts from api and i need to add or change subject in this model But im not sure that my code is correct , using celery and it`s got an error : " counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) KeyError: 'GUID'" I tried pydantic as well and still coudnt solve this problems models.py class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150) customer = models.BooleanField(default=False) contractor = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Counter Party' tasks.py from u.celery import * from .models import CounterParty import requests from requests.auth import HTTPBasicAuth @app.task def create_counter_party(): response = requests.get("http://1c-prod-un/bp3/hs/BpAPI/WebApp/GetListCounterparty", auth=HTTPBasicAuth('#some-login', '#some-pass')) rep = response.json() try: for item in rep: counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) for key, value in item.values(): setattr(counter_party, key, value) counter_party.save() except CounterParty.DoesNotExist: for item in rep: new_values = {'GUID': item['CounterpartyGUID'], 'name': item['CounterpartyName'], 'customer': item['Customer'], 'contractor': item['Contractor']} new_values.update(item) counter_party = CounterParty(**new_values) counter_party.save() json request from an api: [ { "CounterpartyGUID": "#some-uuid", "CounterpartyName": "name1", "Customer": false, "Contractor": true }, { "CounterpartyGUID": "#some-uuid", "CounterpartyName": "name2", "Customer": false, "Contractor": true }, ] -
Visual Studio: Django template with DTL. Problem: HTML form tag doesn't accept DTL(Django Template Language) tag with double (")
My problem is when I write the HTML tag with the DTL(Django Template Language) tag for URL, VSC mark it as wrong (the reason is obvious: wrong string detecting). I'm not entirely sure what approach is the most proper. Should I use an escape character for the inner " or write this?: If an escape character is the most proper way how should be constructed? \" seems not working. -
How to solve Django : ModuleNotFoundError: No module named 'djoser'
I have installed djoser on my Django project, however , for some reason, It will not find djoser and throw : "ModuleNotFoundError: No module named 'djoser'" You can see djoser is on my settings.py installed apps and it's installed on my venv, which is also activate. -
Real Time data in Django
I want to observe data changes in real time in python to create a program that show list of online friends (i.e. every time a friend become online or offline I want update a list). I have a function that make an infinite loop to receive the presence a from am XMPP server. I can't seem to figure out how I could receive data in real-time and update. I use Django for backend and i want ti serve this data to a web page to show online Friends. I tried with Channels, but it’s unuseful for this case. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = ssl.wrap_socket(s, ssl_version=ssl. ssl.PROTOCOL_TLSv1_2) sock.connect((hostname, port)) sock.sendall(“<presence/>”.encode()) while True: response = sock.recv(1024) How can i pass this results to my page view every time i get new update insidie loop? -
Django Project - post a non-empty array using ajax but receive an empty one
My JS goes: (data is not empty in both checkpoint1 and 2) $("#btn_filesUpload").click(async ()=>{ let data = await getFiles() //checkpoint1 $.ajax({ url: '/files_upload/', data: {'data': data}, type: 'post', headers: {'X-CSRFToken': csrftoken }, }).done(function (response) { //checkpoint2 if (response.success){ console.log("Successfully uploaded") } else{ console.log("Uploading failed") } }) }) In view.py def files_upload(request): files = request.POST.getlist('data') print(files) print('----') print(request.POST.getlist) return JsonResponse({ 'success': True }) in the terminal: [] ---- <bound method MultiValueDict.getlist of <QueryDict: {}>> if i replace the data in ajax to data:{'data':[1,2]} it works just fine. <bound method MultiValueDict.getlist of <QueryDict: {'data[]': ['1', '2']}>> Does anyone know why this happens? -
My app 127.0.0.1:8000 is not loading in browsee
I created a todo notes app from geek for geeks and tried to run it, compilation wasn't wrong but the final app link 127.0.0.1:8000 isn't running in browser I tried it in various browser it's still same -
OperationalError at /admin/store/product/ , no such column: store_product.product_name"
I try to create an simple e-commerce site , the model is registered , I did makemigrations and migrate as well , it runs the server and also the model shows on admin panel , but whenever I try to click that it shows the error " OperationalError at /admin/store/product/ no such column: store_product.product_name" but if I click on "+add" button of the side it works , and in order to saving the product information it throws also same error .... I did makemigrations , migrate , sqlflush and syncdb .. but none of this works ... help me -
Django Code Repetition due to Multiple objects in JSON
I have the following code which works as expected i.e saves data to the db as I would like it to, however, there is a lot of code repetition and I am unable to find a way to shorten the code I have about 30 serializers (pasting 3 to shorten the code) class FirstOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = FirstOne fields = ['decimals', 'unitRef', 'value', 'period'] class SecondOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = SecondOne fields = ['decimals', 'unitRef', 'value', 'period'] class ThirdOne(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = ThirdOne fields = ['decimals', 'unitRef', 'value', 'period'] class CashFlowSerializer(serializers.ModelSerializer): FirstItemInJson = FirstOne(many=True) SecondItemInJson = SecondOne(many=True) ThirdItemInJson = ThirdOne(many=True) class Meta: model = Basetable fields = "__all__" def create(self, validated_data): itemOneData = validated_data.pop('FirstItemInJson') itemTwoData = validated_data.pop('SecondItemInJson') itemThreeData = validated_data.pop('ThirdItemInJson') cashflow = Basetable.objects.create(**validated_data) for data in itemOneData: period_data = data.pop("period") dataObj = FirstItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( firstItem_id=dataObj, **period_data) for data in itemTwoData: period_data = data.pop("period") dataObj = SecondItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( secondItem_id=dataObj, **period_data) for data in itemThreeData: period_data = data.pop("period") dataObj = ThirdItemModelClass.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( thirdItem_id=dataObj, **period_data) JSON: (trimmed to keep it shorter) jsonToUse = { "CompanyId": "320193", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": … -
How to access form object before and after saving in django-bootstrap-modal-forms
I have following code in my view of adding a new Item. Some fields are filled via user some fields are filled in the background. If form is valid then user is redirected to a url with a parameter (slug) from added object. How can I convert this code to django-bootstrap-modal-forms way? def category_view(request, slug, *args, **kwargs): ... if request.POST: form = CreateItemForm(request.POST) if form.is_valid(): if not request.user.is_authenticated: raise PermissionDenied() obj = form.save(commit=False) obj.created_country = Constants.country_code obj.created_by = request.user obj.save() return redirect('category:item_detail', slug=obj.slug) -
Catch-all field for unserialisable data of serializer
I have a route where meta-data can be POSTed. If known fields are POSTed, I would like to store them in a structured manner in my DB, only storing unknown fields or fields that fail validation in a JSONField. Let's assume my model to be: # models.py from django.db import models class MetaData(models.Model): shipping_address_zip_code = models.CharField(max_length=5, blank=True, null=True) ... unparseable_info = models.JSONField(blank=True, null=True) I would like to use the built-in serialisation logic to validate whether a zip_code is valid (5 letters or less). If it is, I would proceed normally and store it in the shipping_address_zip_code field. If it fails validation however, I would like to store it as a key-value-pair in the unparseable_info field and still return a success message to the client calling the route. I have many more fields and am looking for a generic solution, but only including one field here probably helps in illustrating my problem. -
Real time data Python
I want to observe data changes in real time in python to create a program that show list of online friends (i.e. every time a friend become online or offline I want update a list). I have a function that make an infinite loop to receive the presence a from am XMPP server. I can’t understand how can update Every time i receive new data. while True: response = sock.recv(1024) -
How to convert POST PascalCase json to snake_case in Django Rest Framework?
I have a DRF API endpoint that accepts python snake_case payloads: { "sample_id": "", "notes": "", "patient_id": "", "dob": "", "scan_model": { "current_time_left": "", "scan_state": null, "timer_configuration": { "timer_interval": null, "timer_length": "", "warning_span": "", "window_of_opportunity": "" } } How to get the endpoint to accept a json with keys in PascalCase like this: { "SampleId": null, "Notes": null, "PateintId": "testid", "DateOfBirth": "05/11/1995", "ScanModel": { "Id": 1, "CurrentTimeLeft": "00:00:00", "ScanState": 6, "TimerConfiguration": { "TimerInterval": 200, "TimerLength": "00:15:00", "WarningSpan": "00:02:00", "WindowOfOpportunity": "00:05:00" } } I am using Django 4.1, DRF 3.14 and python 3.11 Thanks! -
How to let user download a file after the process is completed in Django?
I am a beginner in Django. I am trying to let user download a file after the specific process is completed. Here is view.py. The download button is shown after the process is completed. Users can download the file named WS_file_name+'.xlsx' by clicking the download button. from django.shortcuts import render from django.http import HttpResponse def index(request): if request.method == 'POST': student = StudentForm(request.POST, request.FILES) if student.is_valid(): handle_uploaded_file(request.FILES['file']) firstname= student.cleaned_data.get("firstname") lastname= student.cleaned_data.get("lastname") ### Processing ### WS_file_name = lastname + firstname + newfile Toollist_Raw = pd.read_excel(Toollist_path+Toollist_file_name) WS_file = xlsxwriter.Workbook(WS_file_name+'.xlsx') WS_file.close() file_source = WS_Path + WS_file_name+'.xlsx' Toollist_Raw.to_excel(file_source, sheet_name='CALM_Toollist',index=False) ### Process had completed, users can click download button to download the file ### context= {'username': firstname, 'version':lastname,} return render(request, 'template_Download.html', context) else: student = StudentForm() return render(request,"template_Form.html",{'form':student}) ##### Download Functions ##### import os from django.http import FileResponse def download_file(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define file name filename = WS_file_name+'.xlsx' # Define the full file path filepath = BASE_DIR + '/Capital_Report_Website/Download_Files/Baseline_Cleanup_Toollist_vs_CALM_Download/' + filename +'.xlsx' return FileResponse(open(filepath, 'rb'), as_attachment=True) The below code is template_Form.html. This page is to let user fill in the information which is used to process the file. <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p … -
im want when user click profile pass to profile.html
i want to user when click profile pass user to profile.html but problem i don't solve hem --------- path path('home', views.home, name="home"), path('profile/<int:id>', views.profile_views, name="profile_views") -------- models class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) ------- views def home(request, id): pro_id = profile.objects.get(id=id) context = {'pro_id' : pro_id} return render(request, 'main-frond.html') def profile_views(request, id): ff = profile.objects.get(id=id) context = {'ff' : ff} return render(request, 'profile.html', context) ------ html <br> <a href="{% url 'profile_views' pro_id.id %}">profile</a> <br> <hr> {{request.user}} <hr> <a href="{% url 'login' %}" id="login-register" style="float: right;">Login</a> <a href="{% url 'register' %}" id="login-register">Register</a> where's the problem i want to user when click profile pass user to profile.html but problem i don't solve hem