Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy my conda env to a VPS using fabric or othervise?
I made a website using mezzanine-Django , and used conda env to contain it (I should have used virtual env). but the fabric file is tuned to only deploy virtual envs. What should I do to get my conda env up in the VPS , is there an easy way or should I be installing every packages inside manually? -
Dockerizing multi-node python django backend served by nginx
I am trying to dockerize a project that consists of multiple backend nodes that are served by an nginx server. Would I rather have an insance of nginx running in each docker container serving just that node or would I have a "central" NGINX server that serves all nodes. In case of having a central nginx server, how would it comminicate with the backend nodes. The backend is implemented in python django. If each container has its own nginx instance, the comminication between the web server and the python django application is straighforward. But how would I serve a python django application that lives in one container from an nginx server that lives in another? In case of having an instance of nginx in each container, how would that impact the overall performace of the system? -
Speed Jquery toggle function not taken into account
I'm working on a web app. I use : Last version of Django In a virtual environment for python I use the CDN of getbootstrap (https://getbootstrap.com/) I'm trying to toggle a DIV block when I click on another DIV. This my Jquery script : {% for s in salle %} $( ".{{ s.name }}" ).click(function(event) { var className = $(this).attr('class'); className = "." + className + '-content'; $(className).toggle('slow'); }); {% endfor %} I would like a slow effect. That's why I put a 'slow' speed inside of the toggle() Jquery function, but it is not considered. Would you have an idea of what I'm doing wrong ? Thanks a lot ! -
Django thinks I have an id field when I do not
I have created the following model: class World(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) setting = models.CharField(max_length=200) creation_date = models.DateTimeField('date created') when I run manage.py makemigrations I get the following error: You are trying to add a non-nullable field 'id' to world without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Why does Django think I have an id field, and how do I get rid of this error? -
Django problem "super() argument 1 must be type, not WSGIRequest" in Python 3
While to use class inheritance, Python 3 fails with "super() argument 1 must be type, not WSGIRequest". I'm on Django 2.1.4 and Python 3.7.0. I am trying to see if a user already submitted an file to be analyzed, if not, he is directed to the submission page. I've tried to do not use static methods, check if it's really Python 3 (because this problem is common on Python 2), on the super class I tried to inherit from "object" while also inheriting from "View" provided by Django (because this solves in Python 2 super() argument 1 must be type, not None). This is the super class, it inherits from the class provided by Django "View". class DatasetRequired(View): @staticmethod def get(request): <redirects the user> This is the base class class Estatisticas(DatasetRequired): @staticmethod def get(request): super(request) <do various other stuff> I'm expecting that the base class' get function while called will call the super class get function and check if the user already submitted the file. I get: "TypeError at /estatisticas super() argument 1 must be type, not WSGIRequest" -
Django test client ingnores "include" terms in django template
I have an issue with Django tests client. Let for the home path I have this template (home.html): <html> <body> {% include 'example.html' %} </body> </html> and in example.html I have error: <div> {% non_registered_tag arg1 arg2 %} </div> I wrote a test for accessibility to a Django URL. class HomePageAccess(TestCase): def test_home_page(self): client = Client() response = client.get(reverse_lazy('home')) self.assertEqual(response.status_code, 200) This code fails successfully if there be an error in home.html, But if there be an error in example.html which is included in home.html Test will pass even though we expect to fail because I included it in home.html and in the browser I encounter an error (status code 500) while this not happens in test client. Is it normal? I'm using Django 2.0.2. Any help will be appreciated -
Create a python function to return a session token and pass token to celery task (django)
I need to create a session token and use this token in a request to get data from the matchbook betting exchange api. The shared task below is on a celerybeat task running every two seconds getting pricing for events. This is the function I have below to get the pricing. The problem is if I login every time with mb.login() before I run the task I will get my ip blocked due to too many logins I need to create a session token and call it like mb.get_session_token.get_events I am using a prebuilt wrapper that's on github to interface with matchbook api. https://github.com/rozzac90/matchbook There is no documentation but there is some info in the docstrings that I'm having trouble understanding but I think there's a function for creating session tokens but I'm not sure how to use them. I would like to know how I can make a function that returns a session token and pass it to my function below. Also there's a keep alive function that is used to keep refreshing your connection. I'm not sure how it works but I think you need to ping that function every 6 hours. My function from matchbook.apiclient import APIClient … -
Dockerfile django && mysql
I'm triying to create a docker environment for my django project my dockerfile : FROM python:3 ENV PYTHONUNBUFFERED=1 RUN apt-get install default-libmysqlclient-dev RUN mkdir /config ADD /config/requirements.txt /config/ RUN pip install -r /config/requirements.txt RUN mkdir /src WORKDIR /src my docker-compose : version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_USER: root MYSQL_PASSWORD: root MYSQL_DATABASE: ProjetDjango container_name: mysql01 restart: always nginx: image: nginx:1.13-alpine container_name: nginx01 ports: - "8000:8000" volumes: - ./project:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: django01 command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py collectstatic --noinput && gunicorn hello_django.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./project:/src expose: - "8000" restart: always my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ProjetDjango', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } I've got this error while running : docker-compose up django.db.utils.OperationalError: (2006, 'Can\'t connect to MySQL server on \'127.0.0.1\' (111 "Connection refused")') django01 exited with code 1 I've been working on this issue for 2 days now and didn't find a response that solve it! Thank you for your help -
How can I auto post my blog on Facebook Page and Twitter handle
I have created a blog using django. Now I want that whenever I create a new blogpost and publish it, The link of the same get posted on my facebook page and twitter handle. I have already implemented the social share on my website using which users can tweet or share my post on there respective facebook or twitter TLs. Now I am looking for something which can auto-post on publishing a blog post. -
can not login to my site using user model in django
I created user model using BaseUserManager and AbstractBaseUser. admin can be craeted and login successfully. but when i add a non-admin user i cant use it to login my site. so, superuser can login. others are created successfully but can not login. i do not know where is the problem. that is the code(models.py): from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser from django.db import models class MyUserManager(BaseUserManager): def create_user(self, email, name = "anynomous", password=None ): if not email: raise ValueError('enter your email') user = self.model( email=MyUserManager.normalize_email(email), name = name, ) user = self.create_user(email, password=password, name= name, ) user.set_password(password) user.is_superuser = False user.is_admin = False user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True, db_index=True , null=False , blank=False) name = models.CharField(max_length=50 , null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def create_user(self, email, name = "anynomous", password=None ): if not email: raise ValueError('enter your email') user = self.model( email=MyUserManager.normalize_email(email), name = name, ) user.set_password(password) user.is_superuser = False user.save(using=self._db) return user def get_full_name(self): return self.name def __unicode__(self): return self.email def has_perm(self, perm, obj=None): return True def … -
How To Perform Object Level Validation Django Rest Framework?
Hey Developer I have a Serializer.py like This class ExamTermSerializer(serializers.Serializer): name = serializers.CharField() start_date = serializers.DateField() end_date = serializers.DateField() course = serializers.IntegerField() _class = serializers.IntegerField() def validate(self,data): if data['start_date'] > data['end_date']: raise serializers.ValidationError("Start Date Should be smaller") return data And I Views.py like This: ###Bunch of code.. _exm,c = ExamTerm.objects.get_or_create(name = data['name'], defaults = { 'start_date':data['start_date'], 'end_date':data['end_date'], 'course_id':data['course'], '_class_id':data['_class'] }) if not c: raise serializers.ValidationError({ "Detail":['Exam With This name Already Exist'] }) return Response(data , status=status.HTTP_201_CREATED) When I search About Object Level Validation In DRF i foud this validate Function That i have written in serializer(i.e validate) My Actual Problem in How To implement this Validate Function From views So that the start_date will be always Smaller tha end_date Sorry For Question If It is a silly question . I face with This Problem because im new in DJANGO REST API. Thank You -
Images don't appear - django ckeditor
I upload image in ckeditor but it didn't appear 'cause path to image is http://127.0.0.1:8000/blog/post/hello-23-1547897944/uploads/2019/01/19/southside.jpg But image is uploading to the folder: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'contact', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = 'uploads/' urls.py: urlpatterns = [ ... path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py: from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, blank=True, unique=True) body = RichTextUploadingField(blank=True, db_index=True) I think that problem is in settings.py Sorry, my English isn't well but i hope that u understand my question. -
NameError: name 'Video' is not defined
I have little problem, I tryed make video uploader but something go wrong models.py class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) Forms.py from django import forms class VideoForm(forms.ModelForm): class Meta: model=Video fields=["name", "videofile"] views.py from django.shortcuts import render from .models import Video from .forms import VideoForm def showvideo(request): lastvideo= Video.objects.last() videofile= lastvideo.videofile form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'Blog/videos.html', context) And yes I made migrations but he telling me that name 'Video' is not defined -
Update only specific objects
The problem in my code is when I make any updates for my objects especially the Geometry Model. My code will update every object in this Model with the same values. While I am tying is to update each row with its values instead of updating the model with the same values. I have tried several ways but the problem still occurs. def update(self, instance, validated_data): geo = address_data.get('geo') lat = geo.pop('lat') lng = geo.pop('lng') ... gathers = geometry.objects.update(lat=lat, lng=lng) address = Address.objects.update(address=address, country=country, description=description, geo=gathers ) ... user_data = validated_data.pop('user') username = user_data.pop('username') user = User.objects.update(username=username) gather = userProfile.objects.update(address=address, user=user) return instance. class geometry(models.Model): lat = models.IntegerField(default='') lng = models.IntegerField(default='') class Address(models.Model): ... geo = models.OneToOneField(geometry, on_delete=models.CASCADE, default='') class userProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, name='user', primary_key=True) address = models.OneToOneField(Address, on_delete=models.CASCADE, name='address') The problem is my code updating the whole rows in the model with the same values. { "address": { "id": 1, "address": "2,lot chragua", "country": "Morocco", "description": "dfvfdv", "geo": { "id": 1, "lat": 471, "lng": 39 } }, "user": { "id": 1, "username": "sdfvedfbf", "first_name": "", "last_name": "", "email": "", "date_joined": "2019-01-19T11:31:00.415990Z", "last_login": null } }, { "address": { "id": 2, "address": "2.Lot Chraga", "country": "Morocco", "description": "sfvsfv", … -
django TypeError: quote_from_bytes() expected bytes with json
first time asking here, after looking everywhere, still stuck trying to implement tranzila payment gataway with django, mostly easy stock to sending product shopping cart what do I mean? my site gives me a shopping cart, client can purchase a few different products together, I and want to send this data to tranzila tranzila recieves it as a rawurlencoded json after I do the encoding, I get TypeError: quote_from_bytes() expected bytes my code: def cart_detail(request, total=0, counter=0, cart_items=None): json_purchase_data = None cart_data = [] try: # get session key cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: # calculate total total += (cart_item.product.price * cart_item.quantity) # Item counter counter += cart_item.quantity # cart items for tranzila json_purchase = json.dumps([{"product_name": str(cart_item.product), "product_quantity": int(cart_item.quantity), "product_price": int(cart_item.product.price) }]) cart_data.append(json_purchase) print(cart_data) except ObjectDoesNotExist: pass # tranzila Code thtk = create_thtk(total).split("=")[1] dc_disable = create_dc_disable() json_purchase_data = quote(cart_data) if request.method == 'POST': form = UserData(request.POST) else: form = UserData() context = { 'cart_items': cart_items, 'total': total, 'counter': counter, 'terminal_name': terminal_name, 'thtk': thtk, 'dc_disable': dc_disable, 'form': form, 'json_purchase_data': json_purchase_data } return render(request, 'cart/cart.html', context) I need help, any kind of help will be much appreciated -
What are the keys contained in request.POST.has_key(*...*)?
I was going through source code of one of the django applications in my organisation. I can see response_add method overridden in admin.py as below : def response_change(self, request, obj): if '_upload' in request.POST: url = reverse('admin:%s_%s_change' % ( self.model._meta.app_label, self.model._meta.model_name), args=[obj.pk], current_app=self.admin_site.name) return HttpResponseRedirect(url) else: return super(DfInpAdmin, self).response_change(request, obj) I cant find anywhere on internet what is _upload here. ? Instead I see many code snippets with if request.POST.has_key("_popup"):. What are these _upload, _popup, _continue ? Are they django provided or custom defined in some other .py of my source code? -
Define Filter on django-datatable-view
I am using django-datatable-view to show my data. I have a scenario that I need to retrieve records from a model, that satisfy certain conditions. For example, the request could be described as: "SELECT * FROM model WHERE column_1='value_1' AND column_2='value_2' How could I implement this? Actually, I saw the examples, but I don't have an efficient idea to do this. Would you please help me in View definition or refer to proper sample? -
Getting a TemplateSyntaxError in my Django app
I tried creating a delete button and basically what it should do is "delete an object when clicked" given its id but my app keeps giving a TemplateSyntaxError at / Could not parse the remainder: '{{doc.id}}' from '{{doc.id}}'. Here's the code for said functionality in my View, Template and Urls.py files respectively #Views.py def delete_feed(request, pk): query = Feed.objects.get(id=pk) query.delete() return HttpResponse("Deleted!") #Template <a href="{% url 'delete_feed' pk={{doc.id}} %}"><button type="button" class="btn btn-danger">Delete Item</button></a> #urls.py url(r'^delete_feed/(?P<pk>\d+)/$', delete_feed, name='delete_feed'), -
Python ; Django : AttributeError: 'NoneType' object has no attribute 'group'
Having Issues:- AttributeError: 'NoneType' object has no attribute 'group'; But I'm providing the slug as a symbol and then why is the problem generated. How To Resolve This type of issues? Just focus on Symbol Parameter and x in the code it will definitely lead you to the priorities. for NSETools file: https://github.com/Arkoprabho/NSEToolsPy/blob/master/nsetools/nse.py Code Below : @csrf_exempt def quote_data(request, symbol): symbol = str(symbol) print(symbol) x = nse.get_quote(symbol) changeQuote = float(x['change']) cName = (x['companyName']) print(cName) cURL = "https://newsapi.org/v2/everything?q="+ cName +"&apiKey=2c9f31acb8cc466bbf2647cf4170b81d" quoteNewsSet = (requests.get(cURL)).json print(quoteNewsSet) import quandl as qd import pandas as pd import datetime dt_now = datetime.datetime.today().strftime('%Y-%m-%d') qdauth = 'JvPxndekpt7dVpVZnwLR' equity = 'NSE/' + symbol ##### start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') print(start_date) if start_date and end_date: df = qd.get(equity,start_date=start_date, end_date=end_date, authtoken = qdauth) else: df = qd.get(equity,start_date="2018-01-01", end_date=dt_now, authtoken = qdauth) df = df.reset_index() df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d').dt.strftime("%Y-%m-%d") dfOpen = df[['Date','Open']] dfClose = df[['Date','Close']] dfHigh = df[['Date','High']] dfLow = df[['Date','Low']] dfOC = df[['Date','Open', 'Close']] dfHL = df[['Date','High', 'Low']] contextOpen = dfOpen.to_json(orient='records') contextClose = dfClose.to_json(orient='records') contextHigh = dfHigh.to_json(orient='records') contextLow = dfLow.to_json(orient='records') contextOC = dfOC.to_json(orient='records') contextHL = dfHL.to_json(orient='records') r = requests.get("https://nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxPeerCompanies.jsp?symbol=CHENNPETRO") data = r.text data = data.replace('\r', '') data = data.replace('\n', '') data = data.replace('industry', '"industry"', 1) data = data.replace('data', '"data"', 1) … -
TypeError: 'Library' object is not callable
I have the following project structure: kjp_app/ templatetags/ __init__.py myfilters.py In myfilters.py I have this code: from django import template register = template.Library() @register(name='rep_slash') def rep_slash(value): if '' in value: return value.replace('','/') In the corresponding html file I loaded myfilters and used rep_slash as below, {% extends 'kjp_app/base.html' %} {% load myfilters %} {% block body_block %} {% if client_rec %} <table> {% for rec in client_rec %} <tr> <td>{{ rec.client_name }}</td> <td>{{ rec.client_designation|rep_slash }}</td> <td>{{ rec.client_job_location }}</td> <td>{{ rec.client_phone_num }}</td> </tr> {% endfor%} </table> {% endif %} {% endblock %} I am getting the following error when running the server: File "D:\Django_projects\Pradeep Website\kjp_enterprise\kjp_app\templatetags\myfilters.py", line 5, in <module> @register(name='rep_slash') TypeError: 'Library' object is not callable [19/Jan/2019 14:57:45] "GET /kjp_app/view_clients HTTP/1.1" 500 151123 I am using Django 2.1.5 and python3.7 -
using google send mail from oauth in django
I have been trying for some time to integrate sendmail from google into my Django project in addition to the login with google, so that user to user emails are possible. As a basis I had tried to use the documentation of google. But unfortunately it is no longer up to date. https://developers.google.com/api-client-library/python/guide/django i have adjusted models.py a little bit accordingly from oauth2client.contrib.django_util.models import CredentialsField class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True) credential = CredentialsField() for testing I used this sendmail script based on https://developers.google.com/gmail/api/quickstart/python import httplib2 import os import oauth2client from oauth2client import client, tools, file import base64 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from apiclient import errors, discovery SCOPES = 'https://www.googleapis.com/auth/gmail.send' CLIENT_SECRET_FILE = 'API_credentials.json' APPLICATION_NAME = 'Gmail API Python Send Email' def get_credentials(): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'client_secret.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store) print('Storing credentials to ' + credential_path) return credentials def SendMessage(sender, to, subject, msgHtml): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) message1 = CreateMessage(sender, to, subject, msgHtml) SendMessageInternal(service, "me", message1) def SendMessageInternal(service, user_id, message): … -
Can I have data from different fields of a model returned as separate HTML elements? (Django 2.1)
I am compiling a database of articles and have my model set up like this: class articles(models.Model): ArticleID = models.IntegerField(primary_key=True) Title = models.CharField(max_length=500) Author = models.CharField(max_length=200, null=True) Journal = models.CharField(max_length=500, null=True) Date = models.IntegerField(null=True) Issue = models.IntegerField(null=True) Link = models.URLField(max_length=800, null=True) Content = models.TextField() class Meta: db_table = 'TEST' def __str__(self): return f'{self.Title}, {self.Author}, {self.Journal},{self.Date}, {self.Issue}, {self.Content}' def get_absolute_url(self): return reverse('article-detail', args=[str(self.ArticleID)]) The idea is pretty simple. Each meta data type (i.e. title, author) is it's own field, and the actual content of the article is in the field Content. My view for this model: def article_detail(request, ArticleID): ArticleID = get_object_or_404(articles, ArticleID=ArticleID) context = {'ArticleID': ArticleID} return render(request, 'article_detail.html', context) The HTML template for the view: {% extends 'base.html' %} {% block content %} <div class="container"> {{ ArticleID }} </div> {% endblock %} The data displayed in on the HTML page is one big block of text in one single HTML element. How can I make it so that I can use CSS to target each individual field from the model? Must I make separate models for each field (and bound them with foreign keys)? -
How to put valid input in a ModelChoiceField widget that inherits TextInput widget
This form is updated by a generic view: models.py: class CustomUser(User): user_bio = models.TextField(blank=True, null=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.username class SafeTransaction(models.Model): trans_recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'trans_Recipient',null = True) trans_recipient_email = models.CharField(max_length = 1000, blank=True, null=True) trans_sender = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'safe_Transactions', null = True) date = models.DateTimeField(auto_now_add=True, blank=True) subject = models.CharField(max_length = 1000, blank = True) #trans_type = models.CharField(choices=(1,'Buildingwork'))#DROPDOWN BOX trans_unread = models.BooleanField(default = True) arbitrator_name = models.CharField(max_length=1000,blank=True, null=True) payment_condition = models.TextField(blank=True, null=True) amount_to_pay = models.DecimalField(blank=True, null=True, max_digits=50, decimal_places=2) is_finalised = models.BooleanField(default=False) views.py: class SafeTransUpdateView(UpdateView): ''' This view lets the user Update a SafeTransaction receipt ''' form_class = SafeTransactionForm model = SafeTransaction template_name = "myInbox/safeTrans_update.html" forms.py : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' #version one of trans recipient trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) #version two of trans_recipient #trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class':'special'})) def clean_trans_recipient(self): data = self.cleaned_data['trans_recipient'] try: return CustomUser.objects.get(username=data) except CustomUser.DoesNotExist: raise forms.ValidationError("No user with this username exists") class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'trans_recipient_email', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] So in the forms, I'm mainly trying to inherit a TextInput widget from a ChoiceField. Upon actually submiting the form with this version : trans_recipient = forms.ModelChoiceField(queryset=CustomUser.objects.all(), widget=forms.TextInput()) I am told that … -
Not Found url in django class based view with ajax
I have a problem with "like" functionality. I want to make it possible to like the post, without overloading the whole page. So I used CBV django connected to ajax. My problem is that it receives: Not Found: /like/ by pressing the "Like" button. My view: class PostLikeView(generic.View): def post(self, request): post = get_object_or_404(Post, id=request.POST.get('id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('post/like_section.html', context, request=request) return JsonResponse({'form': html}) Below is jquery code: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault; var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: "{% url 'post:post_like' %}", data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form'])) }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> url to view: url(r'^like/$', login_required(PostLikeView.as_view()), name='post_like'), code in html: <form action="{% url 'post:post_like' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> I would like the button to work on the principle of not reloading the whole page. -
Django: how to store a lot of data between requests if I don't have a database
I am writing an app that will visualize Strava (social site for athletes) user's activities in various ways. The user is required to authenticate with his Strava account, and then my app downloads his activity data from Strava API. As there will be no user accounts in my app - just the Strava authentication - I have decided to not use a database. Therefore, I would need to store the activity data in memory. The data would be quite big: for example, I have 800 activities on Strava, each being a longish JSON. Would storing the data in session like session['activities'] = some_downloaded_activities be suitable for this? I would then set up API endpoints that would query this session data, filter it as required by the front end of my application and return it. My other idea is to use a database only to store the JSON file, but delete the data immediately after the user session is done - but it seems like an overkill. Or is there a better approach?