Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: CSRF cookie not set. CSRF cookie does not exists
I have a Django application that serve with uwsgi and nginx. Sometimes when login, There isn't csrf cookie in browser cookie and does not renew when refresh browser. In login receive "CSRF cookie not set." error and after clean cookie this issue has solved. I used Django runserver for run app and i still have this issue. my setting is: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'app.middlewares.apply_all_requests.SetDefaultLanguage',] SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_AGE = 10 * 60 * 60 SESSION_SAVE_EVERY_REQUEST = True -
I want to add products to my cart and display the cart details..I am not able to understand why the code is not showing the details on the page?
class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True This is my cart.py file... {% load static %} {% block title %} Your Shopping Cart {% endblock %} {% block content %} <div class="container"> <div class="row" style="margin-top: 6%"> <h2>Your Shopping Cart <span class="badge pull-right"> {% with totail_items=cart|length %} {% if cart|length > 0 %} My Shopping Order: <a href="{% url "cart:cart_detail" %}" style="color: #ffffff"> {{ totail_items }} item {{ totail_items|pluralize }}, Kshs. {{ cart.get_total_price }} </a> {% else %} Your cart is empty. … -
Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I want to populate a chartJs exactly like the example: https://www.chartjs.org/docs/latest/charts/bar.html I obtain this error: AttributeError at /timesheet/json-month/ Got AttributeError when attempting to get a value for field `working_hour` on serializer `TimesheetSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'working_hour'. With this model: class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) date = models.DateField(default=datetime.datetime.now()) working_hour = models.FloatField(verbose_name = _("Working time")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.strptime("{}".format(self.date), "%Y-%m-%d").isocalendar()[1] super(Timesheet, self).save(*args, **kwargs) I serialize my data like that (into my view): def get_month_hours(self): cursor = connection.cursor() cursor.execute(""" SELECT MONTH(date), SUM(working_hour) FROM timesheet_timesheet WHERE owner_id = %s AND date >= MONTH(CURRENT_TIMESTAMP) - 12 GROUP BY MONTH(date) """, [self.user]) row = cursor.fetchone()[0] return str(row) @api_view(['GET']) def timesheet_total_per_month(request): hours = ReturnHour(request.user.pk, datetime.datetime.now().isocalendar()[1]) timesheets = hours.get_month_hours() serializer = TimesheetSerializer(timesheets, many=True, read_only = True) return Response(serializer.data) Into my serializers.py: class TimesheetSerializer(serializers.ModelSerializer): class Meta: model = Timesheet fields ='__all__' def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return … -
Setting Initial Field in Django
I have a model form and I am trying to pass an initial value to one of the fields when I call the form from the view. My view has the following: threadform = ThreadForm(text="hello") The model form is as below: class ThreadForm(ModelForm): class Meta: model = Thread fields = ['title'] def __init__ (self,*args, **kwargs): self.fields['title'].initial = kwargs.pop("text") super (ThreadForm, self).__init__(*args, **kwargs) This will give the error "ThreadForm" has no attribute 'fields'. If I reverse the super call then get "init() got an unexpected keyword argument 'text'". Please can someone help as I can't find any information on the correct way to do this as others seem to be setting a hard coded initial value, but mine is dynamic as I want to replace the literal "hello" with data from a model. -
Add GET parameter to the url name - Django
Currently I can pass a GET parameter from my html template like this. <a href="display-associations/players/?association={{ association.user.username }}">View Players</a> But can I do it through a url name parameter? I want something like following. <a href="{% url 'player-registration' %}">Add Player</a> I cannot figure out how to add GET parameter to the url-name. -
405 “Method POST is not allowed” in Django REST framework
I'm using Django REST framework to implement Get, Post api methods, and I got GET to work properly. However, when sending a post request, it's showing 405 error below. What am I missing here? 405 Method Not Allowed {"detail":"Method \"POST\" not allowed."} Sending this body via post method { "title": "abc" "artist": "abc" } I have api/urls.py from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path('api/(?P<version>(v1|v2))/', include('music.urls')) ] music/urls.py from django.urls import path from .views import ListSongsView urlpatterns = [ path('songs/', ListSongsView.as_view(), name="songs-all") ] music/views.py from rest_framework import generics from .models import Songs from .serializers import SongsSerializer class ListSongsView(generics.ListAPIView): """ Provides a get method handler. """ queryset = Songs.objects.all() serializer_class = SongsSerializer music/serializers.py from rest_framework import serializers from .models import Songs class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = ("title", "artist") models.py from django.db import models class Songs(models.Model): # song title title = models.CharField(max_length=255, null=False) # name of artist or group/band artist = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.artist) -
How to sent FCM token to django application
I have django web application and Android WebView application which simply open url of my web site. I would like to sent notification to users. I know that i need to use django-fcm. But there is problem how to sent FCM token from Android App to my django app and bind it to user. There is one idea to sent FCM token to server during user auth sent GET or POST request to server, then put it to the model like token and request.user. But i don't have any knowladge in Android development. Please if you have some ready examples provide it. -
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE
Help me fix error - django_celery/ - my_app/ - __init__.py - task.py - proj/ - __Init__.py - celery.py - settings.py - manage.py proj/init.py : from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) proj/celery.py : from __future__ import absolute_import,unicode_literals import os from celery import Celery from django.conf import settings from django_celery_beat.models import PeriodicTasks os.environ.setdefault('DJANGO_SETTINGS_MODULE','proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/settings.py : import os os.urandom(24) SECRET_KEY = os.urandom(24) BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'my_app.tasks.add', 'schedule': 10, 'args': (10,5) }, } INSTALLED_APPS = ( 'django_celery_beat', ) my_app/task.py from __future__ import absolute_import,unicode_literals from celery import shared_task,task @task def add(x, y): return x + y I am getting error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django testing - test the view which handles an ajax call
In testing Django, the view is returning 200 code but not sending any error message related. def ajax_view(request): msg = '' if request.is_ajax(): username = request.POST['username'] user = User.objects.get(username=username) msg = 'user exists' return HttpResponse(msg) In tests.py response = self.client.post(reverse('ajax_view'), data={'username': 'hello'}) self.assertEqual(200, response.status_code) self.assertContains(response, 'exist') It seems it is not going through the request.is_ajax().. How can I mock the ajax call in Django testing? -
Js or Django? Opinions please.
Seeking opinions. I just want to say that in no way am I over looking the amount of work that would need to be put in to even become decent in any of these disciplines, I'm trying to understand if my logic of this road map is technologically feasible and appropriate. Started down the road of learning python for ease of learning and wanted to tinker with ardiuno's, rasp pi's other IOT's. Also emerging fields python seems to be strong in, blockchain (smart contracts) A.I., machine learning and robotics all seem challenging but interesting. But being realistic I found it maybe a "faster" road if I learned web development to get a job as a dev while I increase my skills in those other area's mentioned. That's where I came across Django. Knowing my interests stated above I figure it be beneficial to learn HTML5/CSS and Django instead of JS to become that web developer since Django is a framework for python logic for websites. So because I've been learning Python, it seems to me, time wise, that Django would allow me to be a web developer while still being able to hone my python foundation for projects ahead as … -
Custom user model and table in django
I know that the django default table to store username and password is in auth_user table. I currently want to use my own table named SysUser, so I've created user model and user manager. Here is my code: model.py class MyUserManager(BaseUserManager): def create_user(self, username, name,role,accesslevel, passwd=None): if not login: raise ValueError('Users must have an username') user = self.model( username=username, name=name, role=role, accesslevel=accesslevel, ) user.set_password(passwd) user.save(using=self._db) return user def create_superuser(self, username, name,role,accesslevel, passwd): user = self.create_user( login, passwd=passwd, name=name, role=role, accesslevel=accesslevel, ) user.is_admin = True user.save(using=self._db) return user class SysUser(AbstractBaseUser): user_id = models.IntegerField(db_column='User_Id', primary_key=True) username = models.CharField(db_column='Username', max_length=50,unique=True) name = models.CharField(db_column='Name', max_length=100) passwd = models.CharField(db_column='Passwd', max_length=30, ) role = models.IntegerField(db_column='Role' ) accesslevel = models.IntegerField(db_column='AccessLevel') objects = MyUserManager() USERNAME_FIELD = 'username' class Meta: db_table = 'SysUser' As we can see, the attributes in my new table are different with the default table. But I get an error when I create a user and get all user. Here is my code to create user: >>> from test.models import SysUser >>> user = SysUser.objects.create_user(username='simon',name='Simon',role='1',accesslevel='1',passwd='simon123') Here is my code to get all user: user = SysUser.objects.all() print(user) Here is the error return: Traceback: File "C:\Python\Python36\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (column … -
HTML : Django Form validation and loading gif "onclick"
I have a django html form where I am taking a name and submitting it. The form works fine when input data is filled in. I want to add additional form validation before loading the gif. Please find below the code. The problem is when I add the form.valid() the gif is not loaded but validation works fine. I am trying add both form validation and gif loading at the same click event. I tried an if condition with form.valid() but that again is not loading the gif post validation. <script> function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } jQuery(function ($) { var threeMinutes = 60 * 3, display = document.querySelector('#time'); startTimer(threeMinutes, display); }); </script> <div class="row"> <p></p> <h5>Form</h5> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <div><span class="error-msg" id="Name"></span><div> <center><button type="submit" onclick="$('#loading').show();">Submit</button></center> </form> <div id="loading" style="display:none; text-align: center;">{% load … -
Django : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I don't know how to fix the error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty django-celery/ proj/ init.py celery.py settings.py/ init.py: from __future__ import absolute_import, unicode_literals import app as celery_app __all__ = ('celery_app',) celery.py: from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') 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)) settings.py: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_BEAT_SCHEDULE = { 'send-summary-every-hour': { 'task': 'summary', 'schedule': 3600.0, 'args': "HELLO" }, # Executes every Friday at 4pm 'send-notification-on-friday-afternoon': { 'task': 'my_app.tasks.send_notification', 'schedule': 10, }, } INSTALLED_APPS = ( 'django_celery_beat', ) I get error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How can I fix this. celery -A proj worker --loglevel=info -
Django: python manage.py createdb Library not loaded: libmysqlclient.20.dylib
I'm almost new with django. When I sent to the terminal on the django project with python manage.py createdb, I had an error. Traceback (most recent call last): File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 26, in <module> import MySQLdb as Database File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib Referenced from: /Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/{ItIsMyName}/.pyenv/versions/anaconda3-5.0.0/lib/python3.6/site-packages/django/db/models/base.py", … -
Django template tag, making my list empty or I'm not pass anything
Thanks for reading my post okay, I'm currently working on Django project that displays data in a dashboard; I manage to display and draw charts with Chart JS, great but now I need to limited number data in Django database to be displayed on charts and display the most recent data put into the database. I use Django built-in tag to display the most recently is "last" and limiting the display data, the tag is "length_is". Here are my HTML codes for using the "last" tag and index page <div class = "containor"> <div class = "float-right my-4 chartjs-render-monitor" id="chartContainerPH" style="width: 49%; height: 400px;display: inline-block; background-color:#FDFDFD;"> <center> <a class="title-link" href="{%url 'ph' %}">PH:</a> <p>{{tank_system.ph|last}}</p> </center> {%include 'FrounterWeb/includes/PHchart.html'%} </div> This is the result I get Last Tag result in my index Here' my code for chart HTML which I use the length_is tag {%block PHchart%} <canvas class = "my-4 chartjs-render-monitor" id="PHchart" ></canvas> <script> var ctx = document.getElementById("PHchart"); var PHchart = new Chart(ctx, { type: 'line', data: { labels: [ {%for tank_system in tank%} "{{tank_system.datetime}}", {%endfor%} ], //x-Axis datasets: [{ //y-Axis label: 'PH1', data: [ {%for tank_system in tank%} {{tank_system.PH|length_is:"3"}}, {%endfor%} ], backgroundColor: "rgb(249, 24, 24,0.2)", borderColor: "rgb(249, 24, 24,0.2)", fill: true, }] … -
LinkedIn OAuth2 redirect url is not working
With social-auth-app-django, I set up the settings as follows: INSTALLED_APPS = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ...] TEMPLATES = [{ ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', .... }] MIDDLEWARE_CLASSES = [ 'social_django.middleware.SocialAuthExceptionMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) And the callback/redirect url is https://localhost:8000/auth/linkedin/callback as the linkedIn dev says, but it is not working. What's wrong here? -
Bash script to create a scheduled task
I wrote a bash script to create a scheduled task and run a django app. I am using Git Bash as my terminal, and I have been able to manually run the commands in the snippet posted below with success. However, when I run bash script with these same commands, the scheduled task and the django app are never run. Why is there a discrepancy in behavior and how can I correct this in my bash script? #!/usr/bin/env bash // Create scheduled task echo schtasks //create //tn my-task //tr '"python app/manage.py loaddata /resources/output.json"' //sc daily //st 09:30 //ri 60 //et 16:00 // Run app echo python app/manage.py runserver echo "TERMINATED" $SHELL -
Make Django query result as a linked list
I have a Django model which has 4 fields including id, from_id, name, project_id. It presents a transaction record about this project. For example: id from_id name project_id 1 null A 1 2 1 B 1 3 null B 2 4 2 C 1 5 3 A 2 So how can I get a linked list likes A->B->C for project 1 or B->A for project 2? (A->B->C and C->B->A are both great, I just want to get the transaction by query) -
Django: how to change label for a form dynamically
is it possible to change the labels of a formset dynamically depending on a variable? Here is my views.py : def ctest(request): c_test_tokens, gaps, tokenindexe = generate_c_test(beispieltext()) # Here I want to give CTestform another variable which includes a list # gaps is an Integer ctestformset = formset_factory(CTestform, extra=len(gaps)) return render(request, 'ctest.html', {'form': ctestformset}) while creating the formset I want to give it another variable with which I can specify the names of the labels of each form. Is this possible and how do I do it or should I search for an alternative? Here is my forms.py: class CTestform(forms.Form): hello = forms.CharField(widget=forms.TextInput(attrs={'size': '5'}), required=False, label='hallo', label_suffix='') -
Django QuerySets, Annotate Sum of Filtered Related Objects field without returning NoneType
Is there a way to perform annotation sum on filtered related model fields without returning None when all the related results have been filtered out? For example, with the models below, I would like to have the yearly and monthly donation sums but excluding donations that were not successful or were refunded. I started using Case/When to avoid the problem of receiving None rather than 0 for users with no donations. But I still need to excluded unsuccessful and refunded donations. Reading Django's docs, I found you can set a custom _base_manager, but then it says "Base managers aren’t used when querying on related models". Is there another approach I could take? models.py class Profile(Model): user = OneToOneField( User, on_delete=CASCADE, related_name='profile' ) has_donor_access = BooleanField( default=False ) ... objects = Manager() account_objects = AccountManager() def __str__(self): return "{0} :: {1}".format( self.user.get_full_name(), self.user.get_username()) class Donation(Model): user = ForeignKey( User, blank=True, null=True, on_delete=SET_NULL, related_name='donations', verbose_name=_('donor') ) creation_date = DateTimeField( auto_now_add=True ) amount = DecimalField( decimal_places=2, max_digits=9 ) is_success = NullBooleanField( default=True ) is_refunded = NullBooleanField( default=False ) ... def __str__(self): user_profile = self.user.profile if self.user else "Anonymous" return "{0} :: ${1} :: {2}".format( user_profile, self.amount, self.creation_date) managers.py class AccountQuerySet(QuerySet): def with_donation_stats(self): a_month_ago … -
Paginator object has no attribute 'get_page'
I am trying to use paginator for the first time on my django project. I am having problems getting it to work. When i run it I get the error AttributeError: 'Paginator' object has no attribute 'get_page'. I have played around with it but cannot seem to resolve it. Can somebody help me please? The error seems to be o the line " babysitters = paginator.get_page(page) " View.py File from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Babysitter, Education, Reference, Work from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .choices import numbers_choices, minder_choices, county_choices # Create your views here. def all_babysitters(request): babysitters = Babysitter.objects.all() paginator = Paginator(babysitters, 3) page = request.GET.get('page') babysitters = paginator.get_page(page) return render(request, "babysitters.html", {"babysitters": babysitters}) -
Django Rest Framework - POST request invokes GET request (localhost)
When I try to access http://localhost:8000/api/articles/ it works fine. When I try to access http://localhost:8000/api/articles/1 it works fine. When I try to access http://localhost:8000/api/articles/create Django thinks that I am trying to perform a GET request ('get': 'retrieve'). What am I doing wrong? errors invalid literal for int() with base 10: 'create' urls.py app_name = 'articles' urlpatterns = [ path('', ArticleViewSet.as_view({'get': 'list'}), name='list'), path('<pk>/', ArticleViewSet.as_view({'get': 'retrieve'}), name='detail'), path('create/', ArticleViewSet.as_view({'post': 'create'}) ,name='create'), views.py class ArticleViewSet(ViewSet): queryset = Article.objects.all() def list(self, request): articles = query_filter(request, ArticleViewSet.queryset) serializer = ArticleSerializer(articles, many=True) articles = formatter(serializer.data) return Response(articles) def retrieve(self, request, pk=None): article = get_object_or_404(ArticleViewSet.queryset, pk=pk) serializer = ArticleSerializer(article, many=False) article = formatter([serializer.data]) return Response(article) def create(self, request): articles = ArticleViewSet.queryset articles.create(title=request.data['title'], body=request.data['body']) article = articles.last() serializer = ArticleSerializer(article, many=False) article = formatter([serializer.data]) return Response(article) -
Inline block not being applied
Im kinda new to HTML/CSS and im trying to align images side by side. I'm trying to use inline block but it's not being applied. Could someone please point out where i am going wrong. Parent class; <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="/static/Css/Parent.css"> <meta charset="utf-8"> </head> <body> <div class="AllCardViews"> {% block Movies/Shows %}{% endblock Movies/Shows %} </div> </body> </html> Child Class; {% extends "Movies/Parent.html" %} {% block Movies/Shows %} {% for Movie in Movies %} <div class="CardView"> <img src= '{{ Movie.Image }}' align = "middle" alt=""> </div> {% endfor %} {% endblock Movies/Shows %} Corresponding Css; .AllCardViews { width: 170px; text-align: center; max-width: 80%; margin: 5px 20px; margin-left: 300px; margin-right: 300px; margin-top: 300px } .AllCardViews .CardView img { display: inline-block; } Above you can see that i'm trying to specify where i want to use inline block as im selecting both classes yet it doesn't seem to work. -
Making list of model into field of another model in django
I am totally newbie in django and I am trying to make a restaurant app. I have two models: component and meal, and i want to make a field in meal model that contains a list of components models. Is there any way to do such a thing ? For example sandwich contains bread, cheese and ham. Thanks for your help -
Uploading Json to django model database results in Key Error
I have a custom manage.py command which I am using to upload a json file (a list of dictionaries) to my model. It appears to upload two records fine, but then throws a key error: KeyError: 'headline' My code is as follows: class Command(BaseCommand): def handle(self,*args,**options): filename = '/DoJ_Data_01-12-18.json' newpath = str(Path(home))+filename with open(newpath) as json_file: data = json.load(json_file) for d in data: q = doj(headline=d['headline'],topics=d['topics'],text=d['text'],url=d['url'],date=d['date']) q.save() As far as I can tell the json is valid. What am I missing?