Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SyntaxError: invalid syntax - Python/Django
I am trying to simply display data from my database in Django. I am getting the following error; Syntax Error My code in views.py is as follows; def InputDisplay(request): input_info = Input.objects.all() args = {"input_detail" : input_info} print args return render_to_response('Project/display.html', args, context_instance=RequestContext(request)) My if statement in display.html; {% block head %} <title> Display Measurements</title> {% endblock %} {% block body %} <div class="container"> <h1> Input Details </h1> {% for detail in input_detail %} {{ detail.id }} {{ detail.waist }} {{ detail.height }} {% endfor %} </div> {% endblock %} Any help is greatly appreciated. -
Save filled form data in Django if user is not logged in?
I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like: # ./app/models.py class SubscribeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=80) # ./app/forms.py class SubscribeForm(forms.Form): phone = forms.EmailField(label='Phone Number', max_length=100) Also, my view for this model like: # ./app/views.py from django.contrib.auth.mixins import LoginRequiredMixin from users.models import User class SubscribeView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'app/subscribe.html' form_class = SubscribeForm def post(self, request): user = get_object_or_404(User, id=request.user.id) form = self.form_class(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') return render(request, self.template_name, {'client': user, 'form': form}) Would be great to understand what to do that logic after save form: Anonymous user fill the form and click Save; He is redirecting to login page (because LoginRequiredMixin); After enter to the site, all data which he filled — saved to his account (automatically). This feature we can see when online shopping: we choose goods, add to our cart and only later, site ask us for login to site, if we are not (for save our order). I think, my question solve saving data to request.session and re-save to DB after logged in, but I have … -
How to test without hitting database
I want to test this code without hitting the database and using pytest and pytest-mock: from django.db.model import Q from orders.models import Order def get_orders_without_comment(): return Order.objects.filter(Q(comment__exact='') | Q(comment__isnull=True})) Here is my test: import pytest from django.db.models import Q from pytest_mock import mocker from .utils import get_orders_without_comment def test_get_orders_without_comment(mocker): orders_mock = mocker.patch('orders.models.Order.objects') orders = get_orders_without_comment() orders_mock.filter.assert_called_with(Q(comment__exact='') | Q(comment__isnull=True)) Here is the pytest exception: E AssertionError: Expected call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E Actual call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E E pytest introspection follows: E E Args: E assert (<Q: (OR: ('p...ll', True))>,) == (<Q: (OR: ('pi...ll', True))>,) E At index 0 diff: <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> != <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> E Use -v to get the full diff What am I doing wrong? -
Why django is not accepting spaces in template?
{% %} means that this is a django template delimiter. So inside {% %} the space should not matter I guess. Now in the example: <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> This is showing expected output whereas <a href="{% url 'post_detail' pk = post.pk %}">{{ post.title }}</a> is showing error. Why this is sensitive to whitespace? -
Django Attribute Error: object has no attribute '__state' and removing __init__ from Class
I'm trying to create a model for a sample Django application "webshop", and I'm having trouble at understanding what my problems stem from. The models.py I have is: from django.db import models class Product(models.Model): def __init__(self, title, quantity, description, image_url=""): title = models.CharField(max_length=255) self.quantity = quantity self.title = title self.description = description self.image_url = image_url def sell(self): self.quantity = self.quantity - 1 and what I want to be able to do with it is to initialize it with something like: toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) I can call it with print(toy1.quantity) print(toy1.title) toy1.sell() and so on fine, but doing toy1.save() returns the error AttributeError: 'Product' object has no attribute '_state' Upon googling about the problem, I came across the fact that it's not advised to use init here, but the offered alternatives in https://docs.djangoproject.com/en/1.11/ref/models/instances/#creating-objects both utilize a logic where the first call of the class function is different from the initial call. If the problem I'm facing is due to relying in __init__, how can I get rid of it while still being able to initialize the objects with toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) or is my problem something completely different? -
Join related models in django rest framework
Trying to create an API method for getting user profile. The problem is that there are two tables related to user: built in django User and SocialAccount from allauth framework. I guess the joining part should be in serializers so after a research I came up with this: from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'first_name', 'last_name') class SocialSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = SocialAccount fields = ('uid', 'provider', 'user') It works but it outputs it as nested objects: { "uid": "", "provider": "", "user": { "pk": 5, "first_name": "", "last_name": "" } } I would like it to be as one object: { "uid": "", "provider": "", "pk": 5, "first_name": "", "last_name": "" } -
Django_hosts Not Working With Django's Default Authentication
I'm using this package called django_hosts to re-route urls for some apps. Everything is working fine except for the fact that django_hosts is not working with Django Authentication. I hosted this url api.example.com, so on this page with the url api.example.com:8000/add_post, I want users to add post but before doing that you must be authenticated. So after I logged in, I still can't submit post via the form talkless of posting. But when I go back to example.com, it shows that I'm logged in but api.example.com is telling me otherwise. How do I make django authentication work with this package? -
Docker alpine python 3.6 build for django and postgres
I want to build and setup and docker image. My dependencies on requirements.txt bcrypt passlib psycopg2 Django My Docker File FROM python:3.6-alpine ENV PYTHONUNBUFFERED=1 RUN apk update \ && apk add --virtual build-deps gcc \ && apk add postgresql-dev \ && apk del build-deps RUN apk add libffi-dev ENV APP_DIR=/service RUN mkdir $APP_DIR WORKDIR $APP_DIR ADD requirements.txt $APP_DIR/ RUN pip install -r requirements.txt ADD . $APP_DIR/ CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"] I am getting errors like Collecting cffi>=1.1 (from bcrypt->-r requirements.txt (line 1)) Downloading cffi-1.11.4.tar.gz (436kB) Complete output from command python setup.py egg_info: unable to execute 'gcc': No such file or directory unable to execute 'gcc': No such file or directory No working compiler found, or bogus compiler options passed to the compiler from Python's standard "distutils" module. See the error messages above. Likely, the problem is not related How can I setup docker python3.6 for my django project successfully. ? -
django choice field returning index but not actual name
models.py class WebFieldType(models.Model): WEBFIELD_CHOICES = ( ('FACEBOOK', 'fb'), ('INSTAGRAM', 'Insta') ) webfield_type = models.CharField(null=True, blank=True, max_length=30, choices=WEBFIELD_CHOICES) def __unicode__(self): return '{}".format(self.webfield_type) class WebTokens(models.Model): token_name = models.TextField() web_field_type = models.ManyToManyField(WebFieldType) def __unicode__(self): return '{}-{}".format(self.token_name,self.template_type) Now in shell if I do like: WebFieldType.objects.all().values('webfield_type'), it is returning [{'webfield_type' : 'FACEBOOK'}, {'webfield_type' : 'INSTAGARAM'} But if I do like WebTokens.objects.all().values('token_name','web_field_type') it is returning [{'token_name' : 'some_token_name','web_field_type' : 1}] As you can see in web_field_type it is returning id, but I need name. Even tried using return '{}".format(self.get_webfield_type_display()) in WebFieldType model but in vain. So basically I need everything that is stored in WebTokens model when I make a call to it. -
Django Triagam: create gin index and search suggested words in Django
I have model with title and description fields. I want to create a GIN index for all the words in the title and description field So I do it the following way using SQL: STEP1: Create a table with all the words in title and description using simple config CREATE TABLE words AS SELECT word FROM ts_stat('SELECT to_tsvector(''simple'',COALESCE("articles_article"."title", '''')) || to_tsvector(''simple'',COALESCE("articles_article"."description", '''')) FROM "articles_article"'); STEP2: Create GIN index CREATE INDEX words_idx ON words USING GIN (word gin_trgm_ops); STEP3: SEARCH SELECT word, similarity(word, 'sri') AS sml FROM words WHERE word % 'sri' ORDER BY sml DESC, word; Result: word sml sri 1 srila 0.5 srimad 0.428571 How to do this in DJANGO and also i have to keep updating the GIN index -
docx file downloaded from Django is corrupt
Im trying to take user input from a form and then using that data to create a document using python docx module. But the downloaded file is not opening in MS word. It says the file is corrupt. Can someone help me with this? def resume_form(request): form = forms.resume() if request.method == 'POST': form = forms.resume(request.POST) if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) f = io.BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' response['Content-Length'] = length #document.save(response) return response return render(request, 'sample_app/index.html', {'form' : form}) -
git server and django program inside nginx
I want to run a git server inside my django program. my nginx config is like this: server{ listen 192.168.1.250:80; root /var/www/html/git; location /server\.git { client_max_body_size 0; # Git pushes can be massive, just to make sure nginx doesn't suddenly cut the connection add this. auth_basic "Git Login"; # Whatever text will do. auth_basic_user_file "/var/www/html/git/htpasswd"; include /etc/nginx/fastcgi_params; # Include the default fastcgi configs fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend; # Tells fastcgi to pass the request to the git http backend executable fastcgi_param GIT_HTTP_EXPORT_ALL ""; fastcgi_param GIT_PROJECT_ROOT /var/www/html/git; # /var/www/git is the location of all of your git repositories. fastcgi_param REMOTE_USER $remote_user; fastcgi_param PATH_INFO $1; # Takes the capture group from our location directive and gives git that. fastcgi_pass unix:/var/run/fcgiwrap.socket; # Pass the request to fastcgi } location / { include proxy_params; proxy_pass http://192.168.1.250:8000; } } my django program run correctly, but for git server, I cannot open that. but when I change the location of django program, both of them work correctly. location /user { include proxy_params; proxy_pass http://192.168.1.250:8000; } I want to use just "/" and not to "/" + string. what should I do?? -
use pygobject in apache
I want to use NetworkManager in a module in a django project. for use this module I use this codes: import gi gi.require_version('NM', '1.0') from gi.repository import NM . .#the code that use NM . when I run this django project with "runserver" there is not any error and anything work correctly. but when I run with apache, it does not work. it stop at line "from gi.repository import NM". I check for apache accesability but it is not affect. beacuse NM (or any other modules form gi,for example GLib) is dynamic and in C language I can not debug it. my system is ubuntu server 16. anybody can help me what is wrong in apache? -
Django: namespace isn't unique
In Django 1, I used to have the following URL mappings: ... url(r'^main/', include('main.urls', namespace='main')), url(r'.*', include('main.urls')) The r'.*' mapping is always at the last line to take care of all kinds of URLs not mapped. In Django 2, the following mappings are used instead: path('main/', include('main.urls', namespace='main')), re_path('.*', include('main.urls')), Although it also works, yet Django complains: ?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace Giving the second mapping another namespace is not working. Any solutions? -
Get onclick url with request in django
I have a template like bellow: <a href={{j}}> <img src="{{k}}" class="img-responsive img-rounded" data-toggle="modal" data-target="#myModal" style="width:350px;height:200px;"> </a> Now i have a function like bellow: def finction_url(requerst): a=get_the_value_of_{{j}} ### how to get the value of {{j}} Now i want to send the {{j}} value to the function (function_url) when user clicks on the photo url . Kindly suggest , either with ajax or django -
AttributeError: module 'django.db.models' has no attribute 'DateTime'
I am new to Django and i'm struck in this error: AttributeError: module 'django.db.models' has no attribute 'DateTime' I don't know the module related to DateTime model -
NoReverseMatch error with password reset emails
I have been trying to create a system for password reset emails. I have been following this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html I am getting this error when I try to visit /password/reset/ : django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Here are the relevant url patterns in urls.py: urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^password/reset/$', auth_views.password_reset, name='reset_password'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='password_reset_complete'),] How do I make this page render correctly? -
Django url variable catching
I'm having trouble at having Django urlpatterns catch a variable as an variable and instead take it as a set URL. urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/', views.about), url(r'^views/available_products/', views.available_products), url(r'^views/productview/<int:product_id>/', views.productview) ] When I host the server and go to /about/, /views/available_products/ or /admin/ they work fine, but trying to go to /views/productview/1/ gives a 404 error whereas going to /views/productview// gives a missing argument -error. I tried to read the documentation and saw no obvious tell as to why my url variable argument wouldn't work, but clearly I'm doing something fundamentally wrong. Here is an example error message from the debug page: Page not found (404) Request Method: GET Request URL: http://localhost:8000/views/productview/12/ Using the URLconf defined in firstdjango.urls, Django tried these URL patterns, in this order: ^admin/ ^about/ ^views/available_products/ ^views/productview/<int:product_id>/ The current path, views/productview/12/, didn't match any of these. And here is the same error message but where the URL I try with is the same as in urlpatterns: TypeError at /views/productview/<int:product_id>/ productview() missing 1 required positional argument: 'product_id' Request Method: GET Request URL: http://localhost:8000/views/productview/%3Cint:product_id%3E/ Django Version: 1.11.8 Exception Type: TypeError Exception Value: productview() missing 1 required positional argument: 'product_id' Server time: Sat, 10 Feb 2018 12:25:21 … -
How to handle inefficiency of Django's Queryset?
I've seen other questions, but unfortunately i couldn't find similar problems yet. The size of information is approximately equal to 1 GB, but the amount of objects that i'm iterating through is very big. (I'm unable to find it out though, shell is automatically killed in minutes after i execute len(model.objects.all()). Considering that the process is killed just by trying to get its length, I knew searching through the objects would be negligible (and even searching through them by utilizing similarity algorithms). But i still tried it, I've used Cosine similarity to find out the best match, this is the code for search: zsim = ("", 0) for qst in Question.objects.all().iterator(): sim = cosine_similarity(qst.question, string) if zenith_sim[1] > 0.75: break elif sim > zenith_sim[1]: zenith_sim = (qst.answer, sim) return str(zenith_sim[0]) The code above searches for the string that is most similar to the string of the user, although to avoid insignificant iteration, if the similarity is above 75%, it breaks the loop. I've also used iterator() method hoping that it would save some memory. As expected, the process was killed few minutes later after its execution. I'm not sure how can this be improved. The machine itself is not slow, … -
Sending not only form input via a POST request but other data as well
I'm trying to "develop" an application that stores todo tasks in a table. These tasks are organised like sub tasks for a "head" task. The problem is that when submitting an input as a sub task via POST I need the name of the head-task as well. I can't figure out how to send the information have stored in my <h1>-label with the information I have in my <input>. Here is my code example: <h1>Taskheader</h1> <form action="/todo/task/" method="post"> <input type="text" name="Taskitem"> <input type="submit" value="Submit" /> </form> Is it possible to send this information off, without using overly complicated code for a beginner? -
i want user enter product name and quantity then using query show whether the stock available or no
please correct my code or guide me ho to do my funtion def productsearch(request): product=request.GET.get('product') quantity=request.GET.get('quantity') product_result=Product.objects.all().filter(product_id=product) if ('quantity') > product_result.quantity_onhand: print('stock is not available') return render(request,'product/productlocation.html',{'product_result' : product_result,'quantity_result':quantity_result, 'product': product,'quantity':quantity}) template... <body> {% if quantity_result %} {% for r in quantity_result %} {{r.quantity_onhand}} {% endfor %} {% else %} <h3>no results</h3> {% endif %} </body> -
Add reverse ForeignKey relation to existing instances from django admin
If I create a new model which is a ForeignKey of another, can I update existing instances of "another" to have the new ForeignKeys as I create them? i.e. without going through the individual edit page of each instance of "another"? Suppose that I have a Car model, and I create a bunch of Car instances filling their details in the django admin: # models.py from django.db import models class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) ... After a year I decide to start renting cars to customers: # models.py from django.db import models class Customer(models.Model): name = models.CharField(max_length=200) ... class Car(models.Model): make = models.CharField(max_length=200) model = models.CharField(max_length=200) color = models.CharField(max_length=200) rented_to = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) ... If I register Customer in the admin site, I can add new customers, edit their attributes and, using inlines, add new cars that are rented to that customer: #admin.py from django.contrib import admin from .models import Car, Customer class CarInline(admin.StackedInline): model = Car extra = 3 class CustomerAdmin(admin.ModelAdmin): inlines = [CarInline] admin.site.register(Customer, CustomerAdmin) Is there a way to add existing Car instances to a Customer from the Customer admin page, instead of clicking through all the cars and selecting … -
Django annotate count value of other class
Im new to Django. Im trying to display a total sum. Portfolio Model: # Create your models here. class Portfolio(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, related_name='portfolios', on_delete=models.PROTECT) def get_absolute_url(self): return reverse('portfolio:detail',kwargs={'pk': self.pk}) def __str__(self): return self.name class PortfolioItem(models.Model): portfolio = models.ForeignKey(Portfolio, related_name='items', on_delete=models.CASCADE) trade = models.ForeignKey(Trade, on_delete=models.CASCADE) Trade Model # Create your models here. class Trade(models.Model): quantity = models.FloatField() open_price = models.FloatField() commision = models.FloatField(null=True,blank=True) exchange_rate_usdsek = models.FloatField(null=True,blank=True) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) #portfolio = models.ForeignKey(Portfolio, related_name='trades', on_delete=models.PROTECT) open_date = models.DateTimeField(auto_now_add=True, null=True) def get_absolute_url(self): return reverse('trade:detail',kwargs={'pk': self.pk}) def __str__(self): return self.stock.name @property def profit(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return ((now - buy ) / buy)*100 def net_gain(self): #(sold - buy) / buy buy = self.open_price * self.quantity now = self.stock.current_price * self.quantity return now - buy Portfolio index.html {% extends 'user/layout.html' %} {% block body %} {% for portfolio in all_portfolios %} <h3>{{portfolio.name}}</h3> <p>Total: {{portfolio.total_amount}}</p> <table class="table"> <thead> <tr> <th>Stock</th> <th>Amount</th> <th>Open Price</th> <th>Net P/L %</th> <th>Net P/L</th> </tr> </thead> {% for item in portfolio.items.all %} <tr> <td>{{item.trade.stock.name}}</td> <td>{{item.trade.quantity}}</td> <td>€{{item.trade.open_price}}</td> <td>€{{item.trade.stock.current_price}}</td> <td>{{item.trade.profit|floatformat:"0"}}%</td> <td>€{{item.trade.net_gain|floatformat:"2"}}</td> </tr> {% endfor %} </table> {% endfor %} {% endblock %} Portfolio view class IndexView(generic.ListView): template_name … -
How to upload and read PDF files in Django
I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename)) TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile index.html <input type="file" name="fupload" multiple> view.py if request.method == 'POST': files = request.FILES.getlist('fupload') pdf_data = [] for filename in files: read_pdf = PyPDF2.PdfFileReader(open(filename)) page = read_pdf.getPage(0) page_content = page.extractText() pdf_data.append(page_content) Can any body tell me what I am doing wrong. Thanks in advance -
Django 2 production image upload results in 500 error
I am using Django 2.0.1 within a virtual environment in production mode with Apache 2.4. Whenever I try to upload an image from Django's admin panel I get a server error 500. The specific error is [Sat Feb 10 11:37:42.473376 2018] [mpm_event:notice] [pid 1311:tid 140525266585472] AH00491: caught SIGTERM, shutting down Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/var/www/springspree/server/venv/lib/python3.5/site-packages/PIL/Image.py", line 587, in __del__ NameError: name 'hasattr' is not defined The virtualhost file is <VirtualHost *:8000> ServerAdmin webdev@springspree.in ServerName www.springspree.in:8000 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/springspree/server/static <Directory /var/www/springspree/server/static> Require all granted </Directory> Alias /media /var/www/springspree/server/media <Directory /var/www/springspree/server/media> Require all granted </Directory> <Directory /var/www/springspree/server/springspree> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django-server python-path=/var/www/springspree/server python-home=/var/www/springspree/server/venv WSGIProcessGroup django-server WSGIScriptAlias / /var/www/springspree/server/springspree/wsgi.py </VirtualHost> The files are in /var/www directory owned by root. I tried uninstalling and installing Pillow but no use.