Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Field 'id' expected a number but got <QuerySet [<Store: X-Clusive Store>, <Store: GenFliX Exception Store>]>
Helo dev, can someone help me with this small but big problem. it returns this field id erro when a user create two store and try to add items to that store. if it is a single store, everything goes well and no erro will show but when the user create a store and try to add item to it, that is when this occurs. def itemupload(request): user = request.user items = Items.objects.filter(user_id = request.user) try: # store = Store.objects.get(author= user) store = Store.objects.filter(author= user) except Store.DoesNotExist: store = None if request.method =='POST': itemsforms =ItemsForm(request.POST, request.FILES) imageforms = ImageForm(request.POST, request.FILES) file= request.FILES.getlist('image') if all([itemsforms.is_valid(), imageforms.is_valid()]): item = itemsforms.save(commit = False) item.user = request.user item.save() item.store.add(store) for i in file: Images.objects.create(item = item, image =i) return redirect('index') return redirect('itemupload') imageforms =ImageForm() itemsforms = ItemsForm() context = { 'imageforms': imageforms, 'itemsform':itemsforms, 'items':items, } return render(request, 'jijiapp/itemform.html', context) this is model.py class Store(models.Model): name = models.SlugField(unique =True, max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) create_date = models.DateTimeField(auto_now_add=True, null=True) discription=models.CharField(max_length=5000, null=True, blank=True) location =models.CharField(max_length=5000, null=True, blank=True) logo =models.ImageField(upload_to='logos/', default = '') def __str__(self): return '%s' % (self.name) class Meta: ordering = ['-name'] verbose_name_plural = 'Store' class Items(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null=True, blank=True) … -
Django model, how to auto-increment an object's value
So I have this Django model.py: class Product(models.Model): name = models.CharField(max_length=128) views = models.IntegerField(default=0, blank=True) I would like the views attribute, to have an auto randomly generated number. So something like this: class Product(models.Model): name = models.CharField(max_length=128) views = models.IntegerField(default=0, blank=True) def auto_views(self): return randint(0,200) and the views attribute will automatically take the value of the auto_views() function when creating a new product. In the same way as an auto-slug would work. -
Django Not Found: /media/ , GET /media/ HTTP/1.1" 404 2679
I am currently building a project which i have to use media. Since i have used media before i copy pasted everyting from my other project and altough the original is working my current project is not. I can upload and select fotos thru admin page but it does not show up in html My view: def index(request): dergi = Dergi.objects.all() kitap = Kitap.objects.all() yazar = Yazar.objects.all() siir = Siir.objects.all() template = loader.get_template("index.html") context={ "DERGI":dergi, "KITAP":kitap, "YAZAR":yazar, "SIIR":siir, } return HttpResponse(template.render(context, request)) My model: class Kitap(models.Model): isim = models.CharField(max_length=255) yazar = models.CharField(max_length=255) foto = models.ImageField(upload_to="foto", null=True) My url: urlpatterns = [ path('admin/', admin.site.urls), path("", include("index.urls")) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And my html: <img src="/media/{{ KITAP.foto }}" alt="" class="rounded-t-lg"> <img src="/media/{{ KITAP.foto.url }}" alt="" class="rounded-t-lg"> <img src="{{ KITAP.foto.url }}" alt="" class="rounded-t-lg"> i have tried all but it just gives me error: GET /media/ HTTP/1.1" 404 2679 or: Not Found: /foto/ -
Partial Problem from configuration settings in `$DJANGO_SETTINGS_MODULE`
Tree Directory: . ├── Pipfile ├── Pipfile.lock ├── README.md ├── Strawberry │ ├── init.py │ ├── pycache │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── catalog │ ├── init.py │ ├── pycache │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── foo.py ├── manage.py └── requirements.txt 7 directories, 19 files Dudes, it's Ok when I use: $manage.py check And I get the result without any problems, Errors and Exceptions. But when I write the same with django-admin: $ django-admin check I get Error: ModuleNotFoundError: No module named 'Strawberry' From this result we can now know that Django finds/see environment variable — $DJANGO_SETTINGS_MODULE but don't see directory with settings. But if I import `models` from `catalog.models` into `foo.py` then on run by python3 pipenv interpretator (Note: virtual environment is activated): $ python3 foo.py I get: ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings In this case Django not see $DJANGO_SETTINGS_MODULE, but $DJANGO_SETTINGS_MODULE has been created (in virtual environment) and its value is: $DJANGO_SETTINGS_MODULE=Strawberry.settings Summing up, I want to … -
Extending a base class ins django
I want to create base model for my questions named Question and extend it by any other question types: `class Question(models.Model): questionnaire = models.ForeignKey(to='Questionnaire', on_delete=models.CASCADE, related_name='questions') question = models.TextField() description = models.TextField(null=True, blank=True) media = models.FileField(upload_to='medias', blank=True, null=True) is_required = models.BooleanField(default=False) def __str__(self): return f'{self.questionnaire.name} - {self.question}'` and I want to extend it like this: `class OptionalQuestion(Question): multiple_choice = models.BooleanField(default=False) additional_options = models.BooleanField(default=False) # If multiple_choice is True, then max_selected_options and min_selected_options will be used max_selected_options = models.IntegerField(null=True, blank=True) min_selected_options = models.IntegerField(null=True, blank=True) # If additional_options is True, then all_options and nothing_selected will be used all_options = models.BooleanField(default=False, null=True, blank=True) nothing_selected = models.BooleanField(default=False, null=True, blank=True) def save(self, *args, **kwargs): if not self.multiple_choice: self.max_selected_options = None self.min_selected_options = None if not self.additional_options: self.all_options = None self.nothing_selected = None if self.nothing_selected or self.all_options: self.all_options = False self.multiple_choice = False super().save(*args, **kwargs)` It's all good in the first creation of migrations But the next time the Django wants me to provide a default value for 'question_ptr' field I don't even know what is this field I tryed making base class abstract and when making migrations Django shows me so many errors like this: question_app.TextAnswerQuestion.questionnaire: (fields.E305) Reverse query name for 'question_app.TextAnswerQuestion.questionnaire' clashes with reverse … -
Django and Nginx with Docker
I am trying to use Nginx with Django and Docker in my project. On my computer, I can run the app with docker-compose but I cannot figure out how to use docker-compose to deploy to the docker hub with GitHub actions. What I have done instead is use WhiteNoise and not Nginx to be able to manage my static and media files. Here is the repo of what is working and any guidance will be greatly appreciated. If using WhiteNoise is also acceptable and has no drawbacks that would be good to hear as I have seen different views in that regard. -
How to make every subsequent page retain the slug in the URL and append URI
I'm making a Django website and I have 2 apps within it. Once the user is logged in and navigates to the dashboard area of the site I would like them to select a tenant to manage and for every subsequent menu button clicked to be in the context of that tenant. For example a user logs in with access to a 'tenant1'. I would like to the urls to all follow the format http://mywebsite/tenant1/. So far I've managed to create a tenant selector page successfully and navigate to the dashboard from there by adding the slug. The issue is every subsequent page no longer contains the slug, and I'm not sure how to access the slug from the previous page to be able to access it in the href. Even so I can see a solution that relies on the previous pages slug to be troublesome as some navigation options don't require the slug, just the user info. Here is my URLs.py urlpatterns = [ path('', tenant_selector.as_view(), name='tenant_selector'), path('<slug:slug>/dashboard', Dashboard.as_view(), name='Dashboard'), path('<slug:slug>/config/', config_view.as_view()), path('<slug:slug>/run_func/', loading_view.as_view()), path('profile/', user_update_view.as_view(), name='Profile'), path('success', Success.as_view()), ] Below is the Views.py class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['total'] = staff_sync_model.objects.count() … -
How to run django runserver in a background thread?
I need to run django runserver in the background to enable tests with selenium and pytest. A similar functionality is provided by pytest-django's live_server. But using live_server flushes the database after each test which implies recreation of tables and migrations on each test which is redundant and unacceptably slow. My main objective is to create a database and test user, login with selenium once and run all tests which is clearly impossible using pytest-django's live_server. As per the docs: you need to repopulate your database every time a test starts, because the database is cleared between tests and there is no way around it. So the solution is to run a django server in the background and use it instead. Here's a couple of approaches: Using a thread: import os from pathlib import Path from threading import Thread from django.core.management import call_command from django.core.wsgi import get_wsgi_application def start_server(src): os.chdir(src) os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'{Path(src).name}.settings') os.environ['DB_NAME'] = 'test_db.sqlite3' get_wsgi_application() call_command('migrate') call_command('runserver') def run_server(src): process = Thread(target=start_server, args=[src], daemon=True) process.start() if __name__ == '__main__': run_server('/path/to/myproject-root') which results in an error: Traceback (most recent call last): File "/usr/local/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/user/Library/Application Support/JetBrains/PyCharm2022.3/scratches/scratch_3.py", line 15, in start_server call_command('runserver') File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 198, … -
accessing django admin using angular frontend
I want to access django admin using angular frontend. I am not sure if its even possible. I am using angular as my frontend (angular ver:8.0) and django as my backend. I have also added admin in my urls.py file as given below from django.urls import path, re_path from django.contrib import admin from django.views.debug import default_urlconf router = routers.DefaultRouter() urlpatterns = [ url(r'^', include(router.urls)), re_path(r'^superadmin/', admin.site.urls), re_path(r'^$', default_urlconf),] but when open http://localhost:4203/admin/ it doesnt open django admin panel. (http://localhost:4203/ is my local angular server) How can I achieve this? Is it even possible to use django admin panel with angular frontend? Please help. -
How can I get my AJAX button press request to work in my Django environment?
So basically I want to use a javascript string variable in a python function, and then return it back to a javascript variable. To start, I have a html element where a string is placed in it. <h2 id="output"></h2> My plan is to pull that value from the HTML (shown in the AJAX statement below): var word = $("#output").val(); and use AJAX to send it to the backend for a python script that checks whether or not the word is a real English word (returning true/false). With the AJAX code I have, I keep getting returned an undefined variable. Here is the AJAX code: $(document).ready(function() { $('#submit_word').click(function() { var word = $("#output").val(); $.ajax({ url: '{% url 'wordgame' %}', //not sure type: 'POST', dataType: 'json', data: {word:word, csrfmiddlewaretoken: "{{ csrf_token }}",}, success: function(response) { var word_result = JSON.parse(response.result); console.log(response.result); $("#check-word").text(word_result); }, error: function(response) { console.log(response.result); } }); }); }); As well as my views function: def fetch_word(request): word = request.POST.get('word') result = check_if_word_in_dictionary(word) return JsonResponse({'result': result}) Whenever I click the button, it executes the 'error' part of my ajax statement: error: function(response) { console.log(response.result); } Which prints 'undefined' in the console. -
get_absolute_url is NOT working on the combined queryset, How can l do it?
I want to use get_absolute_url but it shows nothing on the combined queryset It returns an error that: Page not found Below are my codes #Action/models.py class Action(models.Model): ...... def get_absolute_url(self): return reverse('act',args=[self.slug]) #adventure/models.py class Adventure(models.Model): ...... def get_absolute_url(self): return reverse('adves',args=[self.slug]) #racing/models.py class Racing(models.Model): ...... def get_absolute_url(self): return reverse('act',args=[self.slug]) #puzzle/models.py class Puzzle(models.Model): ...... def get_absolute_url(self): return reverse('puz',args=[self.slug]) Then view of my combined queryset #Others/views.py from itertools import chain def games(request): ... ..... act_games=Action.objects.all() adv_games=Adventure.objects.all() puz_games=Puzzle.objects.all() rac_games=Racing.objects.all() games= list(chain(act_games,adv_games,puz_games,rac_games)) context={ 'games':games, } return render(request,'combined.html', context) #combined.html ....... {% for game in games %} <div class="col"> <a href="{{ game.get_absolute_url }}"> {{ game.game_name }} </a> {% endfor %} ..... My Expections When I refleshed the page l found no error. But when I tried clicking on the link, It returned an error that Page not found Now l would like to know how make it pass successfully and take me to the slug link added when creating the object. E.g When clicking on the action game on the combined page when it was created in the Action models it must redirect me to the slug link page but just returns me 404 Page not found -
bootstrap 5 tabs not working in Django template on click no action
my base.html contains on head: <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}Orphea{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Professional T"> <meta name="author" content="philippe Haumesser"> <link rel="icon" href="{% static 'images/favicons/favicon.ico' %}"> {% block css %} <!-- Bootstrap CSS --> <!-- Latest compiled and minified Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Your stuff: Third-party CSS libraries go here --> <!-- This file stores project-specific CSS --> <link href="{% static 'css/project.css' %}" rel="stylesheet"> {% endblock %} <!-- Le javascript ================================================== --> {# Placed at the top of the document so pages load faster with defer #} {% block javascript %} <!-- Bootstrap JS --> <script defer src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js" integrity="sha512-OvBgP9A2JBgiRad/mM36mkzXSXaJE9BEIENnVEmeZdITvwT09xnxLtT4twkCa8m/loMbPHsvPl0T8lRGVBwjlQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- Your stuff: Third-party javascript libraries go here --> <!-- Popper.js for Bootstrap --> <script src="https://unpkg.com/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz4fnFO9gybBud7M4aw3bN3q5jUQ1g8B5lDfzj5p13bVEE2W5h5+gaawxI" crossorigin="anonymous"></script> <!-- place project specific Javascript in this file --> <script defer src="{% static 'js/project.js' %}"></script> {% endblock javascript %} </head> It is Cookiecutter base except one modification for popper.js My template is : {% extends 'base.html' %} {% load crispy_forms_tags %} {% block javascript %} <script type="text/javascript"> const commandeFormset = document.querySelector('#commande-formset'); const addCommandeFormButton = document.querySelector('#add-commande-form'); const emptyCommandeForm = ` {% with form=formset.empty_form %} <tr … -
enabling submit button based on input
There is a form having a textarea and a submit button I want the submit to be enabled and disabled based on 'if there is any input in the textarea' both the submit and content is being selected correctly (ill send a screenshot of it) JS file: document.addEventListener('DOMContentLoaded',() => { document.querySelector('#all-posts').addEventListener('click', () => loadAllPosts()) if (document.querySelector('#following') != null){ document.querySelector('#following').addEventListener('click', () => loadFollowing()) } loadAllPosts(); }); function loadAllPosts(){ document.querySelector('#allPosts-view').style.display = 'block'; document.querySelector('#following-view').style.display = 'none'; fetch('/api/post') .then(response => response.json()) .then(data => { const posts = data.data.posts; const postCards = posts.map(post => { let likeBtnClass = 'fa fa-heart-o'; if (post.liked_by_user) { likeBtnClass = 'fa fa-heart'; } const on = new Date(post.posted_on).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' }); return ` <div class="card text-white bg-dark mb-3" style="margin-bottom: 5px;"> <div class="card-body"> <h5 class="card-title">${post.posted_by.username}</h5> <p class="card-subtitle mb-2 text-muted" style="font-size: 12px;">${on}</p> <hr style="border: none; height: 1px; background-color: #FFFFF0; margin: 0px;"> <p class="card-text" style="margin-top: 5px; font-size: 25px;">${post.content}</p> <div class="like-container"> <i id="like-btn" class="${likeBtnClass}" style="font-size:24px; cursor:pointer; margin-right: 10px;"></i> <p class="card-subtitle mb-2 text-muted" style="margin-top: 0.5rem; padding: 0px; font-size: 12px;">${post.likes}</p> </div> </div> </div> `; }); document.querySelector('#allPosts-view').innerHTML += postCards.join(''); }) .catch(err => console.error(err)); const likeBtnsContainer = document.querySelector('#allPosts-view'); likeBtnsContainer.addEventListener('click', (event) => { if (event.target.matches('#like-btn')) { event.target.classList.toggle('fa-heart'); event.target.classList.toggle('fa-heart-o'); … -
How can I create relationship in 3 django models
Is it possible to create Microsoft Access Design View in django, I want to create something similar to Microsoft Access Design View in django model using these model: class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('boolean', 'boolean'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) def __str__(self): return self.data_type class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) class Table(models.Model): number = models.IntegerField() character = models.CharField(max_length=30) check_box = models.BooleanField() date = models.DateField() image = models.ImageField(upload_to='image-table') I successfully created 30 Column in the form: From .forms import ColumnForm From django.forms import modelformset_factory def design(request): ColumnFormSet = modelformset_factory(Column, fields = ('name', 'selec_type'), extra=30) formset = ColumnFormSet if request.method == 'POST': formset = ColumnFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('Home') else: formset = ColumnFormSet() return render (request, 'design.html', {'formset':formset}) Using this view, a user can create a name of a field and assign it to the data type that a user want the field to be stored. My problem here is the Table model, where user can store all the information based on the Column table he created or design. How can I archive that using django, which method should I use to make that happen? -
I can not start the server in any way due to problems with installing libraries and starting wheels
I need to run this server on Django and React, I cloned it to myself, went to the "ozone-framework-python-server" folder, created a virtual environment and tried to install the libraries "pip install -r requirements.txt", but I got such errors I work for Windows Building wheels for collected packages: lxml, psycopg2-binary Building wheel for lxml (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [97 lines of output] - - - error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.35.32215\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for lxml Running setup.py clean for lxml Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 - - - It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. … -
Django: Group by and return multiple fields
In Django, Consider the following model class, class Report(models.Model): owner = models.ForeignKey( to=Owner, on_delete=models.CASCADE, related_name='data', ) balance = models.PositiveIntegerField() report_date = models.DateField() Assume this table has only the following four items, <QuerySet [{'owner': 1, 'balance': 100, 'report_date': datetime.date(2023, 3, 4)}, {'owner': 1, 'balance': 50, 'report_date': datetime.date(2023, 3, 9)}, {'owner': 2, 'balance': 1000, 'report_date': datetime.date(2023, 2, 2)}, {'owner': 2, 'balance': 2000, 'report_date': datetime.date(2023, 2, 22)}]> a simple group by owner and aggregating the minimum of report_date will be as follows, Report.objects.values('owner').annotate(min_report_date=Min('report_date')).values('owner', 'min_report_date') and the result will be as follows, <QuerySet [{'owner': 1, 'min_report_date': datetime.date(2023, 3, 4)}, {'owner': 2, 'min_report_date': datetime.date(2023, 2, 2)}]> Now I want to return the balance corresponding to the minimum of report_date field in addition to the owner and min_report_date fields like bellow, <QuerySet [{'owner': 1, 'min_report_date': datetime.date(2023, 3, 4), 'balance': 100}, {'owner': 2, 'min_report_date': datetime.date(2023, 2, 2), 'balance': 1000}]> My attempt was the bellow Django query, Report.objects.values('owner').annotate(min_report_date=Min('report_date')).values('owner', 'min_report_date', 'balance') but the result lost the effect of aggregation (i.e., all rows were returned) and was like bellow, <QuerySet [{'owner': 1, 'balance': 50, 'min_report_date': datetime.date(2023, 3, 9)}, {'owner': 1, 'balance': 100, 'min_report_date': datetime.date(2023, 3, 4)}, {'owner': 2, 'balance': 2000, 'min_report_date': datetime.date(2023, 2, 22)}, {'owner': 2, 'balance': 1000, 'min_report_date': datetime.date(2023, … -
Getting error during Django-MongoDB model migration
i've created a new model in the existing models.py file in my project and i'm trying to migrate this one specific model(not all) to the mongodb database,and it gives an error on performing the command.What exactly am i doing wrong here? Here is what i did:- I ran the command below ('Passengerems' is the model that i'm trying to migrate) python manage.py makemigrations flights --database=mongodb --name=Passengerems And it gave me the following error: (https://i.stack.imgur.com/3ikim.png) Even if i set it to default database by removing('--database')in above command,it gives another error:- "No installed app with label 'flights=mongodb'. I have also properly defined the databases in settings.py here Installed apps of django code block<-Also added the necessary apps too And also lastly,the mongodb server with 'airport' database is also running in the background. Can anyone please help me rectify this error? -
Finding a Real Time Dummy API provider
I am testing an app that updates its information in real time, and I am trying to use either REST API or Websockets to (fetch)GET the data. However I am unbale to find a service that provide an API that updates (hopefully in seconds) in regular intervals, so I can do the testing. I have tried several online tools, such as https://jsonplaceholder.typicode.com/, https://reqres.in/, and various others, The thing is none of them gives information that updates in regular intervals: either in seconds or minutes. -
Django CSRF Verification Failed Despite Correct Token
I'm having trouble with CSRF verification in Django. Despite including the correct CSRF token in my POST requests and following all the recommended steps in the Django documentation, I keep getting a "CSRF Missing" error. Here are my Axios and Django configurations. const service = axios.create({ baseURL, timeout: 4000, withCredentials: true, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', }); ... headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, # settings.py CSRF_COOKIE_NAME = 'csrftoken' CSRF_HEADER_NAME = 'X-CSRFToken' CSRF_TRUSTED_ORIGINS = [ 'http:127.0.0.1:5173' ] CORS_ALLOW_CREDENTIALS = True @ensure_csrf_cookie def get_csrf_token(request): request.META["CSRF_COOKIE_USED"] = True return JsonResponse({'msg': 'now csrftoken has been set in ur Cookies'}) When I send a POST request, the request headers already include the required X-CSRFToken and Cookie ` , but I still receive a 403 response. Here's what I've tried so far: Ensuring that the CSRF token as an X-CSRFToken header Checking that my browser is not blocking third-party cookies Changing the CSRF cookie name in my Django settings None of these solutions have worked for me. Does anyone have any other suggestions or ideas on how to fix this issue? Thanks in advance for your help! -
How to convert Django django.db.models.utils.Row to dict
For example a row like this: Row(added=datetime.date(2021, 2, 23), item='python knowledge', price=6301.0) I need this with whatever fieldname and value: { added:'2021-2-23', item:'python knowledge', price:6301.0 } In other words how I can loop through a row and store values in Dictionary generally? What I tried already: r=dict(row) #cannot convert dictionary update sequence element #0 to a sequence r=set(row) #It does work BUT lost field names r=dict(row.values())#'Row' object has no attribute 'values' r=json.dumps(row,default=str) #It does work BUT lost field names Thank you for your time. -
Embed Bokeh server with Django
I have tried to build a framework for a Django Bokeh application, but can't choose the bokeh server in a separate thread, so use server_document to build a script that can be sent to an html page. When I start the Django dev server and go to the demo.html page, the plot will not appear. I suspect that the Bokeh server may not have started correctly. But unable to see any solution here. demo.py (Bokeh application) from bokeh.plotting import figure from bokeh.layouts import column from bokeh.server.server import Server def modify_doc(doc): x_values = [1, 2, 3, 4, 5] y_values = [6, 7, 2, 4, 5] # Create a figure object fig = figure(title='Simple Bokeh Plot', x_axis_label='X-axis', y_axis_label='Y-axis') # Add a line glyph to the figure fig.line(x_values, y_values) # add the plot and slider to a layout and add to the document layout = column(fig) doc.add_root(layout) Bokeh_server = Server({'/': modify_doc}) view.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.shortcuts import render import threading import asyncio from bokeh.embed import server_document from tavla.bokehapp.demo import Bokeh_server def demo(request): script = server_document('http://localhost:5006/') return render(request, 'tavla/demo.html', {'script': script}) def start_bokeh_server(): Bokeh_server.start() if __name__ == '__main__': bokeh_thread = threading.Thread(target=start_bokeh_server) bokeh_thread.start() demo.html: {% extends "blog/base.html" %} … -
Django: Inconsistent "Page Not Found" Behaviour
I am currently working on a simple Asset Manager program in Django. In assman.html, there is this code snippet which deals with changing the details of an asset: {%if change_form%} <h2>Change Asset Details</h2> <form method="POST" name='change_asset' action="{% url 'assman_handler' %}"> {% csrf_token %} {% if NoSuchUser %} <script>window.alert('No such user!')</script> {% endif %} <table> <tr> <td><label for="qrcode">QR Code:</label></td> <td><input type="text" name="qrcode" class="form-control" id="qrcode" maxlength='13' value = "{{ asset.qrcode }}" required></td> </tr> <tr> <td><label for ="name" required>Asset Name: </label></td> <td><input type="text" name="name" class='form-control' value = "{{ asset.name }}" required ></input></td> </tr> <tr> <td><label for="user_id">User:</label></td> <td> <select name="user_id"> {%for user in users%} <option value="{{ user.id }}" {% if user.id == asset.user.id %}selected{% endif %}>{{ user.username }}</option> </option> {%endfor%} </select> </td> </tr> <tr> <td><label for="checkout_date">Checkout Date:</label></td> <td><input type="date" name="checkout_date" class="form-control" id="checkout_date" value = "{{asset.checkout_date}}" required></td> </tr> <tr> <td><label for="location">Location:</label></td> <td><input name="location" class="form-control" id="location" value = "{{asset.location}}" required></td> </tr> </table> <button type="submit" class="btn btn-primary" value='confirm' name='value'>Confirm Changes</button> </form> {%endif%} This form is previously summoned by clicking the button "change" as described in this code: <h2>Matched Items</h2> {%for asset in matches%} <li> {{asset.name}} at {{asset.location}} owned by {{asset.user}} expiring on {{asset.checkout_date}}</li> <form method="POST" action="{% url 'assman_handler' %}" style="display: inline-block;"> {% csrf_token %} <input type="submit" name="value" … -
Why can't I access MEDIA_URL or MEDIA_ROOT on my urls.py file?
Just trying to add on to my path but when I try adding MEDIA_URL OR MEDIA_ROOT, it just doesn't want to appear. I don't know if there's another method to this. I'm on Django v4.1.7 urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('base.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/images/' MEDIA_ROOT = 'static/images' CORS_ALLOW_ALL_ORIGINS = True urls.py settings.py I was expecting to for MEDIA_ROOT OR MEDIA_URL to appear right after 'settings.' but it didn't. All I want to do is extend the path. -
Django chat-fetch optimization
everyone, I am currently building a chat app using Django. In order to keep the app real time, I am making an API fetch from the Database every second using JSON and refreshing some parts (that contain the messages) of the page. As a result, a lot of queries are being sent to the database every second per user. Is there a better way to load these messages in real time? Please help. Thank you. PS: I wish to write custom code for the app and thus am not using any modules like django-channels. If you could suggest something NOT using this, I would be greatfull. -
Gunicorn Container: No module named 'app.wsgi.application'; 'app.wsgi' is not a package
I've created a python container to statically compile a simple django application, for use with WSGI, aptly named app hereafter. Dockerfile ## Stage 1: Install Python requirements into wheels path FROM python:3.9 as builder # Dont write .pyc to image or we cant build cryptography ENV PYTHONDONTWRITEBYTECODE 0 # Ensure all output is flushed to stdout ENV PYTHONUNBUFFERED 1 # Dont build crypto with rust ENV CRYPTOGRAPHY_DONT_BUILD_RUST 1 RUN apt-get update \ && apt-get install -y \ ca-certificates \ gettext \ libjpeg-dev \ libpq-dev \ libffi-dev \ postgresql-client \ zlib1g-dev WORKDIR /wheels COPY ./${REQUIREMENTS:-requirements/development.txt} /wheels/requirements.txt RUN pip install -U setuptools pip \ && pip wheel -r ./requirements.txt ## Stage 2: Build the Python wheels statically FROM python:3.9 as base ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE="app.settings" COPY --from=builder /wheels /wheels RUN pip install -U pip \ && pip install --no-cache-dir --no-index \ -r /wheels/requirements.txt \ -f /wheels \ && rm -rf /wheels \ && adduser --system --home /var/task --shell /sbin/nologin --no-create-home --disabled-password --disabled-login service \ && ln -s /dev/stdout /var/log/gunicorn-error.log \ && ln -s /dev/stdout /var/log/gunicorn-access.log \ && chmod o+w /dev/stdout COPY . /var/task/ WORKDIR /var/task # Precompile the application RUN python3 scripts/compile.py /var/task # Stage 3: Build a contianer FROM base …