Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django templates sting comprasion every time returns True
If I go to the index or annoucements page, I'm sending to the template embed_text with 'index' or 'announcements' page_name respectively. It should set active class to current link in the navbar. As shown in the picture (movies is my index page) It's my code in the index.html template {% if embed_text.page_name == 'index' %} {% block movies_active %}active{% endblock %} {% endif %} {% if embed_text.page_name == 'announcements' %} {% block announcements_active %}active{% endblock %} {% endif %} And it is code in the base.html template that extends to the index.html <li class="{% block movies_active %}{% endblock %}"><a href="{% url 'movies:index' %}"> Movies</a></li> <li class="{% block announcements_active %}{% endblock %}"><a href="{% url 'movies:announcements' %}"> Announcemets</a></li> So, every time both of expressions return True and set both of links as active, you can see it at the picture. I know, I'm missing a little detail. Please, help resolve it. -
PlaceholderField not editable when rendering model instance
Using django 1.10.5 and django CMS 3.4.2, I've got a PlaceholderField which has a fairly simple model setup; class LatestNews(models.Model): title = models.CharField( _("Title"), max_length=255 ) slug = models.SlugField( max_length=255, db_index=True, unique=True, blank=True, null=True, help_text=_('Auto generated') ) body = PlaceholderField('news') When inspecting the context in the detail view to render instances of this model obj.body has an attribute of is_editable=True. However when in structure view, is set to editable=False in render_placeholder() which I believe doesn't add it to the placeholders to render. There is a second plugin in the _rendered_placeholders list which is set to editable=True so does a kwarg have to be passed in from somewhere, or something set? Request is available in the context, so I hoped that editable would be set using that. -
How to write a stand-alone Python script working with Django modules?
In PyCharm, I created a blank new Django app. Having created some models and issued manage.py makemigrations and manage.py migrate, I tried to write a standalone script that would populate the database with initial data. In its imports I wrote: from MyApp.models import Model1, Model2, … Sadly, running this script in PyCharm throws an exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I Googled this exception, and found an answer in SO http://stackoverflow.com/a/27455703/4385532 advising to put this in the top of my script: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' So I did. Sadly, this didn’t fix the issue. Now I am greeted with another exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. What should I do? -
Wagtail (Django) page not displaying due to TemplateDoesNotExist Error
I have recently installed Wagtail CMS, into an existing Django Project. I have created a new App in my existing Django project, and placed the following into the models.py. from __future__ import unicode_literals from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] If I visit the Wagtail CMS Admin, and then go to Explorer, and Add Child Page, I now see 'Home Page' as a new Page option. As desired. However I have two problems: - Firstly, only the title field is editable. The body field is not clickable. Secondly when I publish the new page I get a template error: - TemplateDoesNotExist at /pages/test/ blog/home_page.html I have checked the documentation here: http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html and it states the following: The page template now needs to be updated to reflect the changes made to the model. Wagtail uses normal Django templates to render each page type. By default, it will look for a template filename formed from the app and model name, separating capital letters with underscores (e.g. HomePage within the ‘home’ app becomes home/home_page.html). This template file can exist in any … -
Post made up of blocks (text, image, video)
I'm trying to create a image site with a similar form for adding posts as on Imgur. A post should be made up of unlimited number of blocks of various types (text, image, video) that create finished blog post. User chooses with which block he wants to start (maybe upload an image) and then adds another block by clicking a button. I can't figure out a sensible model for blocks that would make up a single post. This is my Post model: class Post(models.Model): author = models.ForeignKey('auth.User') text = models.TextField() #just a placeholder until blocks work created_date = models.DateTimeField( default=timezone.now) isWaiting = models.BooleanField(default=True) isLocked = models.BooleanField(default=False) views = models.IntegerField(default=0) tags = TaggableManager(help_text="") I don't know if I should define separate models for textblock, imageblock and videoblock (all with ForeignKey to Post model) or if there's a better solution. I thought of a universal model that would store a TextField (for text written by the user) and a FileField (for image and video upload) used for every block type but one of the Fields in every record would always be empty (user can only write text or upload a file per block) and it seems like a "waste of space". I … -
Changing from Sqllite to Postgres on Heroku- why it is not working?
I am a bit confused , hope someone can help me out Originally I uploaded my django app to heroku account with sqllite db This is what I had in my settings file for DB DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) It didnt work great since SQLlite was getting flashed to its original state every 24 hours (but worked perfectly since I needed demo system) However now I have to make it productive so I want to change the db to connect to postgres . So I used credentials from postgres DB I created with heroku and my db in settings looks like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'd4drq1yytest', 'USER': 'xvvqgkjtest', 'PASSWORD': 'test5y55y5y5y5y5y5y5y5y5y54y45', 'HOST': '777-77-77-67-7.compute-1.amazonaws.com', 'PORT': '5432', } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) But even I changed the settings file and redeployed the new file I still see that my heroku app is connected to my sqllite DB. What did I do wrong? (I deploy using a master brunch from my github.) -
Test coverage in a docker container
So I am trying to use the coverage.py tool to measure the code coverage of my Django app, however, I have had 0 success today. Basically, my plan was after running the docker container, to have a process manager execute a .sh file, containing the following 2 lines: coverage run /path/to/manage.py test nameofapp and coverage html -d coverage_html". The problem is that the html file is not being created and I am basically getting 0 information about the coverage. After entering the docker container using docker exec -it nameofcontainer bash and reading the logs I found the following error: ---------------------------------------------------------------------- Ran 12 tests in 0.081s OK >>> Creating test database for alias 'default'... Destroying test database for alias 'default'... Traceback (most recent call last): File "/usr/bin/coverage", line 9, in <module> load_entry_point('coverage==4.3.4', 'console_scripts', 'coverage')() File "/usr/lib/python3.4/site-packages/coverage/cmdline.py", line 756, in main status = CoverageScript().command_line(argv) File "/usr/lib/python3.4/site-packages/coverage/cmdline.py", line 483, in command_line return self.do_run(options, args) File "/usr/lib/python3.4/site-packages/coverage/cmdline.py", line 641, in do_run self.coverage.save() File "/usr/lib/python3.4/site-packages/coverage/control.py", line 742, in save self.data_files.write(self.data, suffix=self.data_suffix) File "/usr/lib/python3.4/site-packages/coverage/data.py", line 673, in write data.write_file(filename) File "/usr/lib/python3.4/site-packages/coverage/data.py", line 460, in write_file with open(filename, 'w') as fdata: PermissionError: [Errno 13] Permission denied: '/.coverage' So after seeing the lack of permissions on /.coverage, I … -
Grab an object from a data base and a new user and add to database
What I am trying to do is the following: 1. Grab an product from a another user and add it to currents user. IE a. Product is a Pepsi which belongs do bob b. Other user is david 2. I want to clone the product from bob and add it to the database with David as the user and leave bob still owning it. I assume I can edit my current create function which I have copied into my edit function My current create function def create(request): if request.method == 'POST': secret_id = User.objects.get(id=request.session['user_id']) viewsResponse = Myblackbelt.objects.add_product(request.POST, secret_id) return redirect ('blackbelt:index') My models from __future__ import unicode_literals from django.db import models from ..logReg.models import User class ProductManager(models.Manager): def add_product(self, postData, user): product = postData.get('product', None) if product is not None and user: Myblackbelt = self.create(product=product, creator=user) class Myblackbelt(models.Model): product = models.CharField(max_length = 70) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) loguser = models.ManyToManyField(User, related_name='loguser') creator = models.ForeignKey(User, related_name='creator') objects = ProductManager() My views from django.shortcuts import render, redirect from . models import Myblackbelt from ..logReg.models import User def index(request): userobject = User.objects.get(id=request.session['user_id']) context = { 'info' : Myblackbelt.objects.filter(creator=userobject), 'other' : Myblackbelt.objects.all().exclude(creator=userobject), 'theUser' :User.objects.get(id=request.session['user_id']) } print(Myblackbelt.objects.all()) return render(request, … -
In django migrations are not being applied to the database
I have updated some fields of a table in my database by removing a field and adding some, as well as adding a new table. I run: python manage.py makemigrations python manage.py migrate And I get no changes detected and no changes were applied. In django admin I don't see the new table and when I click add a new record into the database it displays the old fields. This is also reflected in the database as it displays the old fields and not the new table. I have dropped all tables in the database and deleted all migrations in each app leaving init.py and I still get this error which confuses me because how can it show old fields which I have deleted and there are no record of as I have deleted the table and migrations? The code in question: from __future__ import unicode_literals from django.db import models from src.profiles.models import Profiles # Create your models here. class Product(models.Model): name = models.CharField(max_length=200, primary_key=True) description = models.CharField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class ProductsOwned(models.Model): ownedID = models.ForeignKey(Profiles.user) product = models.ForeignKey(Product.name) purchaseDate = models.DateTimeField(auto_now=True) expiryDate = models.DateTimeField() def __str__(self): return self.name … -
Handling credentials with django auth
I'm trying to create a login page to be a wrapper around another site, and to do so I have to pass the credentials from the user onto a request that is made to the wrapped website. Here is what I have so far (from the django docs): def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) # issue a request here to wrapped website if user is not None: login(request, user) # Redirect to a success page. return redirect("/") else: print("Invalid credentials") However, the problem is here that the password seems to be a hash, and I therefore can't use this in the request. Is there any way I could get access to the raw credentials to be able to send them in a request ? -
Django Celery - Passing an object to the views and between tasks using RabbitMQ
This is the first time I'm using Celery, and honestly, I'm not sure I'm doing it right. My system has to run on Windows, so I'm using RabbitMQ as the broker. As a proof of concept, I'm trying to create a single object where one task sets the value, another task reads the value, and I also want to show the current value of the object when I go to a certain url. However I'm having problems sharing the object between everything. This is my celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE','cesGroundStation.settings') app = Celery('cesGroundStation') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind = True) def debug_task(self): print('Request: {0!r}'.format(self.request)) The object I'm trying to share is: class SchedulerQ(): item = 0 def setItem(self, item): self.item = item def getItem(self): return self.item This is my tasks.py from celery import shared_task from time import sleep from scheduler.schedulerQueue import SchedulerQ schedulerQ = SchedulerQ() @shared_task() def SchedulerThread(): print ("Starting Scheduler") counter = 0 while(1): counter += 1 if(counter > 100): counter = 0 schedulerQ.setItem(counter) print("In Scheduler thread - " + str(counter)) sleep(2) print("Exiting Scheduler") @shared_task() def RotatorsThread(): print ("Starting Rotators") while(1): item = schedulerQ.getItem() print("In Rotators thread - … -
Can't load css style from middleware
Got a lottle problem. In my middleware class i do next: if request.user.id is None: return render(request, 'login.html') But all style.css doesn't work how i can fix that? -
python - MultiValueDictKeyError Django form data not being posted
I am trying to build a simple form where users can place their address. When the form is submitted, I get an error saying: MultiValueDictKeyError at /store/order/ "'street'" I believe that the data for the street address is not properly getting submitted, which is strange because I know that the street input is not empty. When I try to replace street = request.POST['street'] with street = request.POST.get('street', '') everything is marked as empty, so I know the data is not being posted. This happened at first periodically, but now it's constant. Any thoughts? views.py if request.method == "POST": street = request.POST['street'] street_num = street.split(" ", 1)[0] city = request.POST['city'] state = request.POST['state'] zip_code = request.POST['zip'] street_name = street.split(" ", 1)[1] order.shipping = str(street_num) + " " + str(street_name) + ", " + str(city) + " " + str(zip_code) + ", " + str(state) + ", " + 'US' form.html <form enctype='multipart/form-data' action='/order/' method="POST" id="shipping-form">{% csrf_token %} <span class="lead">Shipping Address</span> <div class="col-md-12 form-group"> <label class="upper text-dark"> <span>Street Address</span> <input id="street" name="street" type="text" size="50" placeholder="'123 Artist St'"> </label> </div> <div class="col-md-6 form-group"> <label class="upper text-dark"> <span>City</span> <input id="city" name="city" type="text" size="50" placeholder="'San Francisco'"> </label> </div> <div class="col-md-3 form-group"> <label class="upper text-dark"> <span>State</span> … -
Require login in a Django Channels socket?
I'm trying out Channels in Django 1.11 and set up a few consumers, looking like this: @channel_session_user_from_http def ws_connect(message, slug): if message.user.is_authenticated(): message.reply_channel.send({"accept": True}) # db logic here else: message.reply_channel.send({"accept": False}) And it worked before logging in; the connection is closed and dropped when the user is logged out. Once logged in, it begins accepting socket connections. Then, I hit accounts/logout (the default login view), and everything logs out. I can't view protected (login_required) views anymore, and it seems like everything was unset properly. However, when I open up the console and fire another websocket request, the request passes the is_authenticated check and enters with the old logged out user, as if it was not cleared. This only happens within channels, every other part of the site is logged out, but this seems to retain the session and not clear it. Is there any solution to this, am I approaching this wrong, or is this a known issue? I also tried creating a login_required decorator for it that closes the connection before executing it. Also integrated unit tests afterwards to test it and they keep failing because it keeps letting guests in (AnonymousUser). Here's the final code: def ws_connect(message, slug): … -
Django - get_list_or_404
I have a model in Django called Worlds which is linked via ForeignKey to a model: SolarSystem. When I want to access the 'SolarSystem' object from a detailed view page, I want all of the 'Worlds' objects to be read on this same page or updated at any point from an edit page. The edit page gives the errors get() returned more than one WorldsModel -- it returned 2! if I applied two 'worlds' model objects via the admin panel or Page not found (404) if the SolarSystem has no 'Worlds' in it with the following code... views.py: solarsystem = get_object_or_404(SolarSystem, solar_slug=solar_slug) try: worldlist = get_list_or_404(Worlds, related_user=request.user.id, parent_system=solarsystem) except Worlds.DoesNotExist: raise Http404('No worlds found') user_profile = UserProfileModel.objects.filter(user=request.user) if request.method == 'POST': # this bit isn't relevant as request.method is GET else: form = NewSystemForm(instance=solarsystem) worldsform = WorldForm(instance=worldlist) return render(request, 'edit.html', {'solarsystem':solarsystem, 'solar_slug':solar_slug,'form':form,'worldsform':worldsform,'user_profile':user_profile}) models.py: class SolarSystem(models.Model): user = models.ForeignKey(UserModel, related_name='SolarSystem', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50, verbose_name='Title') solar_slug = models.SlugField(verbose_name='Slug', unique=True, blank=True, null=True) class Meta: verbose_name = 'Solar System' def __unicode__(self): return str(self.user) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('detail', kwargs={'solar_slug': self.solar_slug}) def get_edit_url(self): return reverse('edit', kwargs={'solar_slug': self.solar_slug}) def save(self, *args, **kwargs): if self.user is None: self.user = UserModel.objects.get(id=1) super(SolarSystem, self).save(*args, … -
New Form Model Not Working - Exception Value: no such table
I've created a comment form for my blog site and I'm having trouble getting the form to work correctly. I can post comments for each blog post from the admin pages, but when I try to submit the form to post a comment I'm getting a table does not exists error. I've researched many questions with people getting the same errors, but non seem to directly relate to the issue I'm having. I've run ./manage.py makemigrates && ./manage.py migrate and it's showing I have no pending migrations. Any help would be greatly appreciated. Here's my relevant code: blog/models.py class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) #tag manager tags = ClusterTaggableManager(through=BlogPageTag, blank=True) #get feature image def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None def serve(self, request): from .forms import CommentForm if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.page_id = self.id comment.save() return redirect(self.url) else: form = CommentForm() return render(request, self.template, { 'page': self, 'form': form, }) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), ], heading="Blog information"), FieldPanel('intro'), FieldPanel('body'), InlinePanel('gallery_images', label="Gallery images"), InlinePanel('comments', label='Comments'), ] class BlogPageComment(models.Model): id = … -
Django: Get user's previous anonymous session key on login
In a django app, I'm trying to associate sessions for anonymous users to the new logged-in session for that user when the user logs in. In other words, on login I want to figure out the session key that existed for that user up until the moment they logged in. I realize I won't be able to get all previous anonymous uses from sessions that have expired, I'm only interested in the just-expired session_key that was used for the user up until the point they logged in and cycle_key() is called. I'm doing something similar to How to lookup django session for a particular user? but this only gives me the active session key, and I also want to access the previous. -
Viewing other user profile
I want users click on other users to visit their profil without editing their posts. here is my Profil view: def Profil(request, username): if not request.user.is_authenticated(): return render(request, 'blog/visitor.html') else: u = User.objects.get(username=username) user = request.user posts = Post.objects.filter(user=request.user) context = {'user': user, 'user_url':u,'posts': posts} return render(request, 'blog/profil.html', context) ( Is there any other solution apart this ? ) My urls.py url(r'^(?P<username>\w+)/$', views.Profil, name = 'profil'), and a link from index.html to profil.html looks like this: the problem with this is when i click on the link it passes with the current user I'm logging in with and not the user that I click on it LogIn with admin and want to see Ala's profil Link from 'Ala' to his profil When I click it shows in the url this: http://127.0.0.1:8000/blog/imedadmin/ which is supposed to be 'Ala' instead of 'imedadmin' And thanks in advance. python django -
UserWarning on Django website for Raven client
I am running Django based on Django Cookiecutter. Once I built (docker-compose build) and started (docker-compose up) everything seems to work just fine. However when I try to open the website I get an Internal server error. In the log there is an error messaage /usr/local/lib/python3.5/site-packages/raven/conf/remote.py:88: UserWarning: Transport selection via DSN is deprecated. You should explicitly pass the transport class to Client() instead. I can't really find any information except for that I have to add RAVEN_CONFIG = {} to my settings. This is my current settings file: base.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import environ ROOT_DIR = environ.Path(__file__) - 3 # (oz_m_de/config/settings/base.py - 3 = oz_m_de/) APPS_DIR = ROOT_DIR.path('oz_m_de') env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: env_file = str(ROOT_DIR.path('.env')) print('Loading : {}'.format(env_file)) env.read_env(env_file) print('The .env file has been loaded. See base.py for more information') DJANGO_APPS = [ # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Useful template tags: # 'django.contrib.humanize', # Admin 'django.contrib.admin', ] THIRD_PARTY_APPS = [ 'crispy_forms', # Form layouts 'allauth', # registration 'allauth.account', # registration 'allauth.socialaccount', # registration ] LOCAL_APPS = [ 'oz_m_de.users.apps.UsersConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
How to add page templates to Wagtail after installing into an existing Django application
I'm trying to extend an already existing Django App. The app is functioning fine as is, but I would like to add blog functionality. I've installed Wagtail, using the guidelines here (http://docs.wagtail.io/en/latest/getting_started/integrating_into_django.html) To check wagtail is installed, I have navigated to here: http://myurl/cms And the wagtail admin panel is displayed. When I navigate to http://myurl/admin I get the default admin control panel for my Django app, so far so good. Now I am trying to build the blog. I found this tutorial: http://wiseodd.github.io/techblog/2015/06/22/developing-wagtail/ which suggests the following as a first step: - First, we’ll create our generic page class as home page class is already created by default when we started Wagtail project. It then displays this code: # core/models.py from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailsearch import index # We’re deriving our GenericPage from Page class, so that our GenericPage also has Page’s field, e.g. title class GenericPage(Page): # Let’s create our custom field, named body which is a rich text body = RichTextField() # Index the body field, so that it will be searchable search_fields = Page.search_fields + (index.SearchField(‘body'),) # To show our body field in admin panel, we have to … -
How to get the attribute of inherited model of user in a template in django
I added one more field dept to the user by inheriting it.How can I access this dept in my template?My codes are models.py class CustomUser(User): dept = models.CharField(max_length=50) objects = UserManager() views.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) all_requests= Retest.objects.all() users = CustomUser.objects.all() if user is not None: if user.is_active: login(request, user) if user.groups.filter(name='hod').exists(): return render(request, 'retest/hod.html', {'all_requests' : all_requests,'users':users}) hod.html <h4>{{user.username}}</h4> <p>{{users.dept}}</p> -
Request Delete record from Django API by ID using python requests
I am testing functionality of my first Django API currently i am able to do GET and POST by using requests I am stuck on trying to make delete request by ID This is my REST_FRAMEWORK API CODE @api_view(['GET', 'POST', 'Delete']) def ShopList(request): if request.method == 'GET': snippets = Shop.objects.all() serializer = ShopSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ShopSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': shop = Shop.objects.get(id=id) shop.delete() return Response(status=status.HTTP_204_NO_CONTENT) In request.method == 'DELETE' i have tried elif request.method == 'DELETE': shop = Shop.objects.all() shop.delete() return Response(status=status.HTTP_204_NO_CONTENT) Which deletes everything How can I make a DELETE request which can delete records by given id or others attributes? My intuition lies on shop = Shop.objects.get(id = id) Which gets the objects by id but my implementation is probably wrong. Here is my request code import requests import json url = 'http://127.0.0.1:8000/shop/' payload = {'Establishment' : 'MacDonalds', 'Address' : '114/5 Albert St.', 'Suburb' : 'Wellington', 'Postcode' : '8218', 'State' : 'No Data', 'Establishment_Type' : 'Home'} requests.delete(url, data=json.dumps(payload)) The requests method above aims to search for all similar records given in the dictionary and delete it. However, objects.all() seems to delete … -
Thumbnail doesn't display with sorl thumbnail
I'm a newbie on Django. I'm trying to use Sorl thumbnail in a template. But i don't figure out why it's not working. I can display image without using thumbnail tags (in my template). But when, i use them, it's not working. Below, the code that i create: My model: from __future__ import unicode_literals from django.db import models from sorl.thumbnail import ImageField def upload_location(instance, filename): return "photos_portfolio/%s/%s/%s" %(instance.categorie, instance.slug, filename) class Portfolio(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=160) image = models.ImageField(upload_to=upload_location) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) categorie = models.ForeignKey('categorie.Categorie') article = models.ForeignKey('posts.Post') def __unicode__(self): return self.title def __str__(self): return self.title class Meta: ordering = ["-timestamp"] My View: def portfolio(request): afficher = Portfolio.objects.all() return render(request, 'portfolio.html', {'afficher': afficher}) My template: {% for photo in afficher %} <div class="image-portfolio"> <a class="example-image-link" href="{{ photo.image.url }}" data-lightbox="example-set" data-title="Click the right half of the image to move forward."> {% thumbnail photo.image "100x100" crop="center" as im %} <img class="example-image" src="{{ im.url }}" alt=""/> {% endthumbnail %} </a> </div> {% empty %} <p>No image.</p> {% endfor %} Do you have any idea where my mistake is? Thanks in advance for your help Singertwist -
django update (soft delete) status instead of delete
I am developing an rest framework api project with django. The default create/update/get/delete works easily without any major coding. All my models has a status_id field which denotes active and deleted. I only want to update the status to 'deleted' when someone try to delete a table row. I wonder is there any way to update the status of a table row instead of deleting it. So that I can review the past data if something happened in future. What code need to be added in views and serializers for this? -
Angularjs + Django Real time application
I am using DRF django rest framework ( http://www.django-rest-framework.org/ ), with angular as front-end , I am require to get real time data ,like nodejs allows socket.io to implement real time application , does django provide any third party for doing the same , i want to implement real time data in angularjs front-end with django as backend,