Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (CSRF cookie not set.) when csrf is in header
The request header is as below. Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, br Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:129 Content-Type:text/plain Host:localhost:9000 Origin:http://localhost:8000 Referer:http://localhost:8000/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 X-CSRFTOKEN:t5Nx0SW9haZTeOcErcBDtaq6psqBfeyuX4LRQ1WOOXq5g93tQkvcUZDGoWz8wSeD The X-CSRFTOKEN is there but Django still complain about CSRF cookie not set. What happen to Django? In settings.py, the naming are perfectly correct. CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" -
validate and save in django field
I have written a function that accept as input a string and do some validation tasks on it and also changes the value. def validate(str): # do validation. If any error, raise Validation error # modify value of str return str I want to use this function as a validator for some django model field. I know how to do it. My problem is that in addition to validation I want the modified value, i.e. return value of function, to be saved in field. -
Suggest a Url pattern (to be used in django project) to match a url coming appended to my domain and send that url to my view
Can anyone suggest a django url pattern, which I can use into my project's urls.py, having such a regex to match a url . I have tried this pattern : url(r'^(?P<preurl>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',prepend_view) But this is failing on some exceptional urls.. Please take into consideration all exceptional urls too, like the following: ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass?one mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 and specially consider this one too: https://www.google.co.in/search?ei=45b1WaCFBoHpvgT7or-4CA&q=create+querydict+from+dictionary&oq=create+querydict+from+dictionary&gs_l=psy-ab.3...19031.33499.0.34313.59.47.3.0.0.0.450.6027.0j11j12j2j1.27.0....0...1.1.64.psy-ab..31.24.4689.6..0j35i39k1j0i20i263k1j0i131k1j0i13k1j0i22i30k1j33i22i29i30k1j33i21k1.297.EmAPX8QpKAw That is I, struggled escaping '?' but was unsuccessful.. Thanks Beforehand for your help.. -
True Django ORM returns empty result
I have two model classes, each containing following info. Model A latitude = models.FloatField() longitude = models.FloatField() Model B latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) Now I want to filter something from model B with ModelB.objects.filter(latitude=model_a_obj.latitude, longitude=model_a_obj.longitude) which returns an empty QuerySet. The latitudes and longitudes are correct though. Because, when I do this to get the model B object ModelB.objects.filter(some_string_field="String I know by hand")[0].latitude == model_a_obj.latitude it returns True, for longitude as well True. So, why does the filter method from above return an empty result? -
How to attach csrf header and value in axios POST request
I need to send crsf token when the user sign up with form provided. However, since the signup/signin will be the first time to interact with django rest api, so I create a dummy GET request when the webpage is loaded to retrieve the crsf token from django. The token is retrieved and stored in cookie. However, I still get Forbidden (CSRF cookie not set.) from django. This is my axios POST request. import axios from 'axios' axios.defaults.xsrfCookieName = 'vcubes' axios.defaults.xsrfHeaderName = 'X-CSRFToken' let req = { url: 'http://localhost:9000/vcubes/signup/', method : 'POST', headers: { 'Content-Type': 'text/plain' }, data: data } NOTE: When I add withCredentials: true into headers in axios POST, the browser send OPTIONS request instead of POST. -
regex match words without two underscores next to each other
I want to write a regex that matches all words that contains alphanumeric characters + underscore, but not those that have two underscores next to each other! match example : 123dfgkjdflg4_, ad, 12354 not match example : 1246asd__ -
Line graph cannot be drawn accurately
Line graph cannot be drawn accurately. I wrote in views.py @login_required def result(request): return render(request, 'result.html', {'chart': _view_plot(request)}) def _view_plot(request): results = ImageAndUser.objects.filter(user=request.user).order_by('-consultation_date') scores = [100, 300, 200] dates = ['2016-04-10', '2016-10-05', '2016-10-10', '2016-10-11', '2016-12-10'] heights = [results[0].score, results[1].score,results[2].score, results[3].score, results[4].score] image_data =[] for i in range(len(scores)): if scores[i] != None : image_data.append(scores[i]) image_data.append(dates[i]) image_data.append(heights[i]) image_scores =[] image_dates = [] image_heights = [] for j in range(0,len(image_data),3): image_scores.append(image_data[j]) image_dates.append(image_data[j+1]) image_heights.append(image_data[j+2]) plt.plot(image_scores, image_heights) plt.xticks(image_scores, image_dates) jpg_image_buffer = cStringIO.StringIO() plt.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array when I read result method,line graph is drawn I really cannot understand why the order of horizontal axis is not '2016-04-10', '2016-10-05', '2016-10-10' .And I really cannot understand why graph is not line graph. How should I fix this?I think this way is for making line graph but am I wrong?What sholuld I write it? -
Django FileUploadHandler that uploads to Amazon S3
django-storages uploads into S3, but only after the entire file has been saved locally in my server. I want something else - upload the file to S3, chunk-by-chunk, without saving the entire file in my server. I can't use the AWS JS SDK, because I need to perform some calculations on the uploaded file. Thus, FileUploadHandler seems like the obvious choice - I can read each chunk, perform my calculation, push that chunk into S3 (asynchronously?), and repeat. Any implementations in existence? -
What's 'slug' for in Django?
In Django, there's slug_filed, slug_url_kwarg What is the definition of slug? I choose the more persuasive explanation within items of 3 dictionaries. In Cambridge dictionary:'a piece of metal used instead of a coin for putting in machines' In MW: 'a disk for insertion in a slot machine; especially :one used illegally instead of a coin' In Oxford:'A part of a URL which identifies a particular page on a website in a form readable by users.' They don't seem make sense. -
Deploying heroku tutorial app locally, but stuck after env file loaded
I am following the "Getting Started on Heroku with Python" tutorial, which instructs me to deploy the example django app locally. https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally However, the command prompt gets stuck after loading the env file and nothing happens after that even waiting for hours. My command prompt looks like this: C:\Users\arlok\python-getting-started>heroku local web -f Procfile.windows [OKAY] Loaded ENV .env File as KEY=VALUE Format The proc file contains: web: python manage.py runserver 0.0.0.0:5000 I am running this on a virtual env with dependencies installed per the instructions. Any idea on how to fix this or even troubleshoot it? -
Django apache server not stable
I have setup django with apache web server. It work but I noticed something strange. Sometimes, the page that I load working normally. Then, if I press refresh it becomes error, page not found. If I keep refreshing, sometimes it returns to normal page sometimes it becomes error. After I restart apache, it always works fine. I noticed this strange behavior appear if I tried to access some page that doesn't exist and give page not found error. Then, if I return back to the correct page, the strange behavior appears. It is as if the server or django has some cache to the error and then randomly display it. How should I handle this? -
Beginner Docker docker-compose
I'm going through this tutorial and I've successfully got the stack up and running. What's bugging me is that when I change my code (in the web service) on my host, it does automatically make the changes when I reload the page in the browser. I don't understand why it's doing that. Here's my docker-compose.yml file: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - ./web:/usr/src/app - ./web/static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000 nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - web links: - web:web postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data I didn't think that this was gunicorn doing the reloading because I believe gunicorn needs the --reload flag to actually do hot reloading. -
Django avoid user to go back to login page once logged in
The admin app in django has this behaviour, and I want to replicate it in my project. In the admin, once you login and press the browser back button, shows the home page again, and the it does not let you go back any further. It doesn't seem it uses javasccript. Any ideas how to accomplish this? Thanks. -
Django: How to register a user with "code" and pre_save signal
sorry if the title is not so descriptive, I did not know how to put it. I have two tables: 1.- The "Matricula" table which contains a code field and another "is_taken" field that is in "False" 2.- The "User" table and when registering a new user must insert an existing code in the table "Matricula", if the code exists then "is_taken" will be "True" and allow the user to register, my question is ... How can I do it ?, Which way would be the best? I was dealing with a "pre_save" signal but without success. models.py class Matricula(models.Model): code = models.CharField(max_length=9, blank=True) is_taken = models.BooleanField("¿Esta ocupado?", default=False) created_at = models.DateTimeField("Fecha de creación", auto_now_add = True) updated_at = models.DateTimeField("Fecha de actualización", auto_now = True) def __str__(self): return "%s" %(self.matricula) class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): matricula = models.CharField("Matricula", max_length=9, blank=True) email = models.CharField("Correo Electrónico", max_length=100, blank=True, unique=True) first_name = models.CharField("Nombre(s)", max_length=60, blank=True) last_name = models.CharField("Apellidos", max_length=60, blank=True) is_staff = models.BooleanField("¿Es Staff?", default=False, blank=True) is_active = models.BooleanField("¿Es Activo?", default=False, blank=True) date_joined = models.DateTimeField("Fecha de registro", auto_now_add=True) Or could it be added in the views? in the process of user registration? And sorry for my bad english -
How to make Django Model run some function when create
what i want I have a column "length" in model episode ,and another have a column "sum_length" in series. i want sum_length only update when episode create, don't update when i modify it. How i do this now? now, i override the save function,and add a function call to update it, just like this. def save(self, *args, **kwargs): if not self.excerpt: md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) self.excerpt = strip_tags(md.convert(self.description))[:54] self.series.addlength(self.video_length) super(Episode, self).save(*args, **kwargs) due to my excerpt is generate by markdown content, so i think when excerpt is blank, it's save, not update Why i ask this question ? my workaround is useable ,but i want to find a more pythonic code my workaround will not update when i really need update it. What you can give me ? maybe a sample code is fine other information Django :1.11.6 Python :3.6.3 Database: MySQL Thanks For your answer -
MSSQL with Django
I'm running Python 2.7 with Django/DRF installed on Win 10 Enterprise. My goal is to access a legacy MSSQL database that's running now on SQL Server 2017 on this machine. I've had some trouble on a couple of different tries getting Python to work with MSSQL at all, usually in some obscure error. I've gotten Django to work fine with MySQL, Postgres, and SQLite otherwise. However, this is a database that I designed many years ago when I was using .NET/MSSQL professionally, and the database is currently being used in production, and some of the clients are actually using legacy MS Access as an ADO project (cringe) to access MSSQL, so moving everything over to a different RDBMS this late in the game is not very feasible. It will create a lot more trouble than it's worth. On a side note I did some preliminary testing with .NET Core as a test for possibly using it as just a Web API server to access the DB, I was not happy with some of the movements that were done in the EF Core arena. It was very slow in my tests, and didn't support some things that I need. I wrote … -
Install django alongside PHP web with apache
I have successfully install Django with apache. Then, I tried to install adminer for mysql administration which uses php. I have created separated virtual host for both django and adminer. When I access adminer web, it display "DisallowedHost at /" error. I know that error is belong to django. Below is my config for both django and adminer. For django: WSGIScriptAlias / /home/bharata/pythonweb/myfirstdjango/myfirstdjango/wsgi.py WSGIPythonHome /home/bharata/virtualenv/ WSGIPythonPath /home/bharata/pythonweb/myfirstdjango/ <Directory /home/bharata/pythonweb/myfirstdjango/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/bharata/pythonweb/myfirstdjango/myfirstdjango> Options Indexes FollowSymLinks AllowOverride None Require all granted <Files wsgi.py> Require all granted </Files> </Directory> For adminer: <Directory /home/bharata/website/adminer/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> I have set the config file in sites-available accordingly. For django: <VirtualHost *:80> ServerAdmin email.com ServerName python-web.local.com ServerAlias www.python-web.local.com DocumentRoot /home/bharata/pythonweb/myfirstdjango ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> For adminer: <VirtualHost *:80> ServerAdmin email.com ServerName adminer.local.com ServerAlias www.adminer.local.com DocumentRoot /home/bharata/website/adminer ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I have set the value for both adminer.local.com and python-web.local.com in the etc/hosts to 127.0.1.1. It seems that apache redirect all request to be handled by wsgi because I set the WSGIScriptAlias to / How can I set apache to distinguish when to use the wsgi and … -
django inserting instead of updating
I've read many questions related to this issue but I haven't found the solution in any of them. In my app, the user logs in and may change some fields in HIS/HER profile. Basically, what I need is to update the user's profile instead of creating a new one. This is my view: @login_required def profile(request, user_id): try: user = User.objects.get(pk=user_id) profile = Profile.objects.get(pk=user_id) ProfileFormset = inlineformset_factory( User, Profile, fields=('nick_name', ), can_delete=False) except: return render_access_denied_message(request) if request.user.is_authenticated() and request.user.id == user.id: if request.method == 'POST': user_form = UserProfileForm(instance=user, data=request.POST) if user_form.is_valid(): profile_formset = ProfileFormset( request.POST, instance=profile) assert False, profile_formset.is_valid() if profile_formset.is_valid(): assert False, user_form # at this point both form are valid current_user = user_form.save() #saves a new user with empty username #assert False, current_user profile_formset.user_id = user_id profile_formset.save() return confirmation_page(request, user_id) return render_access_denied_message(request) else: user_form = UserProfileForm(instance=user) profile_formset = ProfileFormset(instance=user) return render(request, 'users/profile.html', { 'user_id': request.user.id, 'form': user_form, 'formset': profile_formset, }) else: render_access_denied_message(request) and my model is: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField( User, related_name='user', on_delete=models.CASCADE, primary_key=True) nick_name = models.CharField( 'Nick name', max_length=30, blank=True, default='') def __str__(self): return self.user.username def create_profile(sender, **kwargs): user = … -
django template - how to get a dictionary property without using a for loop
Doing this works {% for comment in comments %} {{ comment.user }} {% endfor %} However, I want to get all the comment.user values in the dictionary without using a for loop. Is this possible? I ask because I need to do this check {% if name in comment.user %} # check if name is in any one of the comments # do something {% endif %} -
Django {% if %} statement
I have a form that allows users to upload an image as well as an image url. Depending on which they use the image src on the page should be the uploaded image, or the image from the URL. Here's the form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price' } widgets = { 'description': Textarea(attrs={'rows': 5}), } I have two issues to sort out. The first one is, on the page where the image needs to be displayed I have the following: <img class="img-fluid" {% if product.image.url %}src="{{ product.image.url }}" {% else %} src="{{ product.image_url }}" {% endif %} alt="" /> Only the "product.image.url" images show up. I think I'm confusing myself here so am asking for help. The second thing is only allowing users to upload and image OR use an image URL - that next on the list but, for now, I want to work out how to get this issue sorted out. -
Multi-level Categories in Wagtail
I always make sure I have tried every possible avenue before coming on here for advice. That said, here is what I am currently struggling with; creating multi-level/nested categories. As an aside, it will be nice if the wagtail core developers can implement an easy way for multi-level category creation, without us having to write some vanilla-django hack for it. I have been working on this application for a few weeks, everything runs smoothly, except now, there's a business decision for a nested category to be implemented. My initial M.O was to create a ServiceCategoryIndex Page, a ServiceCategoryPage then make the ServiceIndex Page a descendant or orderable to the ServiceCategoryIndex Page as ServiceCategoryPage, Which just doesn't seem right. After a couple of iteration, I went back to my default model, then tried the url of the category using views and url like vanilla-django, the problem with is, I am not able to query the foreign key with a through relationship on the template, so I still can't get the content of the service page as a list queryset rendered out. Here're my model codes below, any suggestion or work around on this will be absolutely helpful. P.S: I am almost … -
bokeh django plot embed: large amount of white space in generated div tag
I have a Bokeh chart embed working well in my Django project but I'm having problems with the embed that it creates. I'm importing both the script and div in my template as {{ div | safe }} and {{ script | safe }} but the div is creating a large white space after itself on my template. Any ideas? Here's an image -
Using user CSS sheet in a template
I'm using Django to display user uploaded static HTML and CSS files. The HTML isn't a problem, however I can't get Django to actually render using the uploaded CSS. Project structure is the following: my_project main_app display_app my_project media user whatever.html whatver.css My main url.py contains: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^html_uploads/', include('display_app.urls')), url(r'^', include('main_app.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) display_app urls.py is: urlpatterns = [ url(r'^(?P<requested>(?:[\w]+\/?)+)$', views.readhtml, name='requested'),] The relevant part of the view is: def read_html(request, file_name): title = 'html_file_title' body = get_body(file_name) css_source = 'user/whatever.css' return render(request, "display_app/base.html", {'title': title, 'body': body, 'css_source': css_source, 'media_url': settings.MEDIA_URL,} ) The CSS simply contains: body { background-color: #FFCC66 } And the template looks like: <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ media_url }}{{ css_source }}" type="text/css" /> </head> <body> {% autoescape off %} {{ body }} {% endautoescape %} </body> With this, I get a 404 as Django fails to find /media/user/whatever.css. If I change the CSS location to: <link rel="stylesheet" href="/{{ media_url }}{{ css_source }}" type="text/css" /> The 404 warning disappears, the HTML still loads, however the CSS is silently ignored. The HTML is passed through several functions and heavily modified, therefore passing it as a string made sense, however the … -
Django user model extension in an ecommerce application
I have a django ecommerce project that works fine till I decided to improve it. I let users place order on certain services but every time they place an order they have to always input their details (name, emil, address etc) so I decided to upgrade the application to use user registration and extended the user registration so that a user can update their user account with email and address and phone number etc. The initial codes for placing an order is shown below Model class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items') product = models.ForeignKey(Product,related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) view def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'],price=item['price'], quantity=item['quantity']) cart.clear() return render(request,'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html',{'cart': cart, 'form': form}) I then created an account app and extended django user so that user can register address and mobile so that the user does not have to type it every time … -
ModelChoiceField gives “Select a valid choice” populating select with ajax call
I've tried all possible solutions on several threads and I'm still unable to fix the problem. I have the following code: models.py class CustomerVisit(models.Model): start_date = models.DateField() end_date = models.DateField() customer = models.ForeignKey(Customer) address = models.ForeignKey(Address) forms.py address = forms.ModelChoiceField(label='Address', queryset=Address.objects.none(), widget=forms.Select(attrs={'style': 'width: 100%;'})) customer = forms.ModelChoiceField(label='Customer', queryset=Customer.objects.all(), widget=forms.Select(attrs={'style': 'width: 100%;'})) views.py if request.method == "POST": # Cleaning fields post = request.POST.copy() post['address'] = Address.objects.get(id=post['address']) post['start_date'] = dateparser.parse(post['start_date']) post['end_date'] = dateparser.parse(post['end_date']) # Updating request.POST request.POST = post form = CustomerVisitForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect("customervisit:calendar") My address select its being populated based on customer selection using ajax call using select2. After reading several threads I noticed that modelchoicefield expects a Address object so that's why I'm using the following code on my view before the form is being validated: post['address'] = Address.objects.get(id=post['address']) but I'm still getting the Select a valid choice. That choice is not one of the available choices. error I'm using queryset=Address.objects.none(), because I need an empty select