Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I couldn't play the audios that were uploaded to admin
I created a new class in my model.py file: class Audio(models.Model): ..... audio_object = models.FileField(default='') And I uploaded my audios to my admin page. However, the audios don't play and I right-clicked to a new browser, it shows "Page Not Found" saying "The current path, appname/“/media/nameoftheaudio.mp3”, didn't match any of the URLconf defined in projectname.urls. I reviewed the answers from Django MEDIA_URL and MEDIA_ROOT but it didn't solve my problems. In my urls.py, I already have: from django.conf import settings from django.conf.urls.static import static urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my setting.py, I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Another piece of information is the audios I uploaded to another class work fine! And that is the first class model I created in this project. I can't detect what do I lack for this Audio class. I am using Django 3.0.4 Thank you!! -
Django enclosing substring in string with anchor tags with href attribute
Right now im using regex to search for the substring in a given string then enclosing it in anchor tags with href that is in jinja template pattern = re.compile(rf"({substring})",re.IGNORECASE); anchoredString = mark_safe(re.sub(pattern, "<a href=\"{% url 'url' substring %}\">"+substring+"</a>"),string))) The tags work fine but when I click on the link, it tries to redirect me to the literal "{% url 'url' substring %}" not the "url" path that I defined in my urls.py. Is there a better way of doing this? -
Django/AJAX - New data is not getting rendered after first jQuery AJAX call (i.e. on subsequent calls)
I have tried to set the cache property to false on the AJAX request, but it did absolutely nothing. I am implementing a JS calendar and when you click on any day, it opens a popup overlay that also includes another calendar. This second calendar is opened via ajax, and everything seems to be working on the first call which renders: Then, upon closing the overlay and clicking another date on the calendar, I always get the first overlay, no matter how many times I click. The AJAX call $.ajax( { type:"POST", url: "/teachers/teacherDayAgenda/", data:{ 'event_date': dateClicked }, dataType: 'json', cache: false, success: function( eventData ) { var lessonEvents = []; var lesson = {}; for (var key in eventData) { if (key=="eventDefault") break; lesson = {}; lesson['title'] = "Lesson with "+eventData[key]['teacher_name']; lesson['start'] = formatDate(moment(eventData[key]['timeslot_start']).toDate()); lesson['end'] = formatDate(moment(lesson['start']).add(40, 'm').toDate()); lessonEvents.push(lesson); } console.log(eventData); $('#teacher_schedule').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'agendaDay,listWeek' }, defaultDate: eventData['event0']['click_event_date'], navLinks: true, eventLimit: true, events: lessonEvents }); $("#teacher_schedule .fc-agendaDay-button").trigger("click"); /*$('td').removeClass('AddEventPopup_open'); */ } }); The View: @login_required def teacherDayAgenda(request): """ Ajax request for popup overlay, changes to student schedule, see day agenda of availability of teachers """ if request.method == 'POST': click_event_date = request.POST['event_date'] studentid = … -
Suddenly `Error loading MySQLdb module` happens
I am using django system but suddenlyt this error happens. I try to re-install mysqlclient, but situation doesn't change. $pip uninstall mysqlclient $pip install mysqlclient Before it works well but suddenly this error happens. I did rbenv re-install yesterday , is that related??? $python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib Referenced from: /usr/local/opt/mysql@5.7/lib/libmysqlclient.20.dylib Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/whitebear/anaconda3/envs/myapp/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
Issue Connecting to Google Cloud Database
I'm using a postgresql database on the google cloud and I'm trying to create a script to receive API requests using python. This is the error I'm currently getting when I send get requests: 127.0.0.1 - - [12/Apr/2020 22:50:20] "GET / HTTP/1.1" 500 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pg8000/core.py", line 1152, in init self._usock.connect(unix_sock) FileNotFoundError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2285, in _wrap_pool_connect return fn() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 303, in unique_connection return _ConnectionFairy._checkout(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 773, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 492, in checkout rec = pool._do_get() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 139, in _do_get self._dec_overflow() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in exit exc_value, with_traceback=exc_tb, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 136, in _do_get return self._create_connection() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 308, in _create_connection return _ConnectionRecord(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 437, in init self.connect(first_connect_check=True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 657, in __connect pool.logger.debug("Error on connect(): %s", e) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit exc_value, with_traceback=exc_tb, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 652, in connect connection = pool._invoke_creator(self) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect … -
'WSGIRequest' object has no attribute 'data' in django rest_framework
in model.py create a class in which 3 fields are there class signUp(models.Model): username = models.CharField(max_length=100) email = models.EmailField() password = models.IntegerField() in serializer.py class SignupSerializer(serializers.Serializer): class Meta: model = signUp fields = ('username', 'email', 'password') def create(self, validated_data): email = validated_data['email'], name = validated_data['name'], password = validated_data['password'] return signUp.objects.create(**validated_data) in views.py @csrf_exempt def signup(request): if 'username' not in request.data: response = {'message': 'please enter username'} return Response(response, status=status.HTTP_400_BAD_REQUEST) elif 'email' not in request.data: response = {'message': 'please enter email'} return Response(response, status=status.HTTP_400_BAD_REQUEST) elif 'password' not in request.data: response = {'message': 'please enter password'} return Response(response, status=status.HTTP_400_BAD_REQUEST) if request.method == 'GET': signup = signUp.objects.all() serializer = SignupSerializer(signup, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': data = JSONParser().parse(request) serializer = SignupSerializer(data=data) if serializer.is_valid(): user = serializer.validated_data.get('username') message = f'successfully signup {user}' return Response({message: message}, status=HTTP_200_OK) i am new in django i want to make api to register user by post method and get details of user by get method ... -
Delete a user's file after some days after the user is deleted in Django
In my Django application, I want to delete a user's media file(their profile picture and other images) after 4-5 days when the user deletes its account. def delete_files(sender, instance, **kwargs): path = str(os.getcwd()) try: pathdl = f"{path}\\data\\media\\{instance.username}" shutil.rmtree(pathdl) except Exception: print(Exception) post_delete.connect(delete_files, sender=User) I used post_delete to delete the files of the user, but how can I delete the file after 4-5 days or a certain time period. -
Hoe to change the position of pagination on django?
I have a pagination bar below but I want it at the top. So I made an HTML file where I will override the template. But I can't understand how to pick that paginator class and how to move it to the top? Any Suggestion or Idea ???? -
Static properties not changing in Django
I have a website that I am working on and I wanted to change the css a bit to fit the content (change height of a container). However, after applying the changes when I reload my page, the change does not appear in the website. I'm pretty sure I have linked the static files in the right way since not doing so would not render my website as expected. I have tried doing the same changes to a separate copy not linked with django, and it worked. Anyone know whats going wrong? -
docker-compose up on Django in Docker container just prints "exited with code 0" rather than "Starting Development Server"
Dockerfile # The first instruction is what image we want to base our container on # We Use an official Python runtime as a parent image FROM python:3.7 FROM registry.gitlab.com/datadrivendiscovery/images/primitives:ubuntu-bionic-python36-v2020.1.9 # The enviroment variable ensures that the python output is set straight # to the terminal with out buffering it first ENV PYTHONUNBUFFERED 1 # create root directory for our project in the container RUN mkdir /bbml # Set the working directory to WORKDIR /bbml # Install any needed packages specified in requirements.txt RUN pip install -r requirements.txt RUN pip install --upgrade pip COPY . /bbml/ CMD [ "python", "./manage.py runserver 0.0.0.0:8000" ] docker-compose.yml version: '3' services: web: build: . volumes: - .:/bbml ports: - "8000:8000" I try to run 'docker-compose up' and according https://docs.docker.com/compose/django/(sort of this is definitely outdated) and all that happens is this $ docker-compose up Starting a7897a5e26de_blackboxmlsolutions_web_1 ... done Attaching to a7897a5e26de_blackboxmlsolutions_web_1 a7897a5e26de_blackboxmlsolutions_web_1 exited with code 0 It's supposedly supposed to start up the server in the container, but it does not. If anyone has any references for running and developing Django in Docker on Windows that'd be great I'm not having much luck getting this working. I don't even have a DB setup and it's … -
Modal to confirm delete
I have a form for creating products and editing existing products. I can submit changes just fine but when I added a delete button that opens a modal to confirm the delete I've run into some unexpected problems. template.html <div class="container-fluid"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form|crispy}} {{form.errors}} <button type="submit" class="btn btn-primary btn-block"><i class="fa fa-upload"></i> Upload</button> {% if instance %} <button class="btn btn-danger btn-block" data-toggle="modal" data-target="#exampleModalCenter"><i class="fa fa-trash"></i> Delete</button> {% endif %} </form> </div> <div class="m-4"> {% for product in products %} <a href="{% url 'main:update_product_view' slug=product.slug %}"> <h2>{{product.product_title}}</h2> </a> {% endfor %} </div> {% if instance %} <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Confirm Action</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to delete {{instance.product_title}}? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <a href="{% url 'main:delete_product_view' instance.slug %}"><button type="button" class="btn btn-danger"><i class="fa fa-trash"></i> Delete</button></a> </div> </div> </div> </div> {% endif %} views.py def create_product_view(request): if request.method == "POST": form = CreateProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.save() return redirect('main:homepage_view') else: form = CreateProductForm context = { "title": "Create - Product", "form": form, } return render(request=request, … -
Django: Is annotating twice with same lookup a bad practice?
I want to annotate a queryset to filter with this annotation. In some cases, my queryset might already have the annotation set. What happens if I annotate my queryset twice (same lookup, and same values): Does it perform unnecessary jobs on the DB side? Example: queryset = MyModel.objects.annotate(my_annotation=F("some stuff")).filter(my_annotation="some other stuff") # a bit later queryset = MyModel.objects.annotate(my_annotation=F("some stuff")).filter(my_annotation="some other stuff") If yes, how can I check the already annotated lookups without evaluating my queryset? -
Add another and remove is not showing django formset is anythng i missed in html
I have created a formset, which is showing in html but its not showing add another or delete links. When I check the console. I am getting an error like this also, custom.min.js:1 Uncaught TypeError: $(...).slimScroll is not a function at HTMLDocument.<anonymous> (custom.min.js:1) at c (jquery.min.js:3) at Object.fireWith [as resolveWith] (jquery.min.js:3) at Function.ready (jquery.min.js:3) at HTMLDocument.H (jquery.min.js:3) Is this happening because of above error or i missing something in my code. I am attaching my code below. i already tried to add id's which is not working(inside the loop). forms.py class ImageForm(forms.ModelForm): class Meta: model = ProductImage fields = ('item','images') ImageFormset = formset_factory(ImageForm) views.py class CreateProduct(View): def get(self, request): form = ProductForm() formsetx = ImageFormset(prefix='formsetx') context = { 'form' : form, 'formsetx' : formsetx, 'title' : 'Add Product', 'sub_title' : 'Product', } return render(request, 'f_supp/add_product.html', context) add_product.html <form class="uk-form-stacked" method="POST" action="{% url 'f_supp:add-product' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <table cellpadding="0" cellspacing="0" class="table"> <tr> <th>Images</th> <th>Item</th> </tr> {% for f in formsetx.forms %} {{ f.id }} <tr class="form_set_rowp5"> <td> <span class="input1"> {{ f.images }} </span> </td> <td> <span class="input1"> {{ f.item }} </span> </td> <td>{% if f.instance.pk %}{{ f.DELETE }}{% endif %}</td> </tr> {% endfor %} </table> {{ … -
Passing request to messages.error in TemplateView Class
I'm replacing my view defs with classes. I first tried a View: class DiscoverView(View): def get(self, request): page_name = 'discover' try: page = Pages.objects.get(name='discover') except (Pages.DoesNotExist, Pages.MultipleObjectsReturned): messages.error(request, 'Page is not configured: ' + page_name) return redirect('MS_Home') context = { 'page': page, } return render(request, 'base/discover.html', context) This worked fine. I next decided to do a TemplateView with an intervening parent class to try to stay dry. class PageView(TemplateView): def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) page_name = kwargs['page_name'] try: page = Pages.objects.get(name=page_name) except (Pages.DoesNotExist, Pages.MultipleObjectsReturned): messages.error(self.request, 'Page is not configured: ' + page_name) return redirect('MS_Home') context['page'] = page return context class AboutView(PageView): template_name = 'base/about.html' def get_context_data(self, *args, **kwargs): kwargs['page_name'] = 'about' context = super().get_context_data(**kwargs) return context The normal path works. When the exception is thrown, it dies on the message.error: context must be a dict rather than HttpResponseRedirect. If I take out self.request in the messages.error() call, it complains about a missing parameter so I'm pretty sure it doesn't like self.request. How should I pass request to messages.error()? -
How to use html snippets into django template in vscode?
I want to write HTML snippets when I'm using the Django Template but Visual Studio Code doesn't recognize them. I installed HTML Snippet extension but didn't work. I know that i can use HTML template and install django snippets but i want to do the said before. some help? -
Django TransactionManagementError: select_for_update cannot be used outside of a transaction
I am using multiple db environment using DJANGO_DB_ROUTERS. But I am facing this error. TransactionManagementError: select_for_update cannot be used outside of a transaction. Django transaction is used inside django library so I can't use using=db_name. Both read and write are only happening from master but even after I am getting this error ----> 1 create_type(t()) ~/setup.py in create_type(t) 1791 object_identifier=oi, 1792 tenant=t, -> 1793 defaults=data 1794 ) 1795 ~/backend/venv/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs) 80 def create_method(name, method): 81 def manager_method(self, *args, **kwargs): ---> 82 return getattr(self.get_queryset(), name)(*args, **kwargs) 83 manager_method.__name__ = method.__name__ 84 manager_method.__doc__ = method.__doc__ ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in update_or_create(self, defaults, **kwargs) 501 with transaction.atomic(using=self.db): 502 try: --> 503 obj = self.select_for_update().get(**lookup) 504 except self.model.DoesNotExist: 505 obj, created = self._create_object_from_params(lookup, params) ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 395 if self.query.can_filter() and not self.query.distinct_fields: 396 clone = clone.order_by() --> 397 num = len(clone) 398 if num == 1: 399 return clone._result_cache[0] ~/cftr/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in __len__(self) 252 253 def __len__(self): --> 254 self._fetch_all() 255 return len(self._result_cache) 256 ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in _fetch_all(self) 1177 def _fetch_all(self): 1178 if self._result_cache is None: -> 1179 self._result_cache = list(self._iterable_class(self)) 1180 if self._prefetch_related_lookups and not self._prefetch_done: 1181 self._prefetch_related_objects() ~/backend/venv/lib/python3.6/site-packages/django/db/models/query.py in __iter__(self) 51 # Execute the query. This will also fill compiler.select, klass_info, … -
Apache2.4 + Django 3 - No module named 'django'
I am trying to configure my first Django + Apache application. I am using Django 3.05, Python 3.8, Ubuntu 16.04 and Apache 2.4.18. I encountered the No module named 'django' error. Target WSGI script '/srv/tacdb/mysite/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/srv/tacdb/mysite/wsgi.py'. Traceback (most recent call last): File "/srv/tacdb/mysite/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' If I activate the virtual environment and run the server, it works just fine. This is my wsgi.py: import os from mysite.wsgi import get_wsgi_application os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" application = get_wsgi_application() This is the apache configuration file: Listen 80 <VirtualHost *:80> ServerName ServerAdmin ServerAlias DocumentRoot /srv/tacdb Alias /static /srv/tacdb/mysite/static WSGIDaemonProcess mysite python-home=/srv/tacdb/venv python-path=/srv/tacdb WSGIProcessGroup mysite WSGIScriptAlias / /srv/tacdb/mysite/wsgi.py <Directory /srv/tacdb/mysite> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/tacdb_error.log CustomLog ${APACHE_LOG_DIR}/tacdb_access.log combined </VirtualHost> I have installed the latest version of mod_wsgi. sudo apt-get install libapache2-mod-wsgi-py3 I am logged in as root. The structure of my project is: . └── tacdb ├── manage.py ├── mysite │ ├── admin.py │ ├── apache-site2.conf │ ├── apache-site.conf │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── tacdashboard │ ├── templates │ ├── urls.py … -
Django- How to read uploaded excel file in django
I am trying to upload multiple excel files in django and save it to a folder. Once the files have been saved I want to select the file on the GUI and show the data from that file. How do I handle reading particular file from the folder? -
create_user not returning full user object of the newly created user
I am doing simply: user = User.objects.create_user(**data) print(user['id']) # user.pk dont work. If i do print(user), I see username of the newly added user. Is there a way to return the user id along with first_name? Or must I query the model with the user name to get user details of the newly added user? -
Registration information not saving to database in Django
The registration part of the code does not work. After creating a new user it just redirects to the registration page and I can not figure out why. Also is there a way to edit the username and password elements in the RegisterForm like I did with the email element? forms.py from django import forms from django.contrib.auth import authenticate, models from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=100, required=True, widget=forms.EmailInput(attrs={'class': 'form_control', 'name': 'email', 'id': 'email', "placeholder": 'Your class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.username = self.cleaned_data user.email = self.cleaned_data user.password1 = self.cleaned_data if commit: user.save() return user views.py def addUser(request): if request.method == 'POST': form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return redirect('home') else: form = RegisterForm() args = {'form': form} return render(request, 'login_register/register.html', args) register.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Register</title> <!-- Font Icon --> <link rel="stylesheet" href="{% static 'login_register/fonts/material-icon/css/material-design-iconic-font.min.css' %}" /> <!-- Main css --> <link rel="stylesheet" href="{% static 'login_register/css/style.css' %}" /> </head> <body> <div class="main"> <!-- Sign up form --> <section class="signup"> <div … -
Nginx isn't Serving Django Static Files Correctly Because of Trailing Slash
Currently, I have a Django web app being served by Gunicorn. Gunicorn does not serve static file requests so I am using Nginx in front of Gunicorn to serve static file requests. I am able to containerize the app fine with Docker and can successfully serve application requests but Nginx cannot serve the static file requests correctly because Django appends a trailing slash to static file requests. After running the Docker container with Django, Nginx, and Postgres services, I navigate to the home page of the web app and the first request is fine. HTTP Request 200 The rest of the incoming requests after navigating to the home page of the web app are static file requests all with 404 error codes. HTTP Request 404 The 404 error codes indicate that the server cannot find the static files but I can verify that my static files are stored in the correct location and are present. The 404 error codes are happening because Django static file requests append a trailing slash to the request. So, after reading the Nginx documentation, I discovered that Nginx treats all static file requests with trailing slashes as requests for directories and thus searches for an … -
Is sometimes single complicate query worse than two separate query?
I just came into the article on Django that says, when the amount of data is so huge it's better to split it and send them separately. I'm not really sure about this, because as far as I know, DBMS itself is so optimized and the networking is what causes the greatest portion of the latency. Are there really any cases like this? -
Django: Can't redirect to list page after clicking Submit button
Sorry for the long-ass post. I have a problem with my "update_fisher" view. It doesn't redirect to the "list_fishers" view after clicking the "Submit" button. What wonders me more is that "create_fisher" view uses the same html file for submitting forms, but it executes successfully. Here is the code for more details: fishers/views.py ... @ staff_member_required def create_fisher (request): form = FisherForm(request.POST or None) if form.is_valid(): form.save() form = FisherForm() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'form' : form} return render (request, template_name, context) @ staff_member_required def update_fisher (request, fisher_id): items = get_object_or_404(Fishers, fisher_id = fisher_id) form = FisherForm(request.POST or None, instance = items) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("fishers:list_fishers")) template_name = "fisher_form.html" context = {'fishers' : items, 'form' : form} return render (request, template_name, context) ... fishers/urls.py from django.urls import path from . import views # this is responsible for the "namespace" in admin > urls.py app_name = 'fishers' # urlpatterns = [ path('', views.list_fishers, name = "list_fishers"), path('add_fisher/', views.create_fisher, name = "create_fisher"), path('update_fisher/<int:fisher_id>', views.update_fisher, name = "update_fisher"), fishers/templates/fisher_form.html {% extends "base.html" %} <title> {% block title %} Add/Update Information {% endblock %} </title> {% block content %} <div class = "page-header"> <h2> Fisher's Information </h2> </div> <form method … -
How to optimize django-import-export?
I have a data in Excel around 20,000 records. I using django-import-export extension for import data.I tried to import data but very slow about 10 minute. I think one thing to make it slow that is django-import-export render 20,000 records on preview table. I want to know how to speedup ? -
requests.post from python script to my Django website hosted using Apache giving 403 Forbidden
My Django website is hosted using Apache server. I want to send data using requests.post to my website using a python script on my pc but It is giving 403 forbidden. import json url = "http://54.161.205.225/Project/devicecapture" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'content-type': 'application/json'} data = { "nb_imsi":"test API", "tmsi1":"test", "tmsi2":"test", "imsi":"test API", "country":"USA", "brand":"Vodafone", "operator":"test", "mcc":"aa", "mnc":"jhj", "lac":"hfhf", "cellIid":"test cell" } response = requests.post(url, data =json.dumps(data),headers=headers) print(response.status_code) I have also given permission to the directory containing the views.py where this request will go. I have gone through many other answers but they didn't help. I have tried the code without json.dumps also but it isn't working with that also. How to resolve this?