Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install raises raise BadZipfile, "File is not a zip file"
I am trying to do pip2.7 install -r req.txt in my virtual environmen. made a virtual environment virtualenv -p python venv22 activated it source venv22/bin/activate then did sudo pip2.7 install -r req.txt Tried to install package via pip install but after installing it showed that the modules were not found. So I tried with pip2.7 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 324, in run requirement_set.prepare_files(finder) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 484, in unzip_file zip = zipfile.ZipFile(zipfp, allowZip64=True) File "/usr/lib/python2.7/zipfile.py", line 770, in __init__ self._RealGetContents() File "/usr/lib/python2.7/zipfile.py", line 811, in _RealGetContents raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file You are using pip version 9.0.1, however version 19.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.``` How do I install the packages? -
Error occured while reading WSGI handler. ModuleNotFoundError' while hosting DJango on IIS. Can't find settings
I am doing this for the first time. I am trying to host my Django rest app on Windows IIS server. I have followed this tutorial https://medium.com/@Jonny_Waffles/deploy-django-on-iis-def658beae92 but I am getting the following error. Does it have to do something with my conda environment? I haven't used any config file. I've set the environment variables in the system variables instead. In my settings.py WSGI_APPLICATION = 'webapi.wsgi.application' IN wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapi.settings') application = get_wsgi_application() Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "webapi.wsgi.application" could not be imported: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File "C:\inetpub\wwwroot\webapi\webapi\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\ProgramData\Anaconda3\envs\api_env\lib\importlib\__init__.py", line 127, in import_module … -
How to get predicted value of my linear regression model on html page
I'm preparing machine learning model via django project but I'm not able to get that value via views.py to html page. I've tried same concept to print any value on html page,but when I'm sending the same for my machine learning model but I'm not able to get that value. Views.py: from django.shortcuts import render,HttpResponse import pandas as pd import statsmodels.formula.api as sm def pricepred(request): wine = pd.read_csv('https://drive.google.com/file/d/1Eww8ChM1ZQgwCCKkMiUBi1xcs39R6C45/view') model = sm.ols('Price ~ AGST + HarvestRain + WinterRain + Age', data=wine).fit() d = {'Year': pd.Series([2019]), 'WinterRain': pd.Series([700]), 'AGST': pd.Series([15]), 'HarvestRain': pd.Series([100]), 'Age': pd.Series([10]), 'FrancePop': pd.Series([90000.000])} df_test = pd.DataFrame(d) predictDF = model.predict(df_test) context = { 'pred': predictDF } return render(request, 'pricepred.html', context) pricepred.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <title>Real Price</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" type="text/css"> <link href="{% static 'CSS/style.css' %}" type="text/css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <h1>Welcome to Price Prediction Page</h1> {{ pred }} </div> </body> </html> urls.py: from django.urls import path from . import views urlpatterns = [ path('pricepred/', views.pricepred), ] I expect the output of 'pred' i.e. value of prediictDF on html page but I'm getting "urlopen error [Errno 11001] getaddrinfo failed" … -
How to make a loop in function of views.py
I am just trying to simplify it and want to make a loop in views.py instead of writing every item. But it is not working. Destination is a class in models.py and I am getting data from database. from django.shortcuts import render from . models import Destination from django.db.models import Q def index(request): query = request.GET.get('srh') if query: match = Destination.filter(Q(desc_icontains=query)) # instead of writing this target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.desc = 'Article Writing' b.desc = 'Micro Tasks' # I am trying to make a loop but it is not working. target1 = Destination.objects.all() for field in target1: [Destination(img = f'{field.img}', title = f'{field.title}') for __ in range(2)] -
linking css stylesheet django python3?
I am pretty new to Django and I do not know how to link CSS and or javascript to my project. Don't want to have a project with no CSS. Thank you for any help, sorry if this is a very dumb question. Have a nice day! -
How to range the items in generator?
How to make this range working in function. Whenever I limit n, it gives every result without limit. Here I used Destination() which is a class in models.py # This is to show you def generator(f, n, *args, **kwargs): return (f(*args, **kwargs) for __ in range(n)) # This is the problem target1 = Destination.objects.all() for field in target1: [Destination(img = f'{field.img}',title = f'{field.title}') for __ in range(2)] #models.py class Destination(models.Model): title = models.CharField(max_length=255) img = models.CharField(max_length=255) -
django gives duplicate error everytime the project runs
I am trying to add some data which is in response_body to my 'Offenses' table in my database 'dashboard' I want to add this data only once,so at the first time the data was added to my database successfully but after that it gave me this error because it obviously refuse to create duplicate entry for another oid which is set as unique How can I modify my code so that the data is added only once and no duplicate data is added and it does not give me this error django.db.utils.IntegrityError: (1062, "Duplicate entry '4767' for key 'PRIMARY'") Below is my code. I have created the table from models.py and adding the data from views.py because the data is present in views.py and it was easier to add the data from here. if there is any other suitable approach please suggest. models.py from django.db import models from django.contrib.auth.models import UserManager from django.core.validators import int_list_validator # Create your models here. class Offenses(models.Model): oid = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=20) assigned_to = models.CharField(null=True, max_length=20) categories = models.TextField(null=True) category_count = models.IntegerField(null=True) policy_category_count = models.IntegerField(null=True) security_category_count = models.IntegerField(null=True) close_time = models.TimeField(null=True) closing_user = models.IntegerField(null=True) closing_reason_id = models.IntegerField(null=True) credibility = models.IntegerField(null=True) relevance = models.IntegerField(null=True) … -
Can we upload a tree structure in one go to django server? Like we do using git?
Can we upload a tree structure in one go to the django server? Like we do by using git? We can use multiple file upload in Django but that doesn't solve the issue for hierarchical tree structure upload. -
Lightbox 2 doesn't work with django and bootstrap cards?
I have a page where I want to show images uploaded by users in a bootstrap card.The light box isn't loading right but the console doesn't show errors of the js/css files. here's the template of the images: <div class="row"> {% for image in Patient_detail.images.all %} <div class="col-md-4"> <div class="card"> <div class="card mb-4 shadow-sm"> <a href="{{ image.pre_analysed.url }}" data-lightbox="image-1" data-toggle="lightbox"> <img src="{{ image.pre_analysed.url }}" class="img-thumbnail" > </a> <div class="card-body"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </form> </div> </div> </div> </div> {% endfor %} and here's the base.html files loading <script src="{% static 'js/lightbox.js' %}"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script> <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.js"></script> <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table-locale-all.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> and the style sheets: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css" rel="stylesheet"> <link href="{% static 'css/lightbox.min.css' %}" rel="stylesheet"> the images do show but the lightbox effect doesn't happen plus i want to resize/crop the images inside the cards and show the full size in the lightbox. -
when celery task will be execute if we call task with .delay()
since i haven't computer science i can't get exactly about time of execution of celery task . in celery document talking about daemon when calling .delay() but i can't found what is daemon and finally when exactly celery task will be execute if we call it by .delay() ? :) for example if i have below code when my_task will be execute? function.py: def test(): my_task.delay() while second<10: second += 1 # assume this part take a second 1-exactly when test() function finished (about 10 second after test() called) 2-in the middle of while loop 3- after finished test() and when requests wasn't too many and server have time and resources to do task!! (maybe celery is intelligent and know the best time for execute task) 4- whenever want :) 5- correct way that i don't pointed to . :) if it's depending to configuration i must tell i used default configuration from celery documentation.thank you. -
Passing List to Manytomany field in APIVIew having error "Incorrect type. Expected pk value, received str."
I made APIs to create update case But the problem is with task if I pass only one pk like(task=1) while updating or creating through postman then it works fine and case will be created with referencing that task but a task is a manytomany field I need to assign multiple task pk to a case like task = [1,2] Then it is giving error like "Incorrect type. Expected pk value, received str." ] class Case(models.Model): name = models.CharField(max_length=200) task = models.ManyToManyField('task.Task',blank=True, null=True) assigned_to = models.ForeignKey("account.User",null=True, blank=True, on_delete=models.SET_NULL) class CaseSerializer(serializers.ModelSerializer): class Meta: model = Case fields = ('id', 'name', 'task', 'assigned_to') -
How I can create category and subgategory in Django
I am new to Django and I know how to implement theme and pages in Django but now I want to add category and subcategory in my projects, if a user clicks on subcategory then he can see a new page where he can check all the information related to subcategory service. Please let me guide how I can create these features on my website. I have already install Django and created an admin panel. -
Overriding PasswordChangeView
I'm trying to override the PasswordChangeView in Django Allauth. I'd like to implement everything, except override the template name. However, I'm having a hard time with the render_to_response method, it keeps redirecting to the old /password/set/ template. Here's how my method looks like: class PasswordSettings(PasswordChangeView): template_name = 'oauth/password-change.html' success_url = reverse_lazy('oauth:password-settings') def render_to_response(self, context, **response_kwargs): return super().render_to_response( context, **response_kwargs) What am I doing wrong? Why can't it redirect correctly to my template? Here's the source code: https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py -
How to return pagination with djando framework?
How to return pagination with djando framework? I'm trying to use the class LimitOffsetPagination. Where am I going wrong? Thank you guys class Sellers(APIView): pagination_class = LimitOffsetPagination def get(self, request): transactions = Transactions.objects.all() page = self.paginate_queryset(transactions, request) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(transactions, many=True) return Response(serializer.data) page = self.paginate_queryset(transactions, request) AttributeError: 'Sellers' object has no attribute 'paginate_queryset' -
How to make the number of range working in generator
How to make this range working in function. Whenever I limit n, it gives every result without limit. def generator(f, n, *args, **kwargs): return [f(*args, **kwargs) for __ in range(n)] -
'list' object has no attribute 'filter'
def g_view(request): header_category = Category.objects.all() m = Type1.objects.all() r=Type2.objects.all() g=Type3.objects.all() from itertools import chain orders=list(sorted(chain(m,r,g),key=lambda objects:objects.start)) mquery = request.GET.get('m') if mquery: orders = orders.filter( Q(name__icontains=mquery) | Q(game__name__icontains=mquery) | Q(teams__name__icontains=mquery)).distinct() (Type is abstract and type1 type2 type3 are inherited classes) I got this error 'list' object has no attribute 'filter' -
html doc not using external css style sheet
I am starting to learn CSS and after trying to implement an external stylesheet, i found I was unable to change the color of my html document. I am using Visual Studio Code and my html templates are using Djangos inheritance. I have tried double checking that everything is saved, I have checked spelling for the href, and i even restarted VSC. So far nothing. Here is the base html sheet <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% block style %} {% endblock %} <title> {% block title %} {% endblock %} </title> </head> <body> {% block content %} {% endblock %} </body> </html> Here is an html sheet that should use the styling: {% extends 'student_view_base.html' %} {% block title %} Socrates Home Page {% endblock %} {% block style %} <link rel="stylesheet" type="text/css" href="css/sidebar.css"> {% endblock %} {% block content %} <h1>Socrates Home Page</h1> <div> <a href="{% url 'login' %}">Login</a> </div> <a href="{% url 'admin:index' %}">Admin Login</a> {% endblock %} Here is the css sheet: h1{ color: blue; } As you can tell, I am pretty new to Web Dev in general and this was mostly to experiment and make sure I could implement it properly. As … -
folium map not displaying on django page
I am reading data from postgressql to get a dataset of latitude, longitude and name of a jpeg file. I'm iterating through the dataset to create markers on a map. I'm not getting an error message, but the map does not display. I'm displaying data on the index.html page. I'm using iframe to display map.html. I've read a number of threads on the subject, but none of the answers are working for me. views.py: from django.shortcuts import render from django.http import HttpResponse from .models import PhotoInfo import folium # Create your views here. def index(request): VarPhotoInfo = PhotoInfo.objects.order_by('DateTaken') context = {'PhotoInfo': VarPhotoInfo } return render(request,'natureapp/index.html',context) def show_map(request): PhotoInfo1 = PhotoInfo.objects.order_by('DateTaken') m = folium.Map([33.571345, -117.763265], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[33.571345, -117.763265], popup=popup).add_to(m) fg = folium.FeatureGroup(name = "MyMap") for i in PhotoInfo1: fg.add_child(folium.Marker(location=(float(i.Lat),float(i.Long)),popup = str(i.DateTaken) +' file: '+ i.PhotoName, icon = folium.Icon(color='green'))) m.add_child(fg) m.get_root().render() context = {'MyMap': m} return render(request, 'natureapp/map.html', context) map.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NatureMapper</title> </head> <h1>Map goes here </h1> {{ my_map.render }} </html> index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NatureMapper</title> </head> <h1>Here it is! </h1> {% if PhotoInfo %} {% for Photo in PhotoInfo %} <p>there is info.</p> <p> … -
UserCreationForm KeyError 'email' in Registration page
Im learning django and im trying to understand the registration progress with an UserCreationForm and a CreateView, I want to use an email as field on the registration form but they keep poping an error about KeyError 'email' on my form. forms.py from django import forms from accountApp.models import Profile from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name', 'last_name', 'email') class CreateUserForm(UserCreationForm): fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Usuario' self.fields['email'].label = 'Email' views.py from django.urls import reverse, reverse_lazy from . import forms class RegistrationPage(CreateView): template_name = 'accountApp/register.html' success_url = reverse_lazy('accApp:profilepage') form_class = forms.CreateUserForm models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) def __str__(self): return self.user.username -
How to query a query using date field inside a metadata of type JSONField?
How to query a query using date field inside a metadata of type JSONField? In the field metadata of my line contains the following content [ { "id": "57400265c48f4ae16ea6f719bb360", "method": { "id": "be32754f6c3643c49c308a4526646", "expiration_date": "2019-06-12T00:00:00+00:00", "accepted": false, "printed": false, "downloaded": false, "created_at": "2019-06-12T11:49:00+00:00", "updated_at": "2019-06-12T14:48:59+00:00" }] I tried to use a query with range to return values of data between two dates. Transac.objects.filter(id=request.user.id, metadata__method__expiration_date__range=(datetime.date(2019, 7, 1), datetime.date(2019, 7, 30)) ) I also tried using the gte Transac.objects.filter(id=request.user.id, metadata__method__expiration_date__gte=datetime.date(2019, 6, 1) ) Nothing worked. The error follows. TypeError: Object of type 'date' is not JSON serializable If anyone can help, I'm very grateful. -
Django : How to link model one objects with model two in form?
I trying to link one model objects with other model in forms but ending up with invalid form Models.py: class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Rooms(models.Model): name = models.CharField(max_length=200) room_num = models.IntegerField() def __str__(self): return str(self.name) class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.OneToOneField(Rooms,on_delete=models.CASCADE, blank=False) investigation = models.CharField(max_length=300) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,null = False) Forms.py: from .models import Patient,Ipd class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','investigation'] views.py: @login_required def ipd (request,patient_id): patient = Patient.objects.get(pk=patient_id) if request.POST: data = dict(request.POST) data['patient']=Patient.Patient_id formtwo = IpdForm(request.POST) if formtwo.is_valid(): if formtwo.save(): return redirect('/', messages.success(request, 'Patient is successfully updated.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: formtwo = IpdForm(request.POST) return render(request, 'newipd.html', {'form2':formtwo ,'form':patient}) i have Patient model that is used to create patient , and Ipd model which takes additional information from Patient before getiing admitted. so i am trying to link Ipd model with Patient to create New Ipd List -
AttributeError at /map creating folium map in Django
I am reading gps coordinates from a postgressql database, and I am using folium to create a map. I use iframe to embed the map in index.html. The data is being read and displayed in index.html, but the embedded map.html throws an error saying ''QuerySet' object has no attribute 'Lat'' - but my recordset does have a field called Lat and I use it in index.html I am displaying the data (latitude, longitude, a picture taken at those coordinates) in index.html. I've created a model and have data in a postgressql database. I created a function in views.py where I'm looping through the dataset to create markers in a folium map. Then I'm using iframe to embed it in an index.html views.py from django.shortcuts import render from django.http import HttpResponse from .models import PhotoInfo import folium # Create your views here. def index(request): VarPhotoInfo = PhotoInfo.objects.order_by('DateTaken') context = {'PhotoInfo': VarPhotoInfo } return render(request,'natureapp/index.html',context) def show_map(request): #creation of map comes here + business logic PhotoInfo1 = PhotoInfo.objects.order_by('DateTaken') m = folium.Map([33.571345, -117.763265], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[33.571345, -117.763265], popup=popup).add_to(m) fg = folium.FeatureGroup(name = "MyMap") for lt, ln, el, fn in zip(PhotoInfo1.Lat,PhotoInfo1.Lon, PhotoInfo1.DateTaken, PhotoInfo1.PhotoName): fg.add_child(folium.Marker(location={float(lt),float(ln)},popup = str(el) … -
Django - Forbidden (CSRF token missing or incorrect.)
I have a problem with creating a simple form that uses {% csrf_token%}. Template with form: <form action="{% url 'library:my_view' %}" method="post"> {% csrf_token %} <input type="submit" value="Submit"> </form> urls.py urlpatterns = [ # ... path('some_page', views.my_view, name='my_view'), ] views.py #... def my_view(request): used_method = str(request.method) return render(request, 'library/some_template.html', {'test': used_method}) Template with result (some_template.html): {{test}} The server gives me the message: Forbidden (CSRF token missing or incorrect.): / Library / some_page "POST / library / some_page HTTP / 1.1" 403 2513 or (when i use a different browser): Forbidden (CSRF cookie not set.): /library/some_page "POST /library/some_page HTTP/1.1" 403 2868 The form works correctly when I disable protection (@csrf_exempt before the view). Where is a problem? I will be grateful for any help. -
How to POST variables js to Django
I have 3 variables in js. I need post to views.py I use Python 2.7 and django 1.11 i try with ajax but i dont understand. <head> <meta charset="UTF-8"> <title>Prueba de actualización de forma</title> <script type="text/javascript"> function addEvidence(form) { idAlumno = document.getElementById('idAlumno').value; competencia = document.getElementById('Competencia').value; var radios = document.getElementsByName('Calificacion'); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { calificacion = radios[i].value break; } } alert(idAlumno + " " + competencia + " " + calificacion); } </script> </head> views.py def Evidences(request, idAlumno,competencia,calificacion): return render(request, 'resultados_app/resultados.html') i need post idAlumno, competencia and calificacion but i dont know -
How to assert the user is logout in django.test.TestCase?
I'm new to Django and now I'm strugging writing test code. In a test case I want to check if the user is logout successfully. Then how can I write assert? Below is the tiny sample code. from django.test import TestCase class TestLogin(TestCase): fixtures = ['myuserdata.json'] @classmethod def setUpClass(cls): super().setUpClass() def setUp(self): self.USER_ADMIN = { 'email': "foo1@bar.com", 'password': "foobar1234", } self.USER_PLAIN = { 'email': "foo2@bar.com", 'password': "foobar1234", } def test_login_success(self): login_result = self.client.login( email=self.USER_ADMIN['email'], password=self.USER_ADMIN['password'], ) self.assertTrue(login_result) login_result = self.client.login( email=self.USER_PLAIN['email'], password=self.USER_PLAIN['password'], ) self.assertTrue(login_result) self.client.logout() # self.assertFoobar(???) def tearDown(self): pass #...