Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Activation Email
I am following this tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html to send my users an activation email which they have to click to verify and activate their account.. but I keep getting this error: AttributeError: 'UserRegister' object has no attribute 'pk' I've been messing with Django's AbstractUser functions to create my own forms and models for users, so i think that has to do with it.. but i'm not sure where to go from here. Do I need to create an attribute called 'pk'? Here is my forms.py: class UserRegister(UserCreationForm): class Meta: model = UserInfo fields = ['first_name', 'last_name', 'email', 'password1', 'password2', 'street_address', 'city', 'state', 'zipcode', 'sendPromo'] first_name = forms.CharField(label='First Name', required=True) last_name = forms.CharField(label='Last Name', required=True) street_address = forms.CharField(label='Street Address', required=False) city = forms.CharField(label='City', required=False) state = forms.ChoiceField(choices=STATES, label='State', widget=forms.Select(), required=False) zipcode = forms.CharField(label = 'Zip Code', required=False) sendPromo = forms.BooleanField(label='Sign up to receive Promotions!', required=False) def clean_email(self): email = self.cleaned_data.get('email') try: match = UserInfo.objects.get(email=email) print(match) except UserInfo.DoesNotExist: return email raise forms.ValidationError('This email address is already in use.') def getFirstName(self): return self.cleaned_data.get('first_name') def getLastName(self): return self.cleaned_data.get('last_name') def check_passwords(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 != password2: raise forms.ValidationError('Passwords do not match.') return password2 And my models.py: class UserInfo(AbstractUser): '''REQUIRED_FIELDS = ('first_name', … -
Parsing json returned in django modelformset in template
One of the fields returned to my template in a formset generated by modelformset_factory() is a JSONField. I'd like to parse the json and display elements in it separately within the form, read-only. This is readily done if I just return the queryset list, using a builtin filter I created, get(). But it has to be in a form that has some added fields for users to fill. {% for foo in foo_list %} <h5>{{ foo.json|get:"title" }}</h5> {% endfor %} The problem is that doing the same for a formset field I get the error "'BoundField' object has no attribute 'get'" {% for form in formset %} <h5>{{ form.json|get:"title" }}</h5> {% endfor %} Here is the filter: @register.filter(name='get') def get(d, k): print('get(d,k):',d,k) return d.get(k, None) The relevant bits of the view: ... foo_list = Foo.objects.all() ... FooFormset = modelformset_factory( Foo, fields = ['task_id','authority','dataset','place_id', 'authrecord_id','json'], form=FooModelForm, extra=0) formset = FooFormset(request.POST or None, queryset=foo_list) context['formset'] = formset ... return render(request, 'datasets/review.html', context=context) -
Pass parameter to a function-based view from the forms.py in Django
Good day. I have a function-based view and would like to know how to pass the self.update parameter that is in my forms.py exactly in the init function. Form.py class AnuncioForm(forms.ModelForm): justificacion = forms.CharField(widget=forms.Textarea) motivo = forms.ModelChoiceField(queryset=Catalogo.objects.filter(tipo=MOTIVO_DE_RECTIFICACIONES)) class Meta: model = Anuncio def __init__(self, *args, **kwargs): self.update = kwargs.pop('update', None) # THIS PARAMETER super(AnuncioForm, self).__init__(*args, **kwargs) if self.update: self.fields['motivo'].required = True self.fields['justificacion'].required = True Function-Based Views: def Anuncio_create_update(request, pk=None): if pk: anuncio = Anuncio.objects.get(pk=pk) nave = anuncio.nave navefoto = NaveFotos.objects.filter(nave_id=nave.id).first() tipo_navefoto = TipoNave.objects.filter(anu_tipo_nave=anuncio.id).values_list('foto') historial_anuncio = anuncio.historialedicionanuncios_set.all().select_related('usuario').order_by('-fecha').all() update = True anuncio_tmp = anuncio.has_bodega_reporte() tiene_bodega = anuncio_tmp[0] title_meta = u'Anuncio de Naves: Actualización' title = u'Anuncio de Naves' nav = ( ('Panel Mando', '/'), ('Anuncio de naves', reverse('anuncio_list')), (u'Actualización', '') ) # muelle = TarjaMuelle.objects.filter(anuncio=pk, tipo_autorizacion=COMUN_SALIDA) # if muelle is not get_es_directo(tipo_operacion=OPE_EMBARQUE_INDIRECTO): # pass else: anuncio = Anuncio() tiene_bodega = False update = False title_meta = u'Anuncio de Naves: Registro' title = u'Anuncio de Naves' nav = ( ('Panel Mando', '/'), ('Anuncio de Naves', reverse('anuncio_list')), ('Registro', '') ) unidad_operativa_id = request.session.get(SESION_UNIDAD_OPERATIVA_ID) tipo_nave = TipoNave.objects.all().values_list('id', 'descripcion') tipo_trafico = Catalogo.objects.filter(tipo='16').values_list('id', 'nombre') lineas = Catalogo.objects.filter(tipo='02').values_list('id', 'nombre') lista_tipo_carga = get_tipo_carga() # formset AnuncioBodegaFormSet = inlineformset_factory( Anuncio, AnuncioBodega, extra=0, can_delete=True, fields=( 'anuncio', 'bodega', 'total', 'bultos', 'id') ) … -
can i make a simple social media web with python,django, Html,bootstrap,jquery
i just wondering if i can make a simple social media web with these: Html five css three java-script J-query bootstrap python Django very basic knowledge about database** i wanna that web just for posting not for Instant Message (IM). what else i need to make it fast without unnecessary code? if any one can advise me how to start my project in the right path i would be so thankful for you. -
Django, Docker, and Pipenv - Error adding new packages
Using Pipenv with Docker is causing some issues in my Django project. I've installed Django locally with Pipenv which generates a Pipfile and Pipfile.lock. Then used startproject to start a new Django project. Then I add a Dockerfile file. # Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY . /code RUN pip install pipenv RUN pipenv install --system And a docker-compose.yml file. # docker-compose.yml version: '3' services: web: build: . command: python /code/manage.py migrate --noinput && /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 And run docker-compose up --build to build the image and start the container. Everything works. Now here's the issue...I want to add a new package, let's say psycopg2 so I can use PostgreSQL. So...update my docker-compose.yml to add PostgreSQL. # docker-compose.yml version: '3' services: db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /code/manage.py migrate --noinput && /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db volumes: postgres_data: And update the DATABASE config in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432 } } Now if I install psycopg2-binary locally like pipenv install psycopg2-binary this "should" sync with Docker. But I … -
What causes the error "Invalid password format or unknown hashing algorithm."?
I see a lot of answers as to how to solve this issue, but I'd like to know what exactly causes this? I have a random password generator that generates a random sequence consisting of uppercase letters, lowercase letters and numbers like this: min_char = 10 max_char = 12 allchar = string.ascii_letters + string.digits genpassword = "".join(choice(allchar) for x in range(randint(min_char, max_char))) This causes the "Invalid password" error and I'd like to know why. -
Django rest framework social auth
I'm trying to implement the django-rest-framework-social-oauth2 library, following the linked instructions to set up LinkedIn (in place of Facebook). I've added the app, as it says in the instructions, but I don't understand what to do with the redirect URI, as the instructions state that it should be blank. I have a link on my website of the form: https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=CLIEND_ID&redirect_uri= http%3A%2F%2Ffoo.com%2Ffrontend%2Flogin_redirect&scope=r_basicprofile When I click this, linkedin confirms the request and then redirects to the link encoded in the url above (http://foo.com/frontend/login_redirect) with some parameters in the url. I should then send those parameters to a particular linkedin api endpoint to obtain a token for the user. Currently, when linkedin tries to redirect, a 404 error is returned. I tried adding that redirect URI to the redirect URIs of the application, and the result was the same. To summarise, do I need to use a particular redirect url (in which case, what is it?), or, if not, how do I tell django-rest-framework-social-oauth2 which redirect URI it should make available? -
Is it possible to migrate data from MySQL to PostgreSQL through Django dumpdata?
I'm trying to convert my database from MySQL to PostgreSQL, and I'm using AWS RDS. I was trying AWS DMS to migrate data, however it didn't work well and was complicated. While struggling with that, an idea came to mind. What if I use migrate migrations to the new PostgreSQL, and dumpdata from MySQL and loaddata to PostgreSQL? Would that work? Does anyone have experience to migrate database? Am I approaching a right direction? -
Mysqlclient requires MS Visual C++ 10.0 which require again .Net Framework 4
Trying to install with pip install mysqlclient I am installing MysqlClient in Python virtualenv but installation failed with error It requires MS Visual C++ 10.0 I downloaded it, which again requires .NET Framework 4. I again downloaded .NET Framework 4, which is giving error that you cannot install .NET Framework 4 as higher version is already installed. I searched all over the internet there isn't any solution to this problem is available. -
Django Priority Queue
I want to build a delivery app in Django, wherein I will create delivery objects to be delivered according to priority(attribute of the object) by a delivery person. I will login and create the tasks and there can be many delivery persons to login and accept task asynchronously. Objects(tasks) will be popped out as a delivery person logs in and accepts the task, and the next logged in delivery person would see the next priority task. How can this be implemented in Django? Any references and implementation links are welcomed. Thanks in advance! -
Which pattern to use to add functionality to dango models
I have several models in my Django project. Most of these models are quite simple, but some of they are the entry point to complex data structures. For example, Reservation model has several detail models through foreign key relationships (ReservationHotel, ReservationTransfer, ReservationTour, ReservationRountrip, ReservationService), and each one of these details has foreign relationship with product models (Hotel, Transfer, Tour, Roundtrip, Services). I know a good practice is to keep models isolated from other models, so they must not know the detail about them. Due to this, I implement controllers to manage complex data structures like the one described before. I want these controller to implement design patterns, and I believe the proper one for Reservations should be the Proxy pattern, based in its description in wikipedia: What problems can the Proxy design pattern solve? The access to an object should be controlled . Additional functionality should be provided when accessing an object. When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights. What solution does the Proxy design pattern describe? Define a separate Proxy object that can be used as substitute for another object (Subject) and implements additional functionality to control … -
Django REST: How to overwrite field type of a serializer class
I am trying to overwrite serializer's data field, which is a CharField,like this: from jsonfield import JSONField class ActivitySerializer(serializers.ModelSerializer): data = JSONField() class Meta: model = Activity fields = ("date_added", "start_date", "data", "number", "athlete") But when I try to print the representation of the serializer -print(repr(my_serializer)) - the type of field data remains unchanged: ActivitySerializer(<Activity: START DATE: 2018-11-19 06:08:49+00:00, ID: 1973222369, DATE ADDED: 2018-11-20 18:07:32.818798+00:00>): date_added = DateTimeField(read_only=True) start_date = DateTimeField(required=False) data = CharField(style={'base_template': 'textarea.html'}) number = IntegerField(required=False) athlete = PrimaryKeyRelatedField(queryset=Athlete.objects.all(), required=False) What am I doing wrong? -
Unique=True in Django model gives IntergretyError instead of ValidationError
I want to show a validation message like "This email is already in use" inside my html form. But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself? Or maybe show me a best practice for validating unique users inside a form/model. models.py class Customer(models.Model): FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Email = models.CharField(max_length=50, unique=True, error_messages={'unique':"This email is already in use"}) views.py def customerform(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): post = Customer() post.FirstName = form.cleaned_data['FirstName'] post.LastName = form.cleaned_data['LastName'] post.Email = form.cleaned_data['Email'] post.save() return render(request, 'results.html', { 'FirstName': form.cleaned_data['FirstName'], 'Email': form.cleaned_data['Email'],}) else: form = CustomerForm() return render(request, 'form.html', {'form':form}) forms.py class CustomerForm(forms.Form): FirstName = forms.CharField (label='First name:', max_length=50) LastName = forms.CharField (label='Last name:', max_length=50) Email = forms.EmailField(label='Email:', max_length=50) form.html <form action="/customer/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> -
Django Queryset Batches
I have a Django app that runs on SQL Server. SQL Server allows a maximum of 2,100 parameters in a user-defined function. I have a Django view that is attempting to return 10,000 results: def result_list(request): results = MyModel.objects.filter(~(Q(importantField='') | Q(importantField='Some Text'))).select_related('field','field2','field3','field4').prefetch_related('anotherField') return render(request, 'results/result_list.html', {'results':results}) Error: Request Method: GET Request URL: https://server/results/result_list Django Version: 1.11.3 Python Version: 3.6.3 Traceback: File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "D:\Python\Anaconda3\envs\django\lib\site-packages\sql_server\pyodbc\base.py" in execute 545. return self.cursor.execute(sql, params) The above exception (('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)')) was the direct cause of the following exception: File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "D:\Websites\project\app\views.py" in result_list 476. return render(request, 'results/result_list.html', {'results':results}) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\test\utils.py" in instrumented_test_render 107. return self.nodelist.render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render_annotated 957. return … -
Django - TemplateDoesNotExist at /password_reset
I have a django app, that is using the django.contrib.auth package for user authentication. I'm trying to add password reset functionality using the auth views provided by the package. However, I'm getting an error when i actually navigate to that url (ttp://localhost:8000/password_reset). Does anyone have an idea on what the issue could be Error Current urls.py (i don't think a view is needed if done right) from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('profile/<username>', views.profile, name='profile'), path('register', views.register, name='register'), path('login', views.login_view, name='login'), path('password_reset', auth_views.PasswordResetView.as_view(), name='password_reset'), # path('password_reset', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset'), path('password_reset_done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_complete', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('purchase', views.purchase, name='purchase'), ] settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'avatar', ] Similar post, but did not reslove TypeError at /password_reset/ django Documentation https://docs.djangoproject.com/en/2.1/topics/auth/default/ -
Django py manage.py makemigrate
enter image description here What can I make with it? I'm beginner in python and django. I download it and I i wrote py manage.py makemigrate and I've get error. Can u help me? -
Django dumpdata returns empty array when models are in a version subdirectory
I have a Django Rest Framework app where I have separated my models/serializers/views into separate directories (instead of in models.py, serializers.py, etc) and moved those directories into a v1 directory. When I try to run ./manage.py dumpdata api I get an empty array as response. ./manage.py dumpdata will dump out the Django system tables, but none of my model tables. Here's an example: - api/ -- __init__.py -- v1/ --- router.py --- __init__.py --- models/ ---- __init__.py ---- thingy.py --- serializers/ ---- __init__.py ---- thingy.py --- views/ ---- __init__.py ---- thingy.py - project/ -- urls.py -- settings.py -- wsgi.py -- __init__.py The __init__.py file inside each object directory (e.g. models) includes the class from each file: from .thingy import Thingy The router.py file inside api/ looks like this: from rest_framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) router.register(r'thingies', views.ThingyViewSet) api_urlpatterns = router.urls And urls.py inside project/ looks like this: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from api.v1.router import api_urlpatterns as api_v1 urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/v1/', include(api_v1)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
Django, JavaScript, Google Street View: Linking JavaScript 'Click' Event Listeners for Multiple Items to Django Product & Cart Model
I would like to implement in Django a Google Street View where I could use JavaScript event listeners - 'click' to determine if buttons (Add to Cart) in the Street View has been clicked, so that all the items clicked on in the Google Street View is added to a cart when it is clicked.[reference here][1] In a typical Django shopping website, the products is added via the Django admin into the models. Then at the Django templates, the products are run iteratively with a 'for' loop to show all available products. Similarly for the cart to show all added products. {% for product in products.object_list %} {% for cart_item in cart_items %} I plan to add all products into the Django models first. The problem is how can I link every button (Add to Cart) for each specific product item in Google Street View via JavaScript 'Click' event listeners to the Django models/views? Is there a short code example that can show this being done? Thank you! -
How can I add data to my model containing User as a foreign key from a custom-made form in django?
Here, when I try to add a new note with a user logged in, I want that note to have its user-field filled with the current logged in user. So I wrote user=request.user But error arises: UNIQUE constraint failed: mynotes_note.user_id Here are my files: models.py class Note(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=50) desc = models.TextField() def __str__(self): return self.title addForm.py from django import forms class addForm(forms.Form): title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={ 'class':'form-control' })) desc = forms.CharField(widget=forms.TextInput(attrs={ 'class':'form-control' })) Here, I used this way instead of using Meta class just to apply some bootstrap effects to the form fields views.py def addView(request): if request.user.is_active: if request.method=="POST": form=addForm(request.POST) if form.is_valid(): newNote = Note(user=request.user,title=request.POST['title'],desc=request.POST['desc']) newNote.save() return redirect('home') else: form=addForm() args={'form':form} return render(request,'mynotes/add.html',args) else: return redirect('home') -
Map visualization/popup with Django and Leaflet
I am new to Django and I am struggling with a problem for many weeks. My template/html page works fine with leaflet, but when I run the template on Django it doesnt load my map (geoJson file). I have tried watching all the tutorials but no luck. Could anyone please help? I have uploaded a picture which comes alright using only leaflet and html, but comes blank on Django server. Below is my code: [![<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta name="viewport" content = "width=device-width,initial-scale=1"/> <title> Map Visualization </title> <!-- Leaflet --> <link rel= "stylesheet" href="../../leaflet/leaflet.css"/> <script src = "../../leaflet/leaflet.js"></script> <script src ="../data/countries.geojson"></script> <style type = "text/css"> #map { height : 800px; width: 70%; align: left } #filter { height:800px; width: 20% align: right } </style> </head> <body> <h1 style="color:green;"> Map Visualization </h1> <div id="map"></div> <script> function getStateColor(stateShade){ if (stateShade =="colored-state"){ return '#6666ff'; }else if(stateShade!="non-colored-state"){ return '#D3D3D3'; } } function countriesStyle(feature){ return { fillColor : getStateColor(feature.properties.shade), weight : 2, opacity : 1, color: 'white', dashArray : 2.5, fillOpacity :0.7 } } var map = L.map('map').setView(\[80, 30\], 19) var countriesLayer = L.geoJson( countries, {style : countriesStyle} ).addTo(map); map.fitBounds(countriesLayer.getBounds()); var point1 =\[44.066803,-93.533061\]; var point2 = \[43.064,-89.5347\]; var marker1 = L.marker(point1).addTo(map).bindPopup("<p>State: MN" ); … -
Intermittent IndexError with MySQL and Django running on Ubuntu
Here is what I'm getting: Traceback (most recent call last): File "/.../.env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view if test_func(request.user): File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 44, in <lambda> lambda u: u.is_authenticated, File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 213, in inner self._setup() File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 347, in _setup self._wrapped = self._setupfunc() File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 24, in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 12, in get_user request._cached_user = auth.get_user(request) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 189, in get_user user = backend.get_user(user_id) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/backends.py", line 98, in get_user user = UserModel._default_manager.get(pk=user_id) File "/.../.env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get num = len(clone) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__ self._fetch_all() File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 63, in __iter__ for row in compiler.results_iter(results): File "/.../.env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1007, in apply_converters value = row[pos] IndexError: list index out of range As you can see, there is none of my code in the stacktrace, all I know is that this code is happening somewhere in a very simple view that gets … -
how can i show active page in Django pagination
am using django 2.0 and am trying to make this blog, the issue is that once i click the next page the active bar in the pagination section dont change mean from 1 to 2 see pic image i don't know where is the mistake here is the views.py def post_list(request): object_list=Post.objects.filter(status='Published').order_by("-created") pages = pagination(request,object_list,3) context={ 'items':pages[0], 'page_range':pages[1], } return render(request,"blog.html",context) pagination function from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator def pagination(request,data,num=10): paginator = Paginator(data,num) # Show 5 contacts per page page = request.GET.get('page',5) try: items=paginator.page(page) except PageNotAnInteger: items=paginator.page(5) except EmptyPage: items=paginator.page(paginator.num_pages) index=items.number=1 max_index=len(paginator.page_range) start_index=index - 5 if index >= 5 else 0 end_index=index + 5 if index <= max_index - 5 else max_index page_range=paginator.page_range[start_index:end_index] return items, page_range and pagination.html <nav> {% if items.has_other_pages %} <ul class="pagination"> {% if items.has_previous %} <li><a href="?page={{ items.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in page_range %} {% if items.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if items.has_next %} <li><a href="?page={{ items.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> </ul> {% endif %} {% endif %} </nav> blog.html {% for obj … -
Wagtail: Getting a list of snippets with counts of related parents
Using Wagtail I have ArticlePages, each of which can have 0 or more Authors, which are Snippets. I'd like to get a list of Authors with the number of ArticlePages they're attached to, but can't work out how. I'm getting confused by ModelCluster I think, as I'd be fine with vanilla Django. (I'm not even sure if I'm over-complicating this; I don't need the Authors to be orderable on the Articles...) from django.db import models from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import InlinePanel from wagtail.core.models import Orderable, Page from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet class ArticlePage(Page): content_panels = Page.content_panels + [ InlinePanel('authors', label='Authors'), ] @register_snippet class Author(models.Model): name = models.CharField(max_length=255, blank=False) panels = [ FieldPanel('name'), ] class ArticleAuthorRelationship(Orderable, models.Model): author = models.ForeignKey( 'Author', on_delete=models.CASCADE, related_name='+') page = ParentalKey( 'ArticlePage', on_delete=models.CASCADE, related_name='authors') panels = [ SnippetChooserPanel('author'), ] FWIW, I know I could get a single Author's articles using article.get_usage(), which is handy! -
How to add more than one django-leaflet map in a view?
I was able to show a map on a single page using django-leaflet. In another page, I am trying to show two (or more) maps in page but I couldn't figure out how. For showing map in a single page: <div class="card"> {% leaflet_map "main" callback="map_init" %} </div> <script type="text/javascript"> function map_init(map, options) { // get point lat and lon var lon = "{{ project.longitude }}"; var lat = "{{ project.latitude }}"; // zoom to point & add it to map map.setView([lat, lon], 12); L.marker([lat, lon]).addTo(map); }</script> Above works fine as long as one map needs to be shown. However I am not sure how I can modify above to support multiple maps. I have started jsfiddle page here (which is kind of blank), not sure if it's going to helpful. What I am trying is to fill the 'img-top' div in the html below: var locations = [ {"lat":27.988098,"lng":86.924925}, {"lat":27.679535,"lng":83.507020} ] <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="card-columns m-5"> <div class="card"> <div class="card-header">Location A </div> <div class="img-top" id="map-1" style="height:200px"></div> <div class="card-body"> Some information of A </div> </div> <div class="card"> <div class="card-header">Location B </div> <div class="img-top" id="map-2" style="height:200px"></div> <div class="card-body"> Some information of B </div> </div> </div> -
No 'Access-Control-Allow-Origin' header is present on the requested resource error in fetch API django
I'm trying to fetch some data from an API. It works and my data is send to the server but I am getting the following error message that unable me to continue: Access to fetch at 'http://192.168.80.11:8000/upload/5bc4206e3ff2286d24c58899/' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I know that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS. But how can I set Access-Control-Allow-Origin in the response header? I use Django. And this is setting file on server: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGINE_ALLOW_ALL= True CORS_ALLOW_CREDENTIALS = True #CORS_ORIGINE_ALLOW_ALL= False CORS_ORIGINE_WHITELIST=( 'http//:192.168.20.29:8000', 'http//:192.168.20.30:8000', 'http//:127.0.0.1:8000', )