Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I m facing this prblm when I m running my django application on local host I m using atom ide
after starting my server when I open browser then this shows -
How to check whether a object is expired or not in django?
I'm trying to check whether a object is expired or not by using:- if (Token.objects.get(content=token).DatePosted-timezone.now())<'1 days': return False else: return True It is producing following error:- '<' not supported between instances of 'datetime.timedelta' and 'str' my question is hpw can i convert 0 days into a datetime.timedelta object? -
Django on docker container error when trying to connect to local mysql database
Please help me, I have django application that run on docker container with docker-compose, but i have error when trying to connect to mysql database on my local machine. The error message is like this : Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ my docker-compose.yml file is like this : version: '3' services: web: container_name: web build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" and my Dockerfile is like this : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev -y RUN pip install pip -U RUN pip install -r requirements.txt -
ModuleNotFound error in django. PS - virtualenv misbehaving
Something had been wrong with my virtualenv. I never shut pc down nor the text editor with terminal(vs code). I just deactivated vituralenv last night and activated it today to find it's name has changed. I wasn't able to runserver so I figured out something was wrong with virutalenv because on pip freeze it shows all the packages. I installed virtualenv again and made a virtualenv with same name in same directory which overwrote previous virtualenv and now it's fine. Although while executing python manage.py runserver, it shows. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen … -
Django changes dropdown menu to Input Text Fields by itself (CODE HAS DROPDOWN!)
THIS IS THE MODEL.PY file! - class userchoice(models.Model): choice = [] choice2 = list(userdata.objects.all().values_list('key')) for x in choice2: for t in x: choice.append((t,t.capitalize())) Job_ID = models.CharField(primary_key = True, max_length=200, choices=choice, default='key') Group_ID= models.CharField(max_length=200, choices=choice, default='key') Customer_name = models.CharField(max_length=200, choices=choice, default='key') Planned_Duration = models.CharField(max_length=200, choices=choice, default='key') Worker_name = models.CharField(max_length=200, choices=choice, default='key') Job_note = models.CharField(max_length=200, choices=choice, default='key') Customer_tp_name = models.CharField(max_length=200, choices=choice, default='key') AND THIS IS THE MIGRATIONS FILE (DOES NOT MIGRATE CHOICES!!)- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csvfileapp', '0008_userdata'), ] operations = [ migrations.CreateModel( name='userchoice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Job_ID', models.CharField(default='key', max_length=200)), ('Group_ID', models.CharField(default='key', max_length=200)), ('Customer_name', models.CharField(default='key', max_length=200)), ('Planned_Duration', models.CharField(default='key', max_length=200)), ('Worker_name', models.CharField(default='key', max_length=200)), ('Job_note', models.CharField(default='key', max_length=200)), ('Customer_tp_name', models.CharField(default='key', max_length=200)), ], ), ] PLEASE HELP!! -
Django Treebread admin AttributeError - 'Page' object has no attribute 'page_ptr_id'
Please help. Stuck and confused. Trying to use Django Treebread admin to see the tree structure of Journal objects, which inherits from class Page in wagtail. Page inherits from MP_Node in Treebread. models.py from wagtail.core.models import Page class Journal(Page): body = RichTextField(blank=True) admin.py from django.contrib import admin from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from .models import Journal class MyAdmin(TreeAdmin): form = movenodeform_factory(Journal) admin.site.register(Journal, MyAdmin) In Django admin, click Jounal and get error msg as below: AttributeError at /admin/journal/journal/ 'Page' object has no attribute 'page_ptr_id' Request Method: GET Request URL: http://127.0.0.1:8000/admin/journal/journal/ Django Version: 2.2.1 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'page_ptr_id' Exception Location: C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\django\contrib\admin\views\main.py in url_for_result, line 473 Python Executable: C:\Users\Freedom\Anaconda3\envs\myvenv\python.exe Python Version: 3.7.3 Python Path: ['D:\\Python\\Django\\m4ever', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\python37.zip', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\DLLs', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib\\site-packages'] page_ptr_id is actually the Django auto-generated field name for the one-to-one relation from the specific Journal class to the base Page model. Tried define it explicitly in Journal as: page_ptr_id = models.OneToOneField(Page, on_delete=models.CASCADE, parent_link=True) But still get similar error msg, displaying as 'Page' object has no attribute 'page_ptr_id_id' -
Django: How to prevent form resubmission when form validation unsuccessful?
I have looked into this problem with possible duplication but it seems like mine's a different problem. So I have forms which use sessions to temporarily store data. I have also included {{ form.errors }} in my templates to display the errors upon validation. The problem is, when I try to reload the page () when form is invalid/unsuccessful and the errors were displayed, instead of just refreshing the page and clearing the fields as well as the displayed errors, a confirm form resubmission dialog appears and the errors in my form remained. How should I prevent this dialog from appearing? -
Django customize Admin login page
Would it be possible to just reuse the login page? I just want to add sign up button in the login page. But for what I have searched, it needed to customize all in order to override it. <div class="submit-row"> <input type="submit" value="Log in"> <input type="button" value="Sign up" onclick="location.href='/admin/signup'"> </div> Please help. -
Create login session in django
so i try to make a login with session , so user must logged in first before redirect to another page , so i think im doing right , but i dont know how to check if i save the session or not , here's the code views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guess = User.objects.get(username=username) identity = guess.id table2 = UserProfileInfo.objects.get(user_id=identity) role = table2.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': request.session['username'] = username login(request, user) return render(request,'index.html',{"username":username}) elif role == 'Admin': login(request, user) return redirect('/manageuser/') elif role == 'Manager': login(request, user) return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): if request.session.has_key('username'): username = request.session['username'] print(username) return render(request, 'index.html',{"username":username}) settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" When i try to print the username , it wont show in command prompt , i thought i already save the request.session['username'] in … -
NoReverseMatch at /users/login/
'learning.logs' is not a registered namespace. Request Method: GET Request URL: http://localhost:8000/users/login/ Django Version: 2.2.7 Exception Type: NoReverseMatch Exception Value: 'learning.logs' is not a registered namespace settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my_apps 'learning_logs', 'users', ] learning_logs\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls', namespace='users')), path('',include('learning_logs.urls', namespace='learning_logs')), ] users\urls.py from django.urls import re_path, path, include from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ # log in page path('login/', LoginView.as_view(template_name='users/login.html'),name='login'), ] learning_logs\urls.py from django.urls import re_path from . import views app_name = 'learning_logs' urlpatterns = [ # homepage re_path('^$', views.index, name='index'), # show all topics re_path('^topics/$', views.topics, name='topics'), # show dedicated topic re_path('^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), # added new topic re_path('^new_topic/$', views.new_topic, name='new_topic'), # added new entry re_path('^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'), # edit entry re_path('^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), ] login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">log in</button> <input type="hidden" name="next" value="{% url 'learning.logs:index' %}" /> </form> {% endblock content %} base.html <p> <a … -
Django, static files, and horizontal scalabilty
I am making a website in Django, and I am trying my best to make sure it is horizontally scalable. Due to the application being horizontally scalable, I am unable to save Images that users upload locally, in the media folder. I was wondering what are some ways I could save the images that the users upload, in such a way that would allow my application to be horizontal scalable? I do have a MariaDB Galera Cluster that I use to store other data, but it seems like saving images in a shared database might not be the best idea due to performance reasons (Storing Images in DB - Yea or Nay?). If I attempt to use the media folder, are there any solutions that could sync storage (folder) between different instances of the application? In general, what are some good practices for serving(download/upload) static content like images for horizontally scalable websites, and does Django provide anything to assist with this matter out of the box? -
Duplicate queries with inline_formset
In my web application I managed to create an inline_formset that works well. Problem now is when I have let's say 200 rows, each field that has foreign key is called 200 times to generate the drop down menu. I tried to use prefetch but queries are still duplicated, can you please help how to make query only once to get list of dropdown menu ? in forms.py class IssueForm(forms.ModelForm): class Meta: model=Issue fields=('__all__') IssueFormset=inlineformset_factory(IssuesList, Issue, form=IssueForm,extra=0) in views.py class IssuesListUpdateView(UpdateView): model=IssuesList fields='__all__' # ovewrite get_context_data to add formset as an additionnal parameter def get_context_data(self, **kwargs): context = super(IssuesListUpdateView, self).get_context_data(**kwargs) if self.request.POST: # if Save All issues button submitted if 'save_all' in self.request.POST.keys(): formset = IssueFormset(self.request.POST, instance=self.object) # sending formset to the template context['issues_formset'] = formset # save in the DB (saves only what has changed) #https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#saving-objects-in-the-formset # if formset.is_valid(): formset.save() # re-update context with new formset, this is need to refresh table in case of deleting an object # without this, issue is deleted but still visible in the table context['issues_formset'] = IssueFormset(instance=self.object) else: # sending formset to the template issues_formset=IssueFormset(instance=self.object) for form in issues_formset: form.fields["si"].queryset=Si.objects.prefetch_related('si_issues').\ all().filter(product__name='test') context['issues_formset'] = issues_formset return context In template: <form method="post">{% csrf_token %} <!-- … -
How could I make the pop up box stay on the screen so I can press the Ok button before it exits
What I am trying to do is after user click the update button the pop up box shows up on the screen then i can click the ok button to confrim or exit it. But on my code right now it just auto matically close the box after it shows up. Here is my JS if ($(document).find("#show_pop").val() == 1){ swal.fire({ title: "Updated Successfully!", text: "", type: "success", confirmButtonText: "OK" }).then(function(i){ }) } This is from my templates. <input id="show_pop" name="show_pop" value="{{ success }}" type="hidden" readonly> This is from my views.py just on the bottom part.... employee.save() context = { "success": 1, } print(context) return render(request, "index.html", context) -
How to create a membership record for a new user with django_rest_auth and django rest framework
I'm trying to create an invite/acceptance workflow with Django Rest Framework and Django Rest Auth. I have my initial account creation working just fine. Then a user creates a team, no problem. That owner now sends invites. Cool. Email's go out and the invitee get's the email with an ID for the team that they are being invited to. Here's where I'm struggling. There is a membership model that connects a team and a member. When a user has been invited registers, I want to create that membership record. So, where do I put that membership creation method? Is it in the serializer or the view? Django Rest Auth RegistrationView calls the save method of the RegistrationSerializer here. The serializer returns the created user to the view for the response. I know I need to create the membership record AFTER the user is created otherwise there isn't a user to add to membership. But I can't figure out where to do this? I was thinking of creating a create_membership method that is fired after the create method is run, but that isn't working. Something like this: def create_membership(self): team = "6edb0a55-199a-4aae-aa40-e7313186136b" return Membership.objects.create(team__id=team, member=self.user) Then calling it like this (this … -
Logo image in the navbar displays only on home page
The image of my logo on the navbar displays only on the home page, what should I do to fix it? That's root for the image on the navbar: <a class="navbar-brand waves-effect" href="/"> <img src="media\logoBrand.png"> </a> urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('core.urls', namespace='core')) ] if settings.DEBUG: import debug_toolbar urlpatterns += [path('__debug__/', include(debug_toolbar.urls))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And urls.py core: from django.urls import path from django.conf import settings from django.conf.urls.static import static from .views import ( ItemDetailView, CheckoutView, HomeView, OrderSummaryView, add_to_cart, remove_from_cart, remove_single_item_from_cart, PaymentView, AddCouponView, RequestRefundView ) app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', CheckoutView.as_view(), name='checkout'), path('order-summary/', OrderSummaryView.as_view(), name='order-summary'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'), path('add-coupon/', AddCouponView.as_view(), name='add-coupon'), path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'), path('remove-item-from-cart/<slug>/', remove_single_item_from_cart, name='remove-single-item-from-cart'), path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), path('request-refund/', RequestRefundView.as_view(), name='request-refund') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So when i got to homepage the image is displaying, but when I go to let say /checkout/ i get an error in the console: Not Found: /checkout/media/logoBrand.png I am not sure why does it go to this directory Settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' … -
django template timeuntil timezone
I am rendering some meetings with django templates. {% for meeting in m %} <td>{{ meeting.start|date:"j F Y, g:i A" }}</td> <td>{{ meeting.start|timeuntil }}</td> {% endfor %} and view code now = datetime.datetime.now() + datetime.timedelta(hours=-5) m = Meeting.objects.filter( start__gte=now, status=Meeting.PENDING ).order_by("-start") context = { "m": m, } return render(request, "meetings/home.html", context) produces a table like Time Requested Time Pending (hrs) 7 December 2019, 12:00 AM 2 days 5 December 2019, 12:00 AM 12 minutes 4 December 2019, 11:00 PM 0 minutes my browser is in EST time and the api is UTC. The start time is rendered in local time correctly. But the timeuntil countdown is not in the localtime. Is there a good way to achieve the desired output? So far the best thing I can think of is to compute another datetime column with the client's timezone difference applied. Then the template could simply render {{ meeting.start_local|timeuntil }}. -
Programatically create Redirects in Wagtail
Is there a way to programatically create functioning Redirect objects in Wagtail? I am trying the obvious (naively creating the object): Redirect.objects.create(old_path='/test', redirect_link='https://stackoverflow.com') This creates a Redirect that is visible in the Wagtail admin panel, however navigating to /test simply 404s without redirecting. However, if I then save the Redirect from the admin panel, it suddenly works. Is there some special post-save logic I need to run in order to activate the redirect? I looked through the source and could not find anything. -
Pagination menu changing length
I'm paginating some data from a django model. My issue is that I don't know how to control the menu for the pages. I'd like it to show maybe 10 page links at a time and gradually move across. This works to a degree, as it moves forward it will show more, so if on page 1 it will show 1-10, if on page 2 it will show up to 11. The problem is I can't control this in a static fashion. I would like to show 1-10 and then once it gets to 6, display 2-11 and so on. it works from 6 onwards, the problem is at the beginning it will show 1-5, then 1-6, then 1-7 until it gets to 6 when it will look correct. I hope this makes sense.... Here's my html: {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ contacts.previous_page_number }}">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> {% endif %} {% if contacts.number|add:'-4' > 1 %} <li class="page-item"> <a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a> </li> {% endif %} {% for i in contacts.paginator.page_range %} {% if contacts.number == i %} <li class="page-item active"> <a … -
How to have CSS border span the length of the page but have elements remain inside container?
I am trying to create a navigation bar. I have used bootstrap for the body of my site and would like the navigation bar to span the same width. However, I want the border to span the full width; so that the elements 'Home, Learn, Progress, etc' appear to be right above the things in the actual page but not so that the border is cut off. TIA <div class="navbar container"> <div class="navbar-left"> {% url 'quizapp-home' as url %} <a href='{{ url }}' {% if request.path|slice:":6" == url %} id="current" {% endif %}><i class="fas fa-home"></i> Home</a> {% url 'quizapp-learn' as url %} <a href='{{ url }}' {% if request.path|slice:":7" == url %} id="current" {% endif %}><i class="fas fa-pencil-ruler"></i> Learn</a> {% url 'progress' as url %} <a href='{{ url }}' {% if request.path|slice:":10" == url %} id="current" {% endif %}><i class="fas fa-chart-line"></i> Progress</a> </div> <div class='navbar-right'> {% if user.is_authenticated %} {% url 'profile' as url %} <a href='{{ url }}' {% if request.path|slice:":9" == url %} id="current" {% endif %}> Profile</a> {% url 'logout' as url %} <a href='{{ url }}' {% if request.path|slice:":8" == url %} id="current" {% endif %}>Logout</a> {% else %} {% url 'login' as url %} <a … -
Django: ListView Pagination - This page has no results
I'm using a ListView to show all products from model UnitaryProduct. I've set pagination to 9, as there are 12 products for a category the page_num is 2. But when I go to the page 2, I get: "This page has no results". File "D:\virtual_envs\stickers-gallito-app\lib\site-packages\django\core\paginator.py", line 52, in validate_number raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage: Esa página no contiene resultados [04/Dec/2019 17:12:03] "GET /catalogo?page=2 HTTP/1.1" 500 200977 HTML: <div class="d-flex justify-content-between"> <div class=""> <form method="get" action="{% url 'shop:catalogo' %}"> <div class="input-group"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Categorías</label> </div> <select class="custom-select" searchable="Search here.." value={{filtro}} name="filtro"> <option value="todas" disabled selected>Seleccionar categoría</option> <option value="todas">Todas</option> <option value="celulares">Celulares</option> <option value="programacion">Programación</option> <option value="videojuegos">Videojuegos</option> <option value="cine">Cine</option> <option value="series">Series de TV</option> <option value="anime">Anime</option> <option value="musica">Música</option> </select> <div class="input-group-append"> <input class="btn btn-outline-secondary" type="submit" name="buscar" value="Buscar" style="margin-bottom: 0px;" /> </div> </div> </form> </div> <div class=""> {% if is_paginated %} <nav aria-label="..."> <ul class="pagination"> <li class="page-item disabled"> <span class="page-link">Anterior</span> </li> {% for i in page_obj.paginator.page_range %} <li class="page-item"><a class="page-link" href="/catalogo?page={{ i }}">{{ i }}</a></li> {% endfor %} <li class="page-item"> <!--<a class="page-link" href="/catalogo?page={{ page_obj.next_page_number }}"></a>Siguiente</a>--> </li> </ul> </nav> {% endif %} </div> </div> ListView: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 9 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') filter_val … -
Bad request (400) (unsupported syscall) when trying to reach container in Google Cloud Run
I have successfully deployed a Google Cloud Run instance, its showing a green checkmark and I get an address to access the container on. I can also see that the logs show that uwsgi is booted. When trying the container locally I can access it on the port I give it... I suspect that the incorrect booting of the system is due to this line: 019-12-04T21:44:45.834539783ZContainer Sandbox Limitation: Unsupported syscall setsockopt(0x3,0x6,0x9,0x29eebd3f8794,0x4,0x0). Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information. 2019-12-04T21:44:45.834891693ZContainer Sandbox Limitation: Unsupported syscall setsockopt(0x4,0x6,0x9,0x29eebd3f8794,0x4,0x0). Please, refer to https://gvisor.dev/c/linux/amd64/setsockopt for more information. 2019-12-04T21:44:45.835166ZuWSGI http bound on 0.0.0.0:8080 fd 4 2019-12-04T21:44:45.841985Zspawned uWSGI http 1 (pid: 3) 2019-12-04T21:44:45.844243Zuwsgi socket 0 bound to TCP address 127.0.0.1:48977 (port auto-assigned) fd 3 Does anyone have any tips on getting the container to run on Cloud Run? -
Nginx takes too long to send the network response using Django with Gunicorn
I'm developing a web application with Django, and so far everything seems ok, but I'm having a big problem with my server response, usually the first time I want to enter it takes around 20 to 40 seconds to get the response back from the server. I'm using a Linode linux virtual machine running Ubuntu 18.04, is a very cheap plan just for now with only one core CPU, 2GB of ram and 50Gb of SSD storage, however as I'm the only one accessing the website I feel it is not correct that it takes so long to response (It just happen every time I restart nginx or gunicorn, or after some time of inactivity, after it respond it start to work with a normal speed). I made a performance record with chrome dev tools and these were my results: Network result As you can see the network request took 22 seconds, and if I check the main thread I can see that chrome detects that time as idle, and the real time it takes the server to process the view is only a few milliseconds. Chrome results I also have my server with an SSL certificate, the config for … -
Is there a way to have a "nested" reverse relation ship in Django REST Framework
I have Three objects: Product, Attribute, Attribute_Category Right now they are structured like this, I start at the Product. class Product(models.Model): name_single = models.CharField(max_length=30, unique=True) Bla... bla... bla... Currently I have a ForeignKey relation from the attribute to the product and the attribute_category. class Attribute(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='products') attribute_category = models.ForeignKey('AttributeCategory', on_delete=models.CASCADE, related_name='attributes') And some more data... And at last the attribute_category. class AttributeCategory(models.Model): name_single = models.CharField(max_length=30, unique=True) Yet more things... I was thinking with this structure I can filter the objects for a specific attribute- or _category. Though now I am stuck, Is there any way I can go from the product, to the category of its attributes and then get the relevant attributes. This way I can structure my response like this: product1: [ {attribute_category1: [{attribute1}, {attribute2}] }, {attribute_category2: [{attribute3}] } ] I would like to know, how can I get the desired JSON. Am I missing something? Because it feels like I am grossly overcomplicating things. I realize that this question is incredibly messy and might be worded really bad. I will try to think up some way of making the problem worded better, if anyone has any tips on the problem, or rewording it … -
GeoDjango display map on template form from model
I am trying to build a sample website based on Django(GeoDjango) and OpenStreetMap. So far I have this simple scenario: Models.py class Parks(models.Model): park_name_en = models.CharField(max_length=256) description = models.TextField() picture = models.ImageField() geom = PolygonField() @property def picture_url(self): return self.picture.url def __unicode__(self): return self.title views.py def park_insert(request): form = ParkForm() return render(request, 'addpark.html', {'form': form}) forms.py class ParkForm(forms.ModelForm): class Meta: model = Parks fields = ('park_name_en', 'description', 'picture',) geom = forms.PolygonField() and last but not least the template addpark.html <html> <head> {{ form.media }} </head> <body> <div id="map"> <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> </div> </body></html> When I open the template page all fields come up right, except the PolygonField() which comes up as a text. How can I display a map on the user form also (I got it working in the admin panel, but I want to create a form for inserting new parks) -
Django factory boy post_generation in field with default value don't work
I have a model with a field that is a int type, that field have a default value I'm trying to set a value in that field with post_generation but nothing is happening, the field stay with the default value, when I try to use .set I get the following error: AttributeError: 'int' object has no attribute 'set' this is the field that I'm trying to populate @factory.post_generation def priority(obj, create, extracted, **kwargs): for series in range(obj.patrimony.count()): # this is a sequence of numbers series += 1 obj.priority.set(series) and this is the model, is just a simple model class Series(models.Model): priority = models.IntegerField(_("Priority"), default=0, null=True) Can someone open my eyes please?