Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify TastyPie resource queryset with information in filters
I have a situation where I want to modify a Resource's queryset based on the filters that are being passed in. I want this because certain filters require expensive operations to be added to the queryset, and I want to only do them if the user requests the filter in question. The documentation (HERE) shows you how to modify the queryset using get_object_list (which has access to the request). I want to do something like: class MyResource(ModelResource): def get_object_list(self, request): current_qs = super(MyResource, self).get_object_list(request) current_filters = SOMEHOW_GET_FILTERS(request) if 'name' in current_filters: current_qs = current_qs.annotate(best_friend=RawSQL("COMPLICATED SQL QUERY")) return current_qs Any thoughts? If I could do a build_filters from get_object_list without interrupting the rest of the request/response cycle, that might solve my problem. Any direction is appreciated. -
Transfering data to REST API without a database django
Basically I have a program which scraps some data from a website, I need to either print it out to a django template or to REST API without using a database. How do I do this without a database? -
Call setting.py variable while Celery task running
I have a Django app, and need to add a Celery async tasks. I would like to call in the tasks a settings variable from dev.py for example MY_VARIABLE='test'. To simplified the example lets assume that there is my task: from django.conf import settings @shared_task def test_task(): return settings.MY_VARIABLE While runing Celery worker via export DJANGO_SETTINGS_MODULE=proj.settings.dev celery -A proj worker -l info in the caller I run res = test_task.delay(*args) In the response in celery terminal I'm receiving AttributeError. 'Settings' object has no attribute 'MY_VARIABLE' How properly can I call settings variable to the async task? Thanks in advance! -
Mysql Error 1062 Duplicate entry
I am inserting data in the table workflow_summary using Django command. Code - def update_workflow(self,total_count,insert_count,update_count,error_count): curr_date = datetime.datetime.now() try: summary = Summary() summary.summary_date = curr_date summary.datasource = "CACMDB" summary.workflow = "contacts workflow" summary.total_record_count = total_count summary.valid_record_inserted_count = insert_count summary.valid_record_updated_count = update_count summary.error_records_count = error_count summary.save() except Exception as e: logging.error("Exception while Insert data in workflow_summary table. Error is " + str(e)) return Error Message - ERROR:root:Exception while Insert data in workflow_summary table. Error is (1062, "Duplicate entry '2017-08-04 11:20:20-contacts workflow' for key 'echo_workflow_summary_summary_date_930e5790634445f_uniq'") Table Structure - -
Override file behavior in flask
I want to push files to a storage service with the save method of the FileStorage object. But I couldn't find a way like it could be done in django. Is there an elegant way to do it? -
Django RetrieveUpdateAPIView not updating
I'm using django rest framework. I have two models (Model1 and Model2). Each of them has: 2 serializers (Model1CreateSerializer, Model1DetailSerializer, Model2CreateSerializer, Model2DetailSerializer). All the serializers extend ModelSerializer. 2 views (Model1CreateView Model1DetailView, Model2CreateView, Model2DetailView). All the "...CreateView" extend CreateAPIView and all the "...DetailView" extend RetrieveUpdateAPIView They are very similar. The first one is working properly: I can create an istance of Model1 using the Model1CreateView and I can see (GET) and patch that istance using the Model1DetailView. The second one is not working: I can create an istance of Model1 using the Model2CreateView and I can see (GET) that istance using the Model2DetailView. However I can't manage to update the istance. No error messages and no update is applied. I have tried everything. I wrote a new Model, Serializers, Views and table in the database from scratch and it is still not working. I even reduced the fields and just kept a single Charfield Field in Model2 just to see if a field was the cause of the problem. Model1 class Model1(models.Model): Field1 = models.CharField(max_length=255) Field2 = models.CharField(unique=True, max_length=10, blank=True, null=True) Field3 = models.SmallIntegerField() description = models.CharField(max_length=3000, blank=True, null=True) Field4 = models.SmallIntegerField() Field5 = models.ForeignKey('Foreignkey1', models.DO_NOTHING, db_column='Column1') class Meta: managed = … -
My html file won't recognize Jinga syntax
I'm working on a Django project. The problem is, the Jinga syntax isn't being recognized. What am I missing? I can't find anything to install via Terminal to rectify this. Here's home.html: {% extends "personal/header.html" %} {% block content % } <p>Hey, welcome to my website</p> {% endblock % } Here's header.html: <!DOCTYPE html> <html lang="en"> <head> <title>My Website</title> <meta charset="UTF-8"> </head> <body class="body" style="background-color: #f6f6f6"> <div> {% block content % } {% endblock % } </div> </body> </html> -
Is it possible to make such a request in django?
name | date | price ---------------------------- product1 | 01.02.2017 | 100 product1 | 03.02.2017 | 200* product1 | 07.02.2017 | 300* product2 | 02.02.2017 | 300 product2 | 04.02.2017 | 200* product2 | 08.02.2017 | 200* Count the number of products whose price has changed over the two dates. In example, answer: 1., becose only produc1 (200=>300), product2(200=200). -
dependent dropdownlist with json and python
So i am making a dialog panel for my chat bot in django framework.The Dialog panel consists of one intent dropdownlist,one entities dropdown list and a dialog textarea.The dropdownlist will be dependent on my training data which is in json format. I want the dropdownlist so that if i choose intent the entities dropdownlist create itself automatically and show all the entities related to selected intent.I have tried and i am able to show intent dropdown and that too had duplicate intents(which i removed using python set function).But i am unable to figure out how to show all entities based on one particular intent. Help me. Here's my example json: {"rasa_nlu_data": { "common_examples": [ { "text": "hey", "intent": "greet", "entities": [] }, { "text": "howdy", "intent": "greet", "entities": [] }, { "text": "hey there", "intent": "greet", "entities": [] }, { "text": "hello", "intent": "greet", "entities": [] }, { "text": "hi", "intent": "greet", "entities": [] }, { "text": "good morning", "intent": "greet", "entities": [] }, { "text": "good evening", "intent": "greet", "entities": [] }, { "text": "dear sir", "intent": "greet", "entities": [] }, { "text": "yes", "intent": "affirm", "entities": [] }, { "text": "yep", "intent": "affirm", "entities": [] }, { "text": … -
ModuleNotFoundError: No module named 'config.urls'; 'config' is not a package?
itook some sample code that was made in the django version 1.8.4, and like Python 2.7 when transferred to 3 python all flown away and produced such an error, how to fix it? i'am change previous error, but new is blow up ** P.S I HAVE NO CODE, THIS ERROR IS BLOW UP IN LIB/SITE-PACKAGES/config.py ** Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\12\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
The view orders.views.order_create didn't return an HttpResponse object. It returned None instead
The view orders.views.order_create didn't return an HttpResponse object. It returned None instead. I tried everything and still get this error I think that the problem is with the urls but i am not sure. This is the views.py for the order checkout. I get the error when I click the checkout everything else is working and only the checkout is giving an error. from django.shortcuts import render from django.template import loader from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity']) cart.clear() return render(request, 'orders/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'orders/create.html', {'cart': cart, 'form':form}) the base urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^cart/', include('cart.urls', namespace='cart')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^$', views.index, name='index'), url(r'^(?P<product_id>[0-9a-f-]+)/$', views.detail, name="detail"), ] and the order app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^create/$', views.order_create, name='order_create'), ] the url in localhost should be 127.0.0.1:8000/orders/create and the create.html and created.html are in the templates folder in the market folder. I would kindly provide any other information if needed to … -
Django filters options specific to queryset only
I use django-filter to provide user filtering on a list view on my site, e.g. class MyModel(models.Model): fruit = models.ForeignKey(Fruit) price = models.CharField(...) release_date = models.DateTimeField(...) class MyFilter(filters.FilterSet): ... class Meta: model = MyModel fields = ['fruit', 'price', 'release_date'] def my_banana_orange_view(request): ... queryset = MyModel.objects.filter(fruit__name__in=['banana', 'orange']) filter = Filter(queryset) return render(request, 'my_template.html', {'queryset': queryset, 'filter': filter}) Now if I do this, I can display just the MyModel entries that have either banana or orange relationships, but MyFilter will still give the option of all the fruits in the Fruit model. I'm trying to find a setting for a FilterSet to just show options related to the input queryset, but can't find one. Does one exist? Otherwise I guess I would have to override the filter to do something like this: class MyFilter(filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.filters['fruit'].extra['queryset'] = Fruit.objects.filter(mymodel=self.queryset) class Meta: model = MyModel fields = ['fruit', 'price', 'release_date'] Which seems a bit overkill. Only showing options based on the input queryset seems like desirable behaviour, but I can't find any documentation for it. Is there a good way to do this? Any help appreciated! -
django - annotate() - Sum() of a column with filter on another column
I have the following two models. class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) opening_stock=models.PositiveIntegerField(default=0) class Meta: unique_together = ('product_group', 'manufacturer') and TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False) I need to list all products with stock_in_sum=Sum(of all stock ins) , stock_out_sum=Sum(of all stock outs) and blance_stock=opening_stock+stock_in_sum - stock_out_sum This is what I've achieved so far. class ProductList(ListView): model=Product def get_queryset(self): queryset = super(ProductList, self).get_queryset() queryset = queryset.prefetch_related('product_group','product_group__category','manufacturer') queryset = queryset.annotate(stock_in_sum = Sum('stock__quantity')) queryset = queryset.annotate(stock_out_sum = Sum('stock__quantity')) I need to get stock_in_sum as the sum(quantity) where ttype='I' stock_out_sum as the sum(quantity) where ttype='O' blance_stock as product.opening_stock + stock_in_sum - stock_out_sum along with each Product object. How do I achieve this? Thanks. -
How can i POST data with graphene_django?
I'm completely new to GraphQL and graphene and i just finished the graphene_django tutorial I understand how to get data from server, which is pretty easy, but i don't know how to do create or update do i need to use django rest framwork for POSTs or is it possible to use just graphene to get and put data? -
Django: Customizing ManyToManyField form options
I have a ManyToManyField in a Django template like so: {{ form.contacts }} When rendering the Contact objects in a list, Django prints the __str__ (or __unicode__) for each object (the ID). In my case, I want a more human-friendly display of each object, so instead of rendering each of the objects ID's; I'd like to have the name of the object and just some more data about it. So, is there any way to customize each of the list items so that I can add divs to the HTML and display other bits of data for each object like you would do in a for loop? -
Dynamic Dependent Select Box using Jquery and Ajax in Django Template
I found a code sample in the below link http://www.webslesson.info/2017/05/json-dynamic-dependent-select-box-using-jquery-and-ajax.html for Dynamic dependable Select box, how i can implement that in my Django Template. This is the Jquery code <script> $(document).ready(function(){ load_json_data('country'); function load_json_data(id, parent_id) { var html_code = ''; $.getJSON('json/country_state_city.json', function(data){ html_code += '<option value="">Select '+id+'</option>'; $.each(data, function(key, value){ if(id == 'country') { if(value.parent_id == '0') { html_code += '<option value="'+value.id+'">'+value.name+'</option>'; } } else { if(value.parent_id == parent_id) { html_code += '<option value="'+value.id+'">'+value.name+'</option>'; } } }); $('#'+id).html(html_code); }); } $(document).on('change', '#country', function(){ var country_id = $(this).val(); if(country_id != '') { load_json_data('state', country_id); } else { $('#state').html('<option value="">Select state</option>'); $('#city').html('<option value="">Select city</option>'); } }); $(document).on('change', '#state', function(){ var state_id = $(this).val(); if(state_id != '') { load_json_data('city', state_id); } else { $('#city').html('<option value="">Select city</option>'); } }); }); </script> What modification i have to do in the above mentioned Jquery code to run in Django template. -
How to list available links in Django?
In Django, I'd like to display a simple view of the available links a user can click on in descending lexicographic order. For example, say I have a website and I want to display the links in descending lexicographic order. Perhaps it is a site with blog posts and they're created daily. Thus the homepage (rendered in "urls.py" as r"^$") would have something like the following for the past 5 blog posts: Welcome to the Home Page! Below are the last 5 Blog Posts: 2017.08.04 2017.08.03 2017.08.02 2017.08.01 2017.07.31 For anyone who has used Jupyter notebooks, I'm thinking something similar to the directory structure when a notebook is launched (but reversed ordering). Further, similar to the structure in Jupyter notebooks, I'd like to use this link structure to continue to display where a user can navigate to as they click on each link (similar to a directory structure, but for the web pages). If anyone can help with this I'd be most grateful. Thanks -
How to dynamically turn off and on email sending?
I have a model Reservation which sends email to user when it's created. For testing purposes, I want to populate database with hundreds of Reservations from time to time. It can produce thousands of emails so I would like to turn off email sending, or dynamically change email backend if possible. I can't do bulk create because I need to perform save method for every Reservation model. The only thing which comes to my mind is to temporarily change settings.py but maybe there is a better way to do that (I may forgot to change settings). def create_random_reservations(count=10, user='futilestudio'): users = User.objects.all() airports = Location.objects.filter(is_airport=True) cities = Location.objects.filter(is_airport=False) for n in range(count / 2): dt = datetime(year=2017, month=9, day=random.choice(range(15, 20)), hour=random.choice(range(12, 22)), minute=random.choice(range(60))) r = Reservation.objects.create(customer_first_name=get_random_string(10), customer_last_name=get_random_string(10), flight_number=get_random_string(5), destination_from=random.choice(airports), destination_to=random.choice(cities), date_arrival=dt.date(), time_arrival=dt.time(), customer=random.choice(users)) r.confirm(save=True) -
Python upgrade to 3.5 from 2.7 for a different project using virtualenv in windows 10
I am a fresher in Python/Django My local python version is 2.7.12 and OS is windows 10. Django version is for another project is 1.10.1 I have installed virtualenvwrapper. Now I am in the process to setup a dev platform for a project where python 3.5 is required. I have another project where I am using py 2.7 I would like to update python version(not globally) but only for my current project. Any help(steps or a link) is highly appreciated. -
Order by content type generic field django
{ "count": 35, "next": null, "previous": null, "results": [ { "id": 27903, "url": "http://127.0.0.1:8080/api/items/27903/", "comment": "", "content_type": "location", "item": { "id": 217596, "url": "http://127.0.0.1:8080/api/locations/217596/", "name": "Abraço", "latitude": 40.7270499, "longitude": -73.9861623, "description": "", "business_type": "", "is_published": true, } } } I want to sort by name. this is in item. This generic relation. I am working on django rest framework. model.py content_type_limit = models.Q(app_label='search', model='location') | models.Q(app_label='menus', model='menuitem') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=content_type_limit) name = models.TextField(blank=True) object_id = models.IntegerField() item = GenericForeignKey('content_type', 'object_id') serializers.py item = GenericRelatedField({ Location: LocationDetailsSerializer(), MenuItem: MenuItemSerializer(), }, read_only=True) Sort by name in Location. Location is another model. -
How to display indented xml inside a django webpage?
In my Django application, I call an external API, which returns XML. I would like to display this "minified" response as an indented multiline string on the page (a plus would be syntax highlighting). I tried to process the string in Python with toprettyxml() from xml.dom.minidom, and a few things with ElementTree, but it does not play along the Jinja2 rendering well (line breaks disappear and I only get a one line string). What's the recommended way to display such code excerpt? Should I use client-side rendering? Then, which library should I use? Django version: 1.11.2 Python 3.6.1 -
Django 1.9 Cannot resolve keyword 'models' into field. Choices are: comm, id1, id2, id2_id
Having these two models: class Models(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() genes = models.TextField(blank=True, null=True) class Meta: db_table = 'models' class ModelInteractions(models.Model): id1 = models.IntegerField(primary_key=True) id2 = models.ForeignKey('Models') comm = models.TextField(blank=True, null=True) class Meta: unique_together = (('id1', 'id2'),) I'm trying to select comm (from ModelInteractions) but also with name (from Models), for specific request_id (ID received with the request). I'm using: # request_genes example = "ab-2;cra-19" genes = request_genes.split(';') condition = Q(id2=request_id) for field in genes: condition &= Q(models__genes__icontains=field) models = ModelInteractions.objects.filter(condition) This returns: Cannot resolve keyword 'models' into field. Choices are: comm, id1, id2, id2_id. Without for loop everything works fine, but I don't have Models data. What am I missing? -
I am facing when i want to edit the table?
when i ma clicking on the button then i am facing problem so how to resolve it .so please anybody could resolve my code.Is there url problem or some thing else #views.py def edit_post(request,id): user=get_object_or_404(User,pk=id) if request.method == 'POST': form = UserForm(request.POST,instance=user) #return HttpResponse(request.get('first_name')) if form.is_valid(): User=form.save(commit=False) User.first_name=request.first_nmae User.last_name=request.last_name User.email=request.email User.birth_date=request.birth_date User.address=request.address User.save() return redirect('anup:index',id=user.id) else: form=UserForm(instance=User) return render(request, 'anup/login.html', {'form': form}) #models.py class User(models.Model): # username = models.CharField(max_length=50) #password = models.CharField(max_length=20) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=30) birth_date = models.DateField() # Gender = models.BooleanField() address = models.CharField(max_length=30) #def get_absolute_url(self): #urls.py url(r'anup/(?P<id>[-\W]+)/edit/$',views.edit_post, name="post") #table.html <table name="table"> <thead> <tr> <th>ID</th> <th>First_name</th> <th>last_name</th> <th>email</th> <th>birth_Date</th> <th>address</th> <th></th> </tr> </thead> {% for item in query_results %} <tbody> <tr> <td>{{item.id}}</td> <td>{{ item.first_name }}</td> <td>{{ item.last_name }}</td> <td>{{ item.email}}</td> <td>{{ item.birth_date}}</td> <td>{{ item.address}}</td> <td><a href="{%url 'post'%user.id}"><button type="button" class="btn btn-default"><span class="glyphicon glyphicin-pencil" aria-hidden="true"></span>Edit</button> </a></td> </tr> </tbody> {% endfor %} </table> my error is Reverse for 'post' with arguments '('',)' not found. 1 pattern(s) tried: ['anup/anup/(?P<id>[-\\W]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/anup/display/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'post' with arguments '('',)' not found. 1 pattern(s) tried: ['anup/anup/(?P<id>[-\\W]+)/edit/$'] why there is error is my code -
Django: having trouble redirecting to html page after addingdata in database
I have added a get_absolute_url function in a model called "Album". class Album(models.Model): album_title = models.CharField(max_length=30) artist = models.CharField(max_length=30) genre = models.CharField(max_length=30) def get_absolute_url(self): return reverse('cart:details', kwargs={'pk': self.pk}) And added a class CreateView to add new albums in the database. Everytime I enter an album, the page shows an error in redirection. CreateView Class: class AlbumCreate(CreateView): model = Album fields = ['album_title', 'artist', 'genre'] The error is : Reverse for 'details' with keyword arguments '{'pk': 4L}' not found. 1 pattern(s) tried: [u'cart/(?P<album_id>[0-9]+)/$']" What might be the problem here? -
Uploading a files from a React UI to a Django DRF
In order to learn more about ReactJS, I am building a simple prototype with ReactJS on the frontend which is connected to Django Rest Framework backend. I would like to be able to upload a CSV file and let Django process it. I am basically still tinkering on the best way to upload this CSV file. From my understanding it is better to let React render the form on the client side using libraries such as React-DropZone. However I am having trouble figuring out how to save it on the server through an API call. Strategies I am considering: 1. Since I do not need to permanently store CSV, I do not really need to save it on a database but on the local file system and let Django access it from there. 2. Let's say first option is not doable, I would serialise CSV and store it in a model.