Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError Django at /carts
from decimal import Decimal from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save, post_save, post_delete from products.models import Variation Create your models here. class CartItem(models.Model): cart = models.ForeignKey("Cart") item = models.ForeignKey(Variation) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __unicode__(self): return self.item.title def remove(self): return self.item.remove_from_cart() def cart_item_pre_save_receiver(sender, instance, *args, **kwargs): qty = instance.quantity if qty >= 1: price = instance.item.get_price() line_item_total = Decimal(qty) * Decimal(price) instance.line_item_total = line_item_total pre_save.connect(cart_item_pre_save_receiver, sender=CartItem) def cart_item_post_save_receiver(sender, instance, *args, **kwargs): instance.cart.update_subtotal() post_save.connect(cart_item_post_save_receiver, sender=CartItem) post_delete.connect(cart_item_post_save_receiver, sender=CartItem) class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) items = models.ManyToManyField(Variation, through=CartItem) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2) def __unicode__(self): return str(self.id) def update_subtotal(self): print"updating..." subtotal = 0 items = self.cartitem_set.all() for item in items: subtotal += item.line_item_total self.subtotal = subtotal self.save() Views.py from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404, JsonResponse from django.shortcuts import render, get_object_or_404 from django.views.generic.base import View from django.views.generic.detail import SingleObjectMixin Create your views here. from products.models import Variation from carts.models import Cart, CartItem class CartView(SingleObjectMixin, View): model = Cart template_name = "carts/view.html" def get_object(self, *args, **kwargs): self.request.session.set_expiry(0) #5 minutes cart_id = self.request.session.get("cart_id") if cart_id == None: cart = Cart() cart.save() cart_id β¦ -
How should my Procfile look like?
I would like to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I get error: 2017-07-10T19:44:39.000000+00:00 app[api]: Build succeeded 2017-07-10T19:45:19.954230+00:00 heroku[web.1]: Starting process with command `gunicorn pri.wsgi` 2017-07-10T19:45:22.834045+00:00 app[web.1]: [2017-07-10 19:45:22 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-07-10T19:45:22.834597+00:00 app[web.1]: [2017-07-10 19:45:22 +0000] [4] [INFO] Listening at: http://0.0.0.0:53621 (4) 2017-07-10T19:45:22.834712+00:00 app[web.1]: [2017-07-10 19:45:22 +0000] [4] [INFO] Using worker: sync 2017-07-10T19:45:22.838348+00:00 app[web.1]: [2017-07-10 19:45:22 +0000] [8] [INFO] Booting worker with pid: 8 2017-07-10T19:45:22.842567+00:00 app[web.1]: [2017-07-10 19:45:22 +0000] [8] [ERROR] Exception in worker process 2017-07-10T19:45:22.842570+00:00 app[web.1]: Traceback (most recent call last): 2017-07-10T19:45:22.842571+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2017-07-10T19:45:22.842572+00:00 app[web.1]: worker.init_process() 2017-07-10T19:45:22.842573+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2017-07-10T19:45:22.842574+00:00 app[web.1]: self.load_wsgi() 2017-07-10T19:45:22.842574+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2017-07-10T19:45:22.842575+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2017-07-10T19:45:22.842575+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2017-07-10T19:45:22.842576+00:00 app[web.1]: self.callable = self.load() 2017-07-10T19:45:22.842576+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2017-07-10T19:45:22.842577+00:00 app[web.1]: return self.load_wsgiapp() 2017-07-10T19:45:22.842577+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2017-07-10T19:45:22.842577+00:00 app[web.1]: return util.import_app(self.app_uri) 2017-07-10T19:45:22.842578+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app 2017-07-10T19:45:22.842578+00:00 app[web.1]: __import__(module) 2017-07-10T19:45:22.842582+00:00 app[web.1]: ModuleNotFoundError: No module named 'project' It seems to me that β¦ -
Django Base Template Block Content not Rendered Correctly
Basically I am trying to have an fixed on top nav-bar and using only vanilla bootstrap. This required me to have a modification as the content needs to be padded in order for the page to render correctly. Below is the form page it renders the Nav Bar on top but the content renders underneath the navbar instead of below it. NOTE, that the base page itself works for other templates. What gives?? works(list Page): {% extends 'expirations/index.html' %} {% block content %} <div class="container-fluid"> {% for drug in drugs %} <div class = '.col-sm-12'> <ul class = 'list-group'> <li class = "list-group-item" > <span class = "badge">First Expiration: {{ drug.early_exp|date:"l M d Y" }}</span> <a href="{% url 'drug_detail' pk=drug.pk %}">{{ drug.name }}</a> {% regroup drug.expiration_dates.all by facility as facility_list %} {% for x in facility_list %} <span class="label label-info">{{ x.grouper }}</span> {% endfor %} </li> </ul> </div> {% endfor %} </div> {% endblock %} doesn't work (form Page): {% extends "expirations/index.html" %} {% block content %} <div class = "container"> <h1>Add Expiration for:</h1> <h4>{{drug_name.name}}</h4> <form method="POST" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Save</button> </form> </div> {% endblock %} index.html: <html> <head> <title>Expirations Tracker</title> <!-- Latest compiled and β¦ -
Long running file generation on Heroku + Django
I have a Django app running on Heroku. The user can download various reports in either Excel/PDF format. Some of these reports can take a minute to generate, which means I need to create them on a background/worker process. I already have celery setup together with redis as the message broker. My question is what is the best way to deal with this? This is my idea so far. As soon as the user start the report, it shows 'Generating, please wait' on the page somewhere. The file then gets generation and saved in a temporary location. Probably on S3 or in some sort of cache. I then poll a specific location and once the file is ready it returns the url of where the file is stored. At this point the 'Please wait' turns into a link. Once a day I clear out the S3 bucket using lifecycle rules I'm sure this will work, but it just seems like a lot of effort and not the best user experience either. Currently the user just waits for the file once ready the download dialog appears. This works fine as long as the file is returned within 30 seconds, which isn't β¦ -
how to count number usage of a tag? django with taggableManager
I am currently using taggableManager as my tags in django. I can see in admin what is currently using the tag but then is there a way to count them? Thanks in advance -
how to process to forms in single template and single view?
I have got two models and i have bounded those two models with two forms.now, how can i process those two forms in single view and then in templates. here are my codes so far. models.py- from django.db import models class Album(models.Model): album_title=models.CharField(max_length=50) date=models.DateTimeField(blank=True,null=True) def __str__(self): return self.album_title class Song(models.Model): song_title=models.CharField(max_length=50) genre=models.CharField(max_length=50) album=models.ForeignKey(Album,on_delete=models.CASCADE) def __str__(self): return self.song_title forms.py- from django import forms from . models import Album,Song class AlbumForm(forms.ModelForm): class Meta: model=Album fields=('album_title',) class SongForm(forms.ModelForm): class Meta: model=Song fields=('song_title','genre') views.py- def formm(request): if request.method=='POST': albumform=AlbumForm(request.POST) if albumform.is_valid: albumform=albumform.save(commit=False) albumform.date=timezone.now() albumform.save() songform = SongForm(request.POST) if songform.is_valid: songform.save() return redirect("result") else: albumform=AlbumForm() songform=SongForm() return render(request,"musicapp/formmpage.html", {'albumform':albumform}, {'songform':songform}) resultpage.html- {% extends "musicapp/basepage.html" %} {% block content %} <form method="POST" class="post-form"> {% csrf_token %} {{ albumform.as_p }} {{ songform.as_p }} <button type="submit" class="btn btn-info">POST</button> </form> {% endblock %} are my codes correct ? please do correct it, if this is wrong. -
I am new to django and python. Django URLs error: view must be a callable or a list/tuple in the case of include() [duplicate]
This question already has an answer here: Django URLs error: view must be a callable or a list/tuple in the case of include() 2 answers in Django 1.10, I get the error: TypeError: view must be a callable or a list/tuple in the case of include(). My urls.py is as follows: from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^$', 'blogs.views.home', name='home'), url(r'^admin/',include(admin.site.urls)), ] views.py code:- from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html',{}) Help me -
Heroku with Docker and Django- ModuleNotFoundError: No module named 'nameOfMyAppFromProcfile'
I would like to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. In activity I have information that Build succeeded however I get error No module named nameOfMyAppFromProcfile. It is quite strange because it looks as I should have this in my requirements.txt file. I don't understand why this error occurrs and how can I deal with it? Logs: 2017-07-10T17:34:54.977956+00:00 app[web.1]: return self.load_wsgiapp() 2017-07-10T17:34:54.977957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2017-07-10T17:34:54.977958+00:00 app[web.1]: return util.import_app(self.app_uri) 2017-07-10T17:34:54.977958+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app 2017-07-10T17:34:54.977959+00:00 app[web.1]: __import__(module) 2017-07-10T17:34:54.977962+00:00 app[web.1]: ModuleNotFoundError: No module named 'nameOfMyAppFromProcfile' 2017-07-10T17:34:54.978101+00:00 app[web.1]: [2017-07-10 17:34:54 +0000] [9] [INFO] Worker exiting (pid: 9) 2017-07-10T17:34:55.080116+00:00 app[web.1]: [2017-07-10 17:34:55 +0000] [4] [INFO] Shutting down: Master 2017-07-10T17:34:55.080338+00:00 app[web.1]: [2017-07-10 17:34:55 +0000] [4] [INFO] Reason: Worker failed to boot. Procfile: web: gunicorn nameOfMyAppFromProcfile.wsgi Project tree: βββ Backend β βββ AI β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-36.pyc β β β βββ settings.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ wsgi.cpython-36.pyc β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py βββ Dockerfile βββ β¦ -
No module named django.core when running django-admin startproject myproject
when running django-admin startproject myproject on macOS I get the error Traceback (most recent call last): File "/usr/local/bin/django-admin", line 2, in from django.core import management ImportError: No module named django.core I checked out this question but running import django won't produce any output in a python3 shell. /usr/local/bin/django-admin is a symlink to /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/bin/django-admin.py. I already put /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django in my PYTHONPATH as suggested in other questions. Am I missing something? -
Django ManyToMany through with multiple databases
TLTR: Django does not include database names in SQL queries, can I somehow force it to do this or is there a workaround? The long version: I have two legacy MySQL databases (Note: I have no influence on the DB layout) for which I'm creating a readonly API using DRF on Django 1.11 and python 3.6 I'm working around the referential integrity limitation of MyISAM DBs by using the SpanningForeignKey field suggested here: https://stackoverflow.com/a/32078727/7933618 I'm trying to connect a table from DB1 to a table from DB2 via a ManyToMany through table on DB1. That's the query Django is creating: SELECT "table_b"."id" FROM "table_b" INNER JOIN "throughtable" ON ("table_b"."id" = "throughtable"."b_id") WHERE "throughtable"."b_id" = 12345 Which of course gives me an Error "Table 'DB2.throughtable' doesn't exist" because throughtable is on DB1 and I have no idea how to force Django to prefix the tables with the DB name. The query should be: SELECT table_b.id FROM DB2.table_b INNER JOIN DB1.throughtable ON (table_b.id = throughtable.b_id) WHERE throughtable.b_id = 12345 Models for app1 db1_app/models.py: class TableA(models.Model): id = models.AutoField(primary_key=True) # some other fields relations = models.ManyToManyField(TableB, through='Throughtable') class Throughtable(models.Model): id = models.AutoField(primary_key=True) a_id = models.ForeignKey(TableA, to_field='id') b_id = SpanningForeignKey(TableB, db_constraint=False, to_field='id') Models for β¦ -
Why is global intall of Django from packages not working? (calling via python)
https://www.digitalocean.com/community/tutorials/how-to-install-the-django-web-framework-on-ubuntu-14-04#global-install-through-pip i am using this website to install django this test : django-admin --version is successfull but when I type this command : python manage.py migrate or this : python -m django --version the following error is seen: No module named 'django' Why is that so? I used this tutorial https://docs.djangoproject.com/en/1.11/intro/tutorial01/ -
The value of 'form' must inherit from 'BaseModelForm' in django
I am making a simple form to receive user's information and display on next page using django. but I am getting the error The value of 'form' must inherit from 'BaseModelForm',and when i try to inherit from ModelForm it displays the error that there is no module ModelForm. admin.py from django.contrib import admin from .models import Album from .forms import NameForm from django.forms import * from django.db.models import * from models import * admin.site.register(Album) class MyModelAdmin(admin.ModelAdmin): form = NameForm admin.site.register(NameForm, MyModelAdmin) class NameFormAdmin(admin.ModelAdmin): form = NameForm class NameForm(forms.Form): class Meta: model = NameForm views.py from django.contrib import admin from .models import Album from .forms import NameForm from django.forms import * from django.db.models import * from models import * admin.site.register(Album) class MyModelAdmin(admin.ModelAdmin): form = NameForm admin.site.register(NameForm, MyModelAdmin) class NameFormAdmin(admin.ModelAdmin): form = NameForm class NameForm(forms.Form): class Meta: model = NameForm forms.py from django import forms from .models import NameForm from django.forms import ModelForm class NameForm(forms.Form): class Meta: model = NameForm fields = '__all__' your_name = forms.CharField(label="Your name", max_length=100) name.html <form action="/profile/see" method="post"> {% csrf_token %} {{ NameForm }} <input type="submit" value="Submit" /> </form> -
Create a comma separated list from QuerySets
This link does something similar to what I want to achieve, however, it is differnt. The original question wants a string, I need a list. Python: creating a comma separated string from a query In my code, I have something like cert = [] for prospect in prospects: cert.append(prospect.certification.all()) I need to separate them by a delimiter, e.g. '-' I want something like for prospect in prospects: cert.append(prospect.certification.all()) cert.append("-") How can I achieve that? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 21: invalid continuation byte
I added a description for wine in csv file and tried to extract the data python load_wines.py data/wines.csv then I got error such as: traceback (most recent call last): File "load_wines.py", line 25, in <module> wines_df = pd.read_csv(sys.argv[1]) File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 646, in parser_f return _read(filepath_or_buffer, kwds) File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 401, in _read data = parser.read() File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 939, in read ret = self._engine.read(nrows) File "C:\anaconda\lib\site-packages\pandas\io\parsers.py", line 1508, in read data = self._reader.read(nrows) File "pandas\parser.pyx", line 848, in pandas.parser.TextReader.read (pandas\parser.c:10415) File "pandas\parser.pyx", line 870, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:10691) File "pandas\parser.pyx", line 947, in pandas.parser.TextReader._read_rows (pandas\parser.c:11728) File "pandas\parser.pyx", line 1049, in pandas.parser.TextReader._convert_column_data (pandas\parser.c:13162) File "pandas\parser.pyx", line 1108, in pandas.parser.TextReader._convert_tokens (pandas\parser.c:14116) File "pandas\parser.pyx", line 1206, in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:16172) File "pandas\parser.pyx", line 1222, in pandas.parser.TextReader._string_convert (pandas\parser.c:16400) File "pandas\parser.pyx", line 1458, in pandas.parser._string_box_utf8 (pandas\parser.c:22072) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 21: invalid continuation byte how can I solve it? -
Tensorflow/Keras with django not working correctly with celery
We are building a script for face recognition, mainly with tensorflow for basic recognition functions, from videos. When we try the soft directly with a python test-reco.py (which take a video path as parameter) it works perfectly. Now we are trying to integrate it through our website, within a celery task. Here is the main code: def extract_labels(self, path_to_video): if not os.path.exists(path_to_video): print("NO VIDEO!") return None video = VideoFileClip(path_to_video) n_frames = int(video.fps * video.duration) out = [] for i, frame in enumerate(video.iter_frames()): if self.verbose > 0: print( 'processing frame:', str(i).zfill(len(str(n_frames))), '/', n_frames ) try: rect = face_detector(frame[::2, ::2], 0)[0] y0, x0, y1, x1 = np.array([rect.left(), rect.top(), rect.right(), rect.bottom()])*2 bbox = frame[x0:x1, y0:y1] bbox = resize(bbox, [128, 128]) bbox = rgb2gray(bbox) bbox = equalize_hist(bbox) y_hat = self.model.predict(bbox[None, :, :, None], verbose=1, batch_size=1)[0] # y_hat = np.ones(7) out.append(y_hat) except IndexError as e: print(out) print(e) We need a try catch because sometimes there aren't any face present in the first frames. But then we have this line: y_hat = self.model.predict(bbox[None, :, :, None], verbose=1, batch_size=1)[0] blocking. The bbox isn't empty. The celery worker simply blocks on it and you can't exit the process (the warm / cold quit never occurs) Is there something β¦ -
Bootstrap Form Control - Django Form HTML
I've been having trouble adding HTML for Form Control to my Django form. I know (from other features) that I have Bootstrap properly integrated into the project. No fields are showing when I try to integrate form control into the page. The form has two fields: 1) a file field, and 2) a boolean field. Below is my HTML (I don't include the submit button after/closing tags. <form id='name' action = "" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <div class="col-md-4"> <!-- {{ form }} --> #Note that when this is not commented out and when the lines below are commented out, the form works correctly, but obviously with no form control. {% for field in form.visible_fields %} {% if field.auto_id == "file" %} <div class="form-group{% if field.errors%} has-error{% endif %}"> <div class="col-sm-5 col-md-4 col-xs-8 col-lg-4 col-xl-4"> <label for="file">File input</label> <input type="file" class="form-control-file" id="file" aria-describedby="fileHelp"> <small id="fileHelp" class="form-text text-muted">Test</small> <div class="input-group"> <div class="input-group-addon">$</div> {{field}} </div> {{ field.errors }} </div> </div> {% else %} {% endif %} {% endfor %} Any help would be greatly appreciated! -
setup login through Docker API in pyhton
I'm trying Docker API python library, but couldn't get a little success, have go through the docs.Actually I'm trying to login to docker using API. Here's my python Code: import docker config = os.path.join(BASE_DIR, 'IGui') + 'config.json' client = docker.APIClient.login('username', '*******', 'email@gmail.com','https://index.docker.io/v1/', config) Here's the error I received: AttributeError at /gui/docker/ 'str' object has no attribute '_auth_configs' Request Method: POST Request URL: http://127.0.0.1:8000/gui/docker/ Django Version: 1.11.3 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_auth_configs' Exception Location: /Users/abdul/IstioVirEnv/lib/python3.6/site- packages/docker/api/daemon.py in login, line 128 Python Executable: /Users/abdul/IstioVirEnv/bin/python Python Version: 3.6.1 how can I setup docker login through API in python? help me please! -
Deployment on Heroku dockerized web application, gunicorn error - /app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py
I would like to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. In activity I have information that Build succeeded however I get error: 2017-07-10T15:55:17.957033+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 344, in halt 2017-07-10T15:55:17.957377+00:00 app[web.1]: self.stop() 2017-07-10T15:55:17.957381+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop 2017-07-10T15:55:17.957792+00:00 app[web.1]: time.sleep(0.1) 2017-07-10T15:55:17.957810+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 244, in handle_chld 2017-07-10T15:55:17.958175+00:00 app[web.1]: self.reap_workers() 2017-07-10T15:55:17.958194+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 524, in reap_workers 2017-07-10T15:55:17.958709+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2017-07-10T15:55:17.958746+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Project tree: βββ Backend β βββ AI β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-36.pyc β β β βββ settings.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ wsgi.cpython-36.pyc β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py βββ Dockerfile βββ init.sql βββ Frontend β βββ angularProject βββ Dockerfile β βββ all files in my angular project βββ docker-compose.yml βββ requirements.txt Frontend's Dockerfile: # Create image based on the official Node 6 image from dockerhub FROM node:6 # Create a directory where our app will be placed RUN mkdir -p /usr/src/app # β¦ -
How to set image upload root for django application
I have trouble of setting up the root folder for uploaded images. The upload image is inside django application named api. The view returns this link on image: http://www.example.com/media/4a273bdf-564d-4dec-b657-43db27f04042.jpeg However when I go on that link I get error because image is not on there. I set in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'PAGE_SIZE': 1 } MEDIA_ROOT = os.path.join(BASE_DIR,STATIC_ROOT,'media') MEDIA_URL = '/media/' and I write this in api/models.py: from django.db import models import uuid def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) def filename(instance, filename): return filename # Create your models here. class UploadImage(models.Model): image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename) captcha_type = models.IntegerField("Image type") any ideas? -
Tutorial for Django User to User messaging
I am looking for a beginner tutorial for user to user messaging in Django. I've looked at the Postman and Post-Office packages but do not know how to integrate it into my web app. Are there any step by step videos, github examples/samples or tutorials that walk through this for someone new to Django? -
difficulty in loading image in a recommendation system
I tried to add image in the reviews page of my project.The data is loaded but the image is not updated in the page.It just shows a blank white box. my models.py looks like this: class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) wine = models.ForeignKey(Wine) pub_date = models.DateTimeField('date published', null=True) user_name = models.CharField(max_length=100) comment = models.CharField(max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) images = models.ImageField(null = True, blank=True) the code for reviews_list look like this: {% extends 'base.html' %} {% block title %} <h2>Latest reviews</h2> {% load static %} {% endblock %} {% block content %} {% if latest_review_list %} <div class="row"> {% for review in latest_review_list %} <div class="col-xs-6 col-lg-4"> <h4><a href="{% url 'reviews:review_detail' review.id %}"> {{ review.wine.name }} </a></h4> <br> <a><img src="{% static wine.images.url %}" height="200"></a> <h6>rated {{ review.rating }} of 5 by <a href="{% url 'reviews:user_review_list' review.user_name %}" >{{ review.user_name }}</a></h6> <p>{{ review.comment }}</p> </div> {% endfor %} </div> {% else %} <p>No reviews are available.</p> {% endif %} {% endblock %} the code for views.py look like this: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .models import Review, Wine from .forms import ReviewForm β¦ -
Handling django-rest-auth auth token on a client webapp developed using django
I have developed an api wgich is protected using token authentication. I m able to fetch the token once when logging in to the webapp. The token is stored in a cookie. Every call to the api contains the token. But what after the token expires? I've been unable to figure that out. How should I request a new one? I know I can request a new token using the login credentials. But what if the token expires every 300 seconds? And what is the ideal duration before it expires? Have I kept it too short-lived? Any help is appreciated. -
celery beat is sending task and receiving task also
I'm running celery beat and worker via supervisor. In the worker log file, I see it started up successfully but there 's no sign of receiving tasks. In the beat log file, I see it is both sending task and executing task [2017-07-11 00:07:09,732: INFO/MainProcess] Scheduler: Sending due task run_logster (momsplanner.tasks.response_time.run_logster) [2017-07-11 00:07:09,947: INFO/MainProcess] Task momsplanner.tasks.response_time.run_logster[6858df2a-5018-4955-ab69-5f8def4d4fe4] succeeded in 0.21451169718056917s: None What could be the cause? -
Django NoReverseMatch while return render()
Django 1.11.1 Hello Community, i allways recieve a NoReverseMatch error, and i dont know why. This ist the error message: NoReverseMatch at /suche/any-thing/ Reverse for 'article_search' with arguments '(u'any thing',)' not found. 1 pattern(s) tried: ['suche/(?P[-\w]+)/$'] So as you can see, im entering a url with "-" instead of whitespace, but django is looking for url pattern with withespace instead of "-". This is the part of my url.py: url(r'suche/(?P<search>[-\w]+)/$', views.article_search_view, name='article_search'), Suprisingly django starts to compute my article_search_view, which looks like this: def article_search_view(request, search=None): """Filters all articles depending on the search and renders them""" articles = get_active_not_rented_articles() search = re.sub(r"[-]", ' ', search) articles = articles.filter(title__icontains=search) articles = aply_sort(request, articles) orderd_by = articles[0].get('filter') articles = articles[1] return render(request, 'article/list.html', {'object_list':articles, 'url_origin':'article_search', 'parameter':search, 'orderd_by':orderd_by}) As i checked with "print()" statements, the error is raised when the return render(...) statement is called. If i do a return redirect(...) instead, no error will be raised. For completenes, my article/list.html template: {% extends "base.html" %} {% load static %} {% block content %} <div id =articles> <div class="info_filter"> <div class="header_info_filter"> {% if orderd_by == "not" %} <h1>Neueste Artikel</h1> {% endif %} {% if orderd_by == "distance" %} <h1>Artikel in Ihrer NΓ€he</h1> {% β¦ -
Get Django object from modelfield ManytoMany
I would like to get your help in order to solve my issue. I have a Django Application which is named Identity with an important model : Societe. class Societe(models.Model): Nom = models.CharField(null= False, max_length=70, verbose_name='Nom de SociΓ©tΓ©') ... #Some model fields ... user = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name="User Access", default=" ") This model is saved in my database as a table : Identity_societe When I migrated my model, a new table Identity_societe_user which looks like is appeared : This table gives an access to the Societe page for one or multiple users with societe = get_object_or_404(Societe, pk=id, user=request.user) My issue is : I don't overcome to get objects from this table : Identity_societe_user. I tried lot of things : Societe_user, Societe_User, Societe.user, ... but nothing up to now.