Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF verification failed (Django)
I'm getting this error when trying to log in to my django app. Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. Help Reason given for failure: CSRF cookie not set. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: - Your browser is accepting cookies. - The view function passes a request to the template's render method. - In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. - If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. - The form has a valid CSRF token. After logging in in another browser tab or … -
Django login as modal - issues checking if the username inputted exists
I'm attempting to produce a global login form in a modal pop-up using custom login middleware. middleware.py (custom login form middleware): class LoginFormMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.method == 'POST': login_form = AuthenticationForm(data=request.POST, prefix="login") if login_form.is_valid(): user = login_form.get_user() username = login_form.cleaned_data['username'] if User.objects.filter(username=username).exists() and user: login(request, user) return HttpResponseRedirect(request.path) else: raise login_form.ValidationError(u'Aw, snap! Looks like the username "%s" doesn\'t exist. Perhaps you should register?' % username) if reverse('logout') in request.get_full_path(): return HttpResponseRedirect('/') else: login_form = AuthenticationForm(request, prefix="login") request.login_form = login_form return self.get_response(request) Essentially - this works great when logging in a user. Very happy. I have some client side form validation checks - mainly to check that both the username and the password fields have something (anything) in them. The issue for me lies with the server side checks. The current state is that the above middleware isn't raising the form errors when required...it just redirects back to the home page :'( My template looks like this (inside base.html which all other templates extend from, ignore the rather hacked forloop counter stuff - that's just to get certain Bootstrap.js stuff working): <!--Start Django Login Form --> <form id="loginForm" action="." method="POST"> {% csrf_token %} … -
Fillter jvectormap markers on button click
I am trying to add a filter that will activate on-click. The way I have it set up is I built a JSON in the back-end, and send it to the front-end(JS). Cool? On click, I would like to filter the JSON and re-assign the data variable passed into the map. Here is the code... var data = {{map_data|safe}} var filterMarkers = ['recommend', 'upcoming', 'trip', 'residence', 'saved'] var filteredData; var filters = []; var color = data.color; $(".map-legend-circle").click(function(e) { e.preventDefault(); data = {}; filteredData = {}; filteredData = data; $(this).toggleClass('map-legend-filtered'); $(this).children().children().toggleClass('map-legend-filtered'); var idName = $(this).prop('id').split('-')[0]; if ($(this).hasClass('map-legend-filtered')) { // remove it from filterMarkers // filter it against the filterMarkers and get rid of it. filterMarkers = filterMarkers.filter(function(marker) { return marker !== idName; }); console.log(filterMarkers, "filterMarkers"); for (var marker in filteredData.marker) { for (var i = 0; i <= filterMarkers.length; i++) { if (filteredData.marker[marker].type.toLowerCase() === filterMarkers[i]{ filters.push(filteredData.marker[marker]); } } } data = {marker: filters, color: color}; } else { filterMarkers.push(idName); // dont worry much about this yet. } }); So I want to update data cos I am then passing it into here... $('#world-map').vectorMap({ map: 'world_mill', markers: data.marker, // more code The JSON updates, but not the filters. I suspect I … -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I have two apps : Characters and Accounts. Here is Characters' models : from django.db import models class Character(models.Model): characterid = models.AutoField(primary_key=True, unique=True) charactername = models.CharField(max_length=100) characterspell1 = models.CharField(max_length=100) Now, here is Accounts' models : Persos = Character.objects.all() class Profile(models.Model): PERSO_CHOICES=[] for Perso in Persos: PERSO_CHOICES.extend([(Perso.characterid ,Perso.charactername)]) user = models.OneToOneField(User, on_delete=models.CASCADE) character = models.IntegerField(choices=PERSO_CHOICES, null=False, blank=False, default=0) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Now, I would like to do something like this in Accounts' Profile class : Character_info = Character.objects.filter(characterid = Profile.character) characterspell1 = Character_info.characterspell1 (Or something like this) Here is the error I'm having : TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' How can I fix that ? -
Django Live Project not showing media/images
I have a site that collected finaly the CSS, but now i have an issue with the Media files. The blog part is not showing the images for each post. the site is on: http://beta.reichmann.ro:8000/posts/ My media settings are: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root") The location on the server is: The images are broken so they are not linked up to the page. PS. I will not gonne have a lot of images there, i will write maybe 1 posts per month, therefore shouldn't be an issue with the space etc. Please advise. -
I want to add a location field in django model which take location input by putting lattitude and longitude
I also want to pick the location through Django REST API Through template..please suggest necessary django packages for it and how to write locationField in the Django Model -
notify user if similar model created _Django
I have a model.that I need to if any model with specific field created in database.send a Email to user for notify.I did some search too many apps are there for handling the notify. thats not my concern .I dont know how deploy this structure.any guide or example for this.for example : if x = book.objects.create(title="book1") : print("the book created") if this action happend do something. -
How is not displayed news?
How is not displayed news - plugin djangocms aldryn-newsblog? Con be exemple visible last news from admin panel? Screens: https://image.ibb.co/ewP8zG/b9481709_d6dc_4b77_890a_6d0ca852866f.png https://image.ibb.co/mcZaeG/3bd573d3_36d0_429a_bd50_436a9ee26cc3.png https://preview.ibb.co/dALFeG/5841cbf1_259f_4a2d_93eb_f7352dc3ddb8.png -
TypeError: 'GoodsCategory' object does not support indexing
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') import_goods_data.py from apps.goods.models import Goods, GoodsCategory, GoodsImage from db_tools.data.product_data import row_data for goods_detail in row_data: goods = Goods() goods.name = goods_detail['name'] goods.market_price = float(int(goods_detail['market_price'].replace('¥', '').replace('&', ''))) goods.shop_price = float(int(goods_detail['sale_price'].replace('&', '').replace('$', ''))) goods.goods_brief = goods_detail['desc'] if goods_detail['desc'] is not None else '' goods_goods_desc = goods_detail['goods_desc'] if goods_detail['goods_desc'] is not None else '' goods.goods_front_image = goods_detail['images'][0] if goods_detail['images'] is not None else '' category_name = goods_detail['categorys'][-1] category = GoodsCategory.objects.filter(name=category_name) if category: goods.category = category[0] goods.save() Because I got a error.So let me try to write it this way: categories = GoodsCategory.objects.filter(name=category_name) if categories.exists(): category = categories[0] else: category = GoodsCategory.objects.create(name=category_name) goods.category = category[0] goods.save() But I had another error. TypeError: 'GoodsCategory' object does not support indexing -
How to populate django models with form information
Right now I am having a bit of struggle trying to understand how forms work, and I am learner by example. Right now, I am trying to set up 2 models: Teacher and Student so that these models get their entries from logged users (teachers and students) but also from admin panel. So I made these 2 models and I made different views and forms for teachers so that they can create accounts by extending the AbstractUser. This model only provides me username, email, password and password confirmation. As you can see, for example,in my student model; photo, email and phone are blank=True. That is, because I want supervisor to add name, surname and student_ID only. When student creates account, he will be needed to enter these other fields as well. And also, I want that if his name, surname and student_ID don't match those from the model, he will not be able to create his account. I don't know if this approach is good or if I started bad, so I want a bit of advice. Here is what I tried: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return … -
Where are the built in django template tags located?
I found a directory called template tags in the django repo, but I do not see the template tags I'm looking for. Specifically, this one: {{ testdate | date:'m-d-Y, H:i a' }} -
how to call different settings from manage.py in django
I'm trying to call environment specific settings in django. I found that you can do something close in django admin according to: https://docs.djangoproject.com/en/2.0/topics/settings/#the-django-admin-utility I tried this with the manage.py: python3 manage.py runserver --settings=mysite.settings.prod_settings I get the error: ModuleNotFoundError: No module named 'mysite.settings.prod_settings'; 'mysite.settings' is not a package How can I call environment specific settings? Thanks -
Django - join between different models without foreign key
Imagine I have two simple models (it's not really what I have but this will do): Class Person(models.Model): person_id = models.TextField() name = models.TextField() #...some other fields Class Pet(models.Model): person_id = models.TextField() pet_name = models.TextField() species = models.TextField() #...even more fields Here's the key difference between this example and some other questions I read about: my models don't enforce a foreign key, so I can't use select_related() I need to create a view that shows a join between two querysets in each one. So, let's imagine I want a view with all owners named John with a dog. # a first filter person_query = Person.objects.filter(name__startswith="John") # a second filter pet_query = Pet.objects.filter(species="Dog") # the sum of the two magic_join_that_i_cant_find_and_posibbly_doesnt_exist = join(person_query.person_id, pet_query.person_id) Now, can I join those two very very simple querysets with any function? Or should I use raw? SELECT p.person_id, p.name, a.pet_name, a.species FROM person p LEFT JOIN pet a ON p.person_id = a.person_id AND a.species = 'Dog' AND p.name LIKE 'John%' Is this query ok? Damn, I'm not sure anymore... that's my issue with queries. Everything is all at once. But consecutive queries seem so simple... If I reference in my model class a "foreign key" (for … -
Download file with boto3 in s3, why my files are delete after download?
Download file with boto3 in s3, why my files are delete after download ? I tried several ways to download a file to my S3 bucket, but each time the file is deleted. Here is the mechanism of the program: 1) First I display the contents of my bucket. 2) Then via a client interface, I send the name of the file via ajax on a page in python. 3) Finally, I send a request on AWS thanks to Boto3 to have a url of downloading. I do not want to download directly into a local folder, the person must be able to choose the folder of destination and therefore I must generate a link on the bucket. Here is my Class : import boto3,botocore,sys, os import urllib class AWS: def __init__(self): self.aws_access_key_id='xxxxx' self.aws_secret_access_key='xxxxxx' class S3(AWS): def __init__(self,request): AWS.__init__(self) self.client_s3 = boto3.client('s3', aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key) self.bucket='bucket' self.path='path/' def download_file(self,request,name_file): if not (name_file is None): url = self.client_s3.generate_presigned_url('get_object', Params = {'Bucket': self.bucket,'Key': self.path+name_file}) urllib.request.urlopen(url) #url=self.client_s3.get_object(Bucket=self.bucket,Key=self.path+name_file) #with open(name_file, 'wb') as data: # self.client_s3.download_fileobj(self.bucket, self.path+name_file, data) urllib.request.urlopen() In this example, with generate_url my object is deleted and i can't download the object. But with boto3 function like download_file, i can download but it still … -
Django: Difference between using ASGI (Asynchronous Server Gateway Interface) and WSGI(Web Server Gateway Interface) . Which is better?
I would like to know the following: Difference between WSGI and ASGI in django. What is a WSGI application? How to Use ASGI/WSGI In Django ? -
django: how to display possible solutions according to user input?
The page should have a list where user can select desired option, and an submit button. On click of the submit button the results of the page should get displayed for eg: if the user selects india the results should be all the languages people speak in india. -
variable field in an "if"
how can I force the insertion of this "fascia" variable here: fascia = input("fascia [1-9]:") if iscritti.corso**+fascia+**_id==None: ... contatore1= Iscrizione.objects.filter(corso**+fascia+**_id=corsi) -
Select2 Conditional POST
I'm a new developer and I have the select2.js plugin working correctly and my logic in the application is working. The next step is the POST, which i'm struggling at. My javascript uses the div class to show/hide the div based on the selected data_id. I'm trying to POST only the results of the data in the multi selector when the submit button is POSTed. I think i'm close, but i'm not sure how to handle a conditional for the data: in the ajax. My example is focused on the group situation being selected, but all others will follow the same. $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().select2(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); $('#submit-button').click(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'submitted' %}", data: JSON.stringify({ ?:? }), dataType: 'json', type: 'POST', success: function (serverResponse_data) { }, }); }); }); My linter tool gives me an unexpected token on this line, regardless of if I add field:variablename in place of the ?:?, i just left the ?:? because i'm unsure of how to handle the conditional: data: JSON.stringify({ ?:? }), … -
Rackspace cloud object
I am trying to embed a video into my project, I have a the video on rackspace cloud which currently in private. I am using pyrax API and Django framework.I got the exact object of my file, but i could find documentation only on how to download the content not embed them to website. Can anyone help me how to embed this content to a webpage thanks in advance -
Django Project Live not Collecting Static
I have a django project which is deployed on a webserver http://beta.reichmann.ro:8000/. The thing is that it doesnt collect the static files. I run python manage.py collectstatic, but somehow the path is broken. The it from the site told me that the server searches for beta.reichmann.ro:8000/static/css/bootstrap.min.css. My settings are: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'contact.apps.ContactConfig', # am pus asta aici cand am creat for apliktie noua.for se ia din apps din apliktia contact si settings--contactconfig 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'posts', ] 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', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'chn.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] WSGI_APPLICATION = 'chn.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'ro' from django.utils.translation import ugettext_lazy as _ TIME_ZONE = 'Europe/Bucharest' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), … -
Web scraping using beautifulsoup, output keep varying
I'm currently want to scrape the review from the website foursquare.com. I used the following code to do it url = "https://foursquare.com/v/pantai-klebang/4c7c12d22d3ba14318e595d0" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") containers = soup.findAll("li", {"class": "tip"}) filename = "review.csv" f = open(filename, 'w') for container in containers: review = container.find("div", {"class": "tipText"}).text print(review.decode('unicode_escape').encode('ascii','ignore')) I should get 144 data when I run the above code. Sometimes I get all of the data and sometime i get only 56 of the data Why does the output keep varying? Is it the issue with the code or the internet connectivity? -
django learning is going no where prefer a techinal answer not moral science
i ve learning django for 10 days now, made polls app ,blog app and some other apps present on tutorial websites.The concepts of django ain't sticking in head that's why i see my learning is going no where.Could you suggest some technical and practical measures to step up my learning and confidence? -
TransactionManagementError in Django
I created a Custom User Model in Django. I am now want to extend this model with an additional model called Ambassadors. The error I am getting is "TransactionManagementError". No matter what I tried or read I don't find the issue. Do you have any idea where the problem could be? Attached the Traceback as well as models.py Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounts/myuser/add/ Django Version: 2.0.1 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed 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'] Traceback: File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Users/Marc/Desktop/Dev/accounts/lib/python3.6/site-packages/django/utils/decorators.py" … -
Django ORM, getting variables from three tables
I am basically trying to do two joins in one line in Django, but I cannot seem to find a solution. Below you can see the models.py. from django.db import models class Person(models.Model): name = models.CharField(max_length=100) surname = models.CharField(max_length=100) birthdate = models.DateTimeField() phonenumber = models.CharField(max_length=100) address = models.ForeignKey(Address,on_delete=models.CASCADE) def __str__(self): return self.name class Address(models.Model): name = models.CharField(max_length=100) number = models.IntegerField() city = models.ForeignKey(City,on_delete=models.CASCADE) def __str__(self): return self.name class City(models.Model): zippcode = models.CharField(max_length=10,primary_key=True,unique=True) name = models.CharField(max_length=100) def __str__(self): return self.name I want to filter the people with surname Smith, and show their name, date of birth, their street name and the name of their city. I came so far: Person.objects.filter(surname='Smith').values('name','birthdate','address__name','address__city__name') This doesn't work because of the last part in values 'address__city__name'. I am trying to figure out how to get the city name in some other way, but I can't seem to figure this out. Any suggestions? -
Namespace and URLs Multi-site
I am pretty new to Python and Django, but I am working on a multi-site Django, created on 1.9 I am currently trying to make it work with Django 2.0 but I don't understand how the namespace and URL Works. Here is how it worked with the 1.9 version (Account is mapped in Search site) : /* HTML, did not change */ <li><a href="{% url 'account:profile' %}">Profil {{ user.firstname.0 }}. {{ user.lastname }}</a></li> The old version /* Main project URLS.PY */ from search import urls as search_urls urlpatterns = [ url(r'^frontend/', include(frontend_urls)), url(r'^search/', include(search_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /* search project URLS.PY */ ACCOUNT_PATTERNS = [ url(r'^profil$', views.MyProfileFormView.as_view(), name='profile'), ] urlpatterns = [ url(r'^gestion/', include(ACCOUNT_PATTERNS, namespace='account')), ] And here is the 2.0 modified version I am trying to work with : /* Main project URLS.PY */ temppatterns = [ path('admin/', admin.site.urls), path('search/', include(search_urls)), ] urlpatterns = temppatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /* search projects did not change */ But when I go to /search, I got this NoReverseMatch at /search/ 'account' is not a registered namespace I do believe there was some huge change on the URLConf but I can't find any documentation to help me understand what and why. To …