Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Effect on lua scripts when redis is unable to save in background due to memory allocation issues
I recently added some Lua scripts to a Django application (for interfacing with a Redis backend). In production (although not in development), the set up ends up giving me the following error: Error running script (call to f_8c07b227bc796743f66bad8dbe75a5bf8fcc8cd6): @user_script:2: @user_script: 2: -MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error. While this happens, if I look at redis logs, I'm seeing can't save in background: fork: Cannot allocate memory. I get what's happening. My question is, howcome redis remains functional when memory can't be allocated for background saving, but lua scripts crash? Is there a way to avoid such a scenario? FYI, following is how my lua_scripts.py module is laid out: import redis from location import REDLOC2 #location of relevant unix socket my_server = redis.StrictRedis(unix_socket_path=REDLOC2) # Get recent lualatestlogins = """ local l = redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[1]-600, '+inf') -- returns key:value pairs local c = {} for _, v in pairs(l) do local p = v:find(':') local i = v:sub(1,p-1) c[#c+1] = i end return c""" getlatestlogins = my_server.register_script(lualatestlogins) # Evict old luacleanselogins = … -
Django RecursionError
When i runserver i have this error RecursionError at /cart/ maximum recursion depth exceede It seems to me that the fault lies somewhere in functions def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): # usunięcie koszyka del self.session[settings.CART_SESSION_ID] self.session.modified = True @property def delivery(self): if self.delivery_id: return Delivery.objects.get(id=self.delivery) return None def get_delivery(self): if self.delivery: return (self.delivery.cost / Decimal('100')) * self.get_total_price() def get_total_price_delivery(self): return self.get_total_price() - self.get_delivery() -
How to use django filter in jinja2 template (error: access requires 2 arguments, 1 provided )
I've just switch to jinja2 as template engine in my django project. In my templates/templatetags/my_filters.py I have a simple filter (works with django default template engine) @register.filter def access(dictionary, key): return dictionary.get(key) my_template.jinja2: <span>{{ myDict|access(5) }}</span> but i receive this error: access requires 2 arguments, 1 provided Here is how I originally called the filter (which worked): <span>{{ myDict|access:'5' }}</span> I've followed the steps in http://jinja.pocoo.org/docs/2.9/switching/#filter-arguments Also I've found http://jinja.pocoo.org/docs/2.9/api/#custom-filters Does it mean my django filter only works with jinja2 if I make that settings entry? (couldn't get it to work') 'OPTIONS': { 'environment': 'myproject.settings.jinja2.environment', 'filters': { 'access': os.path.join(BASE_DIR, '/templates/templatetags/my_filters/access') } } Any help would be much appreciated. -
Put a link in the footer Django Tables 2
I'm trying to add a footer to my table that is a link. I have found you add a footer like this: ID = tables.Column(footer=('')) but I'm not sure how to make what's in the quotes a link. Thanks! -
Can manage.py runserver execute npm scripts?
I am developing a web application with React for frontend and Django for backend. I use Webpack to watch for changes and bundle code for React apps. The problem is that I have to run two commands concurrently, one for React and the other one for Django: webpack --config webpack.config.js --watch ./manage.py runserver Is there any way to customize runserver command to execute the npm script, like npm run start:dev? When you use Node.js as a backend platform, you can do the similar job like npm run build:client && npm run start:server. -
how to validate the discount that I add with date range in Django
excuse me. I have a problem. I have the following model: class Discount(models.Model): code = models.CharField(max_length=10, unique=True) article = models.ManyToManyField(Article) place = models.ManyToManyField(InvoiceCategory) start = models.DateField() end = models.DateField() name = models.CharField(max_length=30) cut_price = models.PositiveIntegerField() def __str__(self): return self.name discount model relate ManyToMany place of the model and the model articles. before, I have a discount with the data of articles (A, B and C) and place (Store and Website) applicable discounts from Jan 1 2017 to February 1, 2017. next, I add a discount of data where the articles are A and C and Places at from a Web on 3 Jan, 2017 and ended on March 1, 2017. DISCOUNT -------- CODE | ARTICLES | PLACE | START DATE | END DATE ------------------------------------------------------------ 1 | A, B, C | WEB | JAN, 1 2017 | FEB, 1 2017 STORE ------------------------------------------------------------ 2 | A, C | WEB | JAN, 3 2017 | MARCH, 1 2017 --> HOW TO VALIDATE ? Rules: Each discount is not allowed to contain one or more articles and places the same on the other discount on the start date until the end date (which is where the discount still applies). The problem: how to validate … -
How can I approach data split across multiple databases?
I'm putting together a proposal for the development of a web application. The app is to be launched in multiple countries, and some of the client's partners and (allegedly; I'm no lawyer) some of the countries involved have rules about where personal data can be stored. The upshot is that there is a hard requirement that particular data about certain countries' users is stored on servers in that country. (It sounds like they're OK with me caching data in any country, though -- so I intend to have a Redis in-memory store in the main data centre.) Some of the data (credit card details, for example) will additionally be encrypted, but this seems to make no difference to them in terms of where it can be stored. With the current set of requirements, users from one country won't actually ever interact with users from another country, so one obvious option is to run different instances of the application in each country, entirely self-contained. This is simpler from an architectural point of view, but harder to manage, and would have overall higher server costs. It might get complicated if for example the client wants reports on all users across all countries, … -
Django - 3js - Adding a separate javascript library to the project
I am attempting to add the latest 3js library that I downloaded to my project. Here is what I am doing in my html file and here is the error FileName: test.html {% load staticfiles %} <script src="{% static "modelling/js/three.js/src/Three.js" %}"></script> .... ... // Set up renderer, scene and camera renderer = new THREE.CanvasRenderer(); -//---ERROR : Uncaught ReferenceError: THREE is not defined container.appendChild( renderer.domElement ); Now this is in the Three.js File referenced above. Also for some reason Pycharm is giving me the error "Export declaration is no longer supported by the current Javascript Version" . Could that be the cause of problems ? import './polyfills.js'; export { WebGLRenderTargetCube } from './renderers/WebGLRenderTargetCube.js'; export { WebGLRenderTarget } from './renderers/WebGLRenderTarget.js'; export { WebGLRenderer } from './renderers/WebGLRenderer.js'; // export { WebGL2Renderer } from './renderers/WebGL2Renderer.js'; export { ShaderLib } from './renderers/shaders/ShaderLib.js'; export { UniformsLib } from './renderers/shaders/UniformsLib.js'; export { UniformsUtils } from './renderers/shaders/UniformsUtils.js'; export { ShaderChunk } from './renderers/shaders/ShaderChunk.js'; export { FogExp2 } from './scenes/FogExp2.js'; export { Fog } from './scenes/Fog.js'; export { Scene } from './scenes/Scene.js'; ...... ...... ...... -
Prefetching One-to-Many Relationship django ORM
I am working on an API function right now that would return a list of a users friends as well as all of the references for that users photos. (Although I only need the reference sorted by ord) Below are my models with the foreign keys. class Personimage(models.Model): photo_uuid = models.CharField(db_column='photoUUID', max_length=100, blank=True, primary_key=True, default='') user_id = models.ForeignKey('Member', db_column='userID', on_delete=models.CASCADE, blank=True, null=True) ord = models.IntegerField(db_column='ord', blank=True, null=True) reference = models.CharField(db_column='reference', max_length=200, blank=True, null=True) class Member(AbstractBaseUser): user_id = models.CharField(db_column='userID') class Friends(models.Model): id = models.IntegerField(db_column='id', primary_key=True, blank=False, null=False) puser = models.ForeignKey('Member', on_delete=models.CASCADE, db_column='puser') suser = models.ForeignKey('Member', on_delete=models.CASCADE, db_column='suser', related_name='secondary_friend') So far I was able to do this : friends = Friend.objects.filter(puser=cur_user).prefetch_related('suser') for r in friends: photos = Personimage.objects.filter(user_id=r.suser) united.append({'user_id': r.suser.user_id, 'name': r.suser.name, 'photos': [photo.reference for photo in photos.filter(user_id=r.suser)]}) but as you can image that is incredibly slow as it has to make a call to the Personimage table for each user in the friends list. I know there is a way to do this using prefetch_related or some combination of it and something else but I cannot find how to do it anywhere online or in my experimentation. The closest I got was return just one photo for each of the members … -
Django migration default value callable generates identical entry
I am adding a new field to an existing db table. it is to be auto-generated with strings. Here is my code: from django.utils.crypto import get_random_string ... Model: verification_token = models.CharField(max_length=60, null=False, blank=False, default=get_random_string) I generate my migration file with ./manage.py makemigrations and a file is generated. I verify the new file has default set to field=models.CharField(default=django.utils.crypto.get_random_string, max_length=60) so all seems fine. Proceed with ./manage.py migrate it goes with no error from terminal. However when i check my table i see all the token fields are filled with identical values. Is this something i am doing wrong? How can i fix this within migrations? -
Django Apache mod_wsgi - Unable to open database file
After upgrading mod_wsgi to the latest version, my app can no longer access its caching db (sqlite). The Apache error log shows the following: mod_wsgi (pid=1050): Target WSGI script '/location/to_my_project/project_name/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=1050): Exception occurred processing WSGI script '/location/to_my_project/project_name/wsgi.py'. aceback (most recent call last): File "/location/to_my_project/project_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/location/to/my/env/lib/python3.5/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "/location/to/my/env/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 153, in __init__ self.load_middleware() File "/location/to/my/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/location/to/my/env/lib/python3.5/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/location/to/my/env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/location/to_my_project/project_name/middleware/some_middleware.py", line 16, in <module> include_get_headers=True, File "/location/to/my/env/lib/python3.5/site-packages/requests_cache/core.py", line 182, in install_cache backend = backends.create_backend(backend, cache_name, backend_options) File "/location/to/my/env/lib/python3.5/site-packages/requests_cache/backends/__init__.py", line 50, in create_backend return registry[backend_name](cache_name, **options) File "/location/to/my/env/lib/python3.5/site-packages/requests_cache/backends/sqlite.py", line 28, in __init__ self.responses = DbPickleDict(location + extension, 'responses', fast_save=fast_save) File "/location/to/my/env/lib/python3.5/site-packages/requests_cache/backends/storage/dbdict.py", line 58, in __init__ with self.connection() as con: File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ return … -
Summing two char Case-expressions results in integer result
I have a Django 1.9 project in which I try to concatenate two Case expressions like this: .annotate(aggr_field= Case( When(my_field1__isnull = False, then = F('my_field1')), output_field = models.CharField()) + Case( When(my_field2__isnull = False, then = F('my_field2')), output_field = models.CharField())) In case of field1 = "Hello" and field2= "World", I get 0.0 instead of "Hello world". I tried to use ''.join([Case(...), Case(...)]), but Django says join accepts strings, not case-expressions. Is there any evident fix to this issue ? Or maybe cleaner way to achieve what I am trying to do here in alternative way without aggregation and case-expressions ? -
django objects.filter(x__in = y) where y is repetitive QuerySet
Customer.objects.filter(customer_id__in=contact_list_senders) contact_list_senders is a repetitive QuerySet that involves some customer_ids: {sender_id1, sender_id2, sender_id1, sender_id2, sender_id1} When I try to find the Customer objects from the contact_list_senders QuerySet with the above code Actual Output: {Customer1, Customer2} Desired Output {Customer1, Customer2, Customer1, Customer2, Customer1} I understand the actual output makes sense because there are only 2 Customer objects that matches with these contacts. Can you please help me to get the desired outcome? models.py: class Customer(models.Model): customer_id = models.CharField(max_length=244, blank=False, null=False) first_name = models.CharField(max_length=244, blank=True, null=True) last_name = models.CharField(max_length=244, blank=True, null=True) email = models.CharField(max_length=244, blank=False, null=False) enrollment_method = models.CharField(max_length=244, blank=True, null=False) account_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) reserved_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) modified = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) -
Refresh super'd model fields via views.py -- Django
I have a site which catalogs local hikes, and gives user points for each hike they go on based on how difficult that hike was. Here's what I'm looking to do: Grab each user For each user, grab all their hikes. Separate those hikes by difficulty. Apply some modifier (ie, give more points for more difficult hikes) Add all those together to get a point total Leaderboard to show who has the most points The best way that I've found to do it is to add a super'd field within the user's profile that details how many of each difficulty hike they've been on, then via views.py I can do the rest of the math/magic and come up with a leaderboard. I'm still early into working on this, but the following seems to be working for me: models.py: class Hike(model.Model) DIFFICULTY = ( (Difficulty choices here, in integer values) name = ... difficulty = models.IntegerField(choices=DIFFICULTY) class UserLog(models.Model) DIFFICULTY = ( (Difficulty choices here, in integer values) user = models.ForeignKey(User, on_delete=CASCADE) hike = models.ForeignKey(Hike, on_delete=CASCADE) personal_difficulty = models.IntegerField(choices=DIFFICULTY) class UserDetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) difficulty10hikes = models.IntegerField(editable=False) #repeat_for_all_other_difficulties def save(self): self.difficulty10hikes = UserLog.objects.filter(Q(user_id=self.user.id) & Q(personal_difficulty=10)).count() #repeat_for_all_other_difficulties super(UserDetails, self).save() So now I … -
How to populate hidden fields with data I got from another form in Django?
I have a very simple form, form1 [Rendered on template1] that takes in text for a required field. Clicking Submit on this form will lead to form2, [Rendered on template2]. On template2, I also display the data from the text field entered in form1. form2 has two fields, subject and body, along with a hidden field that is supposed to store the value of text field from form1. After clicking submit on form2, how do I now print out all data (acquired from both forms) on template3? This is what I have so far: Form1: class EmailForm(forms.Form): product_code = forms.CharField(required=True, max_length=100, label='Enter Product Code') Form2: class CustomersWhoBoughtForm(forms.Form): subject = forms.CharField(required=True, max_length=1000, label='Email Subject') body = forms.CharField(widget=forms.Textarea({'rows': 5}), required=True, label=mark_safe('<br>Body')) database_product_code = forms.CharField(required=False, widget=forms.HiddenInput()) Views.py def email_customers(request): if request.method == 'POST': if form.is_valid(): # raise Exception(request.POST.get('product_code')) - Executing this line successfully if request.POST.get('form_submit') == 'fetch_code': product_code = request.POST.get('product_code') form2 = CustomersWhoBoughtForm(initial={'databse_product_code': product_code}) return render(request, 'thanks.html', {'product_code': product_code, 'email_id': 'xyz@ecample.com', 'form2': form2}) if request.POST.get('form_submit') == 'send_email': form2 = CustomersWhoBoughtForm(request.POST) form2['database_product_code'] = form.cleaned_data['product_code'] if form2.is_valid(): database_product_code = request.POST.get('database_product_code') email_subject = request.POST.get('subject') email_body = request.POST.get('body') return render(request, 'email_sent.html', {'email_subject': email_subject, 'email_body': email_body, 'database_product_code': database_product_code, 'recipient': 'xyz@example.com'}) else: return render(request, 'thanks.html', {'form2': form}) else: form … -
Uploading pictures in Django fields and calling that file in HTML
My name is Luca and this is my first post, I've been working on a little project lately. I solve flight deals for people and would like to upload a screenshot for every deal I solve so that the client can see on his unique url the screenshot. What is the line of code that I have to insert so I can add a screenshot and what is the line I have to insert in my html that I have to insert so that it is linked to that file specifically? in my models I have from django.db import models import random def deal_get_code(): code = ''.join(random.choice('abcdef0123456789') for i in range(16)) while Deal.objects.filter(code=code).exists(): code = ''.join(random.choice('abcdef0123456789') for i in range(16)) return code class Deal(models.Model): code = models.CharField(primary_key=True, max_length=16, default=deal_get_code) #all my fields and their attributes ex: name = models.CharField(max_length=255) surname = models.CharField(max_length=255) #etc def __str__(self): return "{} - {}".format(self.code, self.name) And then in my HTML I have <div>Dear, your flight will depart on the: {{ deal.departure_date }} Your flight will return on the: {{ deal.return_date }} </div> etc etc.. I would like to be able to upload a file in Deal and see it in the html. It would be … -
Getting Started with Tastypie: no such table: myapp_entry
Just like the title of the page says, I'm Getting Started with Tastypie by following the linked tutorial. But when I try to load /api/entry/?format=json, I get HTTP 500 response, with this error message: no such table: myapp_entry When I look in sqlite3, indeed, there's no such table. Here's how I followed the tutorial: $ django-admin startproject mysite $ cd mysite $ django-admin startapp myapp I created/edited myapp/models.py, myapp/api.py and mysite/urls.py as specified in the tutorial, and added 'tastypie' to my INSTALLED_APPS in mysite/settings.py. Note: It wasn't clear to me which urls.py file to edit or create, so I edited the existing one in mysite. So now it looks like this: from django.conf.urls import url, include from myapp.api import EntryResource from django.contrib import admin entry_resource = EntryResource() urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^blog/', include('myapp.urls')), url(r'^api/', include(entry_resource.urls)), ] I commented out the 'blog' line, because it caused the error ImportError: No module named 'myapp.urls'. I think this is the step I'm stuffing up, but when I tried putting the tutorial code in myapp/urls.py instead, I got a 404 when I tried loading the page, and when I then tried adding url(r'^blog/', include('myapp.urls')) to mysite/urls.py, I got a stack overflow. So … -
Manipulating Django form to show the correct validation error(s)
In a Django form, I'm getting users to input their usernames. The field is like so: username = forms.RegexField(max_length=50,regex=re.compile('^[\w.@+-]+$'),\ error_messages={'invalid': _("(tip: only use alphabets, numbers or @ _ . + - symbols)")}) Later, in the clean_username method, I also need to ensure users didn't include a whtiespace in the username. I do that like so: def clean_username(self): username = self.cleaned_data['username'] if ' ' in username: raise ValidationError("(tip: a username can't have whitespaces)") return username The problem is that this validation error never appears, since whitespaces fail the prior regex check. I need to be able to show the whitespace related ValidationError separately. Moreover I also don't want to compromise on showing the relevant error if a user writes a regex failing username such as Bèndèr*. What's the best way to fix this issue? An illustrative example would be great. Thanks! -
Django and Python 3, If POST value equals not working
from datetime import datetime, timedelta from django.utils.dateparse import parse_date I'm trying to be able to either request database logs from either a set period of hours, or a custom time range. When sending through the custom time range, I use a value of 0 and convert it to an int to measure it: camera_id = request.GET.get('camera_id', None) range = request.GET.get('range', None) start = request.GET.get('start', None) end = request.GET.get('end', None) if int(range) <= 0: end_date = parse_date(start) start_date = parse_date(end) else: end_date = datetime.now() start_date = end_date - timedelta(hours=int(range)) data = [] camera_logs = CameraLog.objects.filter(camera_id=camera_id, created_at__range=(start_date, end_date)) But I'm not getting anything back from the database when choosing a custom date range. I get data back when requesting a standard hourly range (like 3), but I'm not even sure that my dates are being parsed properly. Is there a better way to do this? -
Facebook Login in Django Backend with big Frontend separation.
I'm trying to make a login with Facebook. What I want is to create and endpoint and use it as I use the "standard" email login endpoint, since I need a big separation between the backend and the frontend. I think it should be easy to do it, but I don't know how to do it. I read this and when I use the Url in the browser, it works properly and I get the token in the response Url. But, it happens always on the frontend side. I tried many tutorials this one is an example, and it works, but I'm the backend, I'm not allowed to have something like that, as the frontend is written in Django too. So, I don't know how should be the workflow when you're just the Backend, I don't know what the Frontend developers wait from me because the authentication happens actually on the frontend side. And I'm a little bit lost. Maybe someone had the same problem as Backend and could help me, at least tell me, how the workflow backend - frontend should be. -
How do you handle cross origin with Angular 2 + Django during development?
I'm using Angular CLI to run my SPA during development. It launches a dev server directly in memory with hot reload and all cool stuff. I'm using Django as my back-end and Django has its own development server. Naturally they respond from different ports and this seems to be a problem for browsers. How am I supposed to handle this? I can switch off CSRF in Django, but even then I have to start Chrome with some special flags that allows it to connect to my dev back-end. Firefox doesn't work at all. Security is a great thing, but I'd like to develop my application after all. I have no idea how I can test with Firefox without making a production build running on Apache together with the back-end. -
ClusterTaggableManager Not Saving Tags in Django Wagtail CMS
Not sure if I can use it this way, but I have a Price model that I am using ClusterTaggableManager for the name object. The Price model then has an Inline relationship to my Product model. The tag names are not being saved when I create a new product. Am I missing something or is it not possible to use ClusterTaggableManager in this way? PriceTag model class PriceTag(TaggedItemBase): content_object = ParentalKey('Price', related_name='tagged_items') class Price(ClusterableModel): menu = ClusterTaggableManager(through=PriceTag, blank=True) price = models.DecimalField( blank=True, null=True, max_digits=5, decimal_places=2, help_text='Numbers only with 2 digital decimal. I.e. 25.00' ) panels = [ MultiFieldPanel( [ FieldPanel('menu'), FieldPanel('price'), ], heading='Prices', classname='collapsible collapsed' ), ] Product model class ProductPrice(Orderable, Price): page = ParentalKey('Product', related_name='price') @register_snippet class Product(ClusterableModel): name = models.CharField(max_length=255, verbose_name='Menu Product Name') description = models.TextField(verbose_name='Description', blank=True) section = models.ForeignKey(Section) panels = [ MultiFieldPanel( [ FieldPanel('name'), FieldPanel('description'), FieldPanel('section') ], heading='Item Details', classname='collapsible' ), MultiFieldPanel( [ InlinePanel('price', label="Menu & Price"), ], heading='Menu & Pricing', classname='collapsible' ), ] class Meta: verbose_name = 'Create Menu Item' ordering = ('name',) def __str__(self): return self.name -
Python - Pulling Large (millions) of records from a postgremysql Database is timing out
I am writing a large number of records, probably 2 million records in a text file(zip). I would like to do that in chunks. I would to stream the data out of the database, rather than load it in all at once. That way I can write the data straight back out without having too much of it loaded into memory at once. I know how it streams by chunks, but I'm not sure how I should compress (zip) the file when a file is still generating. Here is what I have tried so far import math from django.db.models import Q from django.conf import settings import uuid with open(filename, 'w+') as file: oparray = [[0 for x in range(521)] for y in range(477)] file.write(BCH_HEADER) for sp in range(1, 209): local_result = local_BCH.filter(stress_period=sp) nonlocal_result = nonlocal_BCH.filter(stress_period=sp) if all(i == 0 for i in local_result) and all(i == 0 for i in nonlocal_result) and one: continue for r in local_result: oparray[r.m_row][r.m_col] = r.recharge for r in nonlocal_result: oparray[r.m_row][r.m_col] = r.recharge if all(i == 0 for i in oparray) and one: continue file.write(BCH_SUBHEADER) for x in range(1, 477): for y in range(1, 520, 10): file.write(' {:e} {:e} {:e} {:e} {:e} {:e} {:e} {:e} … -
Django Angular JS integration
I have a django working app in which I use a terminal command to display a database, this command is written in a function inside models.py In addition, I have an html template that uses angular.js to display 3 text boxes.(fields, ID, Date, Source) This all works, but what I want to do is to be able to use what the user inputs in these 3 text boxes as the the 3 variables to be used in the models.py, currently I have to write the whole command manually in models.py The problem is that I know how to borrow from models.py using angular.js but not the other way around. Any suggestions? Lev -
Trying to make a cart using django but in views I am passing product id rather than slug because I am adding product to cart directly from homepage
Cart App views.py from django.shortcuts import render, HttpResponseRedirect from django.core.urlresolvers import reverse # Create your views here. from products.models import Product from .models import Cart def view(request): cart = Cart.objects.all()[0] context = {"cart": cart} template = "cart/view.html" return render(request, template, context) def update_cart(request, id): cart = Cart.objects.all()[0] try: product = Product.objects.get(id=id) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) return HttpResponseRedirect(reverse("cart")) urls.py from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'products.views.home', name='home'), url(r'^products/$', 'products.views.home', name='products'), url(r'^$carts/products/$', 'carts.views.update_cart', name='update_cart'), url(r'^cart/$', 'carts.views.view', name='cart'), url(r'^admin/', include(admin.site.urls)), ) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) base.html <p><a href='{% url "update_cart" product.id %}' class="btn btn-primary" role="button">Add to cart</a> </p> According to me there is some fault in the urls.py Error NoReverseMatch at /products/ Reverse for 'update_cart' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$carts/products/$'] Request Method: GET Request URL: http://127.0.0.1:8000/products/ Django Version: 1.6.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_cart' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$carts/products/$'] Exception Location: /Users/apulgupta/Desktop/table1.2/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 452 Python Executable: /Users/apulgupta/Desktop/table1.2/bin/python Python …