Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the correct way of generating test fixtures for use in Wagtail unit tests?
I am trying to generate a custom page tree for testing user view permissions in the admin panel. I am dumping the fixture into a file with the following command: ./manage.py dumpdata --natural-foreign --natural-primary --indent 4 > test.json and using the fixture in the test case as so: class MyTest(TestCase, WagtailTestUtils): fixtures = ['test.json'] def test_my_code(self): # More code.... Running this test returns the following error: File "/Users/jchau/.pyenv/versions/2.7.8/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, params) DeserializationError: Problem installing fixture '/Users/jchau/Documents/wagtail/wagtail/tests/testapp/fixtures/test_group_restrictions.json': no such table: auth_user It appears that my test data is malformed. Is there an accepted way for generating custom test fixtures for use in Wagtail? Note: These commands are being run against a vanilla installation of Wagtail 1.8. I have not created any custom models or datatypes or otherwise made any modifications, so the only existing data is comprised of sites and pages. -
Profile matching query does not exist on the server, but on local vagrant all fine
I have code< which works as needed in my vagrant machine, but always fails in aws server. In my view? after saving object, I add it to raters field in my profile object(which I use as user_auth_model): serializer.save() profile = Profile.objects.get(id=request.user.id) created = Rater.objects.latest('name') profile.raters.add(created) profile.save() Error message: Profile matching query does not exist Where can be bug/mistake? -
Not getting the value in django template
models.py class StockList(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) stock = models.ForeignKey(Stock) quantity = models.IntegerField(verbose_name='No.of Shares',default=0) timestamp = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return str(self.stock) def market_value_reciever(sender, instance, *args, **kwargs): purchase_price = instance.stock.purchase_price quantity = instance.quantity market_value = purchase_price * quantity instance.market_value = market_value print(purchase_price) print(market_value) pre_save.connect(market_value_reciever, sender=StockList) html template {% for item in queryset %} <tr> <td> <a href="#">{{ item.stock.name }}</a> </td> <td> {{ item.purchase_price }} </td> <td> {{ item.quantity }} </td> <td> {{ item.market_value }} </td> </tr> {% endfor %} Here I am getting only the value of quantity on html template, purchase price and market value fields are not getting on templates but its values are getting on terminal. Anybody can help, Thank you so much. -
POST Data from Arduino to Django Server on Pythonanywhere Return 404
I have been trying for a while now to use the HTTP POST method to send data to my Django server on pythonanywhere.com, but I keep getting a 404 error. I can't think of anything wrong with the URL (Even though there must be), but below is my code for both Arduino and Django: Arduino: #include "arduino4G.h" // APN settings /////////////////////////////////////// char apn[] = "phone"; char login[] = ""; char password[] = ""; /////////////////////////////////////// // SERVER settings /////////////////////////////////////// char host[] = "marcoprouve.pythonanywhere.com"; unsigned int port = 80; char resource[] = "/sensors4G/sensor_log/"; char data[] = "\"Name\": \"Marco\""; /////////////////////////////////////// // variables int error; void setup() { error = _4G.ON(); if (error == 0) Serial.println(F("module ON...")); else Serial.println(F("module OFF")); Serial.println(F("Start program")); ////////////////////////////////////////////////// // 1. sets operator parameters ////////////////////////////////////////////////// _4G.set_APN(apn, login, password); ////////////////////////////////////////////////// // 2. Show APN settings via USB port ////////////////////////////////////////////////// _4G.show_APN(); } void loop() { ////////////////////////////////////////////////// // 1. Switch ON ////////////////////////////////////////////////// error = _4G.ON(); Serial.println(F("Start program")); if (error == 0) { Serial.println(F("1. 4G module ready...")); //////////////////////////////////////////////// // 2. HTTP POST //////////////////////////////////////////////// Serial.println(F("2. HTTP POST request...")); // send the request error = _4G.http( POST_METHOD, host, port, resource, data); // check the answer if (error == 0) { Serial.print(F("Done. HTTP code: ")); Serial.println(_4G._httpCode); Serial.print("Server … -
Django Inplaceedit Exception: KeyError 'Request', Even With Request Context Processors
I am trying to use Django's inplaceedit form so my client can do front end editing. I have place {% load inplace_edit %} and {% inplace_static %} in all the appropriate places, but get this exception message when I navigate to any of the pages on my site. KeyError: 'request' I did some snooping around the web, and on SO to see if I could find a common problem. The usual problem people face with this issue is that they don't have django.template.context_processors.request in their templates configuration in their settings file. I have this template context processor though so I am not sure why I am still getting this exception. I am using python v3.5, and Django v1.9 . settings.py template configuration. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'webapp.context_processors.detail_context', ], }, }, ] base.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> {% load static %} {% load inplace_edit %} {% inplace_static %} <html> <head> <title>{% block title %}Parenti-Morris{% endblock %}</title> <!-- CSS --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css"> <link type="text/css" rel="stylesheet" href="/static/css/base.css"/> <link type="text/css" rel="stylesheet" href="/static/css/nav.css"/> <!-- SCRIPTS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script … -
Django postsave signal missing parameters in user login from admin panel
This is my signal: def deactivate_users_by_default(sender, user, created, **kwargs): print sender, user, created if created: user.is_active = False user.save() signals.post_save.connect(deactivate_users_by_default, sender=User, dispatch_uid="deactivate_users_by_default") When I login through my login form, this is fine, doesn't pass the if statement, but the signal gets called properly. Now when I login through the admin panel I get this: response = receiver(signal=self, sender=sender, **named) TypeError: deactivate_users_by_default() takes exactly 3 arguments (2 given) What am I doing wrong? -
Django Rest Framework filter class method with two parameters
I have a model which relates to many models, like this: class Father: son = # Foreign key to Son model class Son: @property def son_daughters: if ... : obj = TypeA.objects.get(...) elif ... : obj = TypeB.objects.get(...) else: obj = TypeC.objects.get(...) return obj I would like to get Father data from daughter name or type. I have this filter class where I need to send two query set parameters related to daughter in order to get daughter ids and apply it as a filter to Father. This is my filter class: class FatherFilter(django_filters.rest_framework.FilterSet): def daughter(self, method_name, args, **kwargs): print(method_name, args, kwargs) ... daughter_id = django_filters.NumberFilter(method=daughter) But when I call this endpoint I just get one query parameter and not all. Is there a way to get the query parameters inside this method instead of just one? Thanks in advance. -
Using inline formset factory with multiple foreign keys in a model
I have the following models: class Train(models.Model): pass class City(models.Model): train = models.ForeignKey(Train) name = models.CharField(max_length=100) class Route(models.Model): train = models.ForeignKey(Train) name = models.CharField(max_length=100) class Travel(models.Model): train = models.ForeignKey(Train) current_city = models.ForeignKey(City, related_name = 'current') through = models.ForeignKey(Route) next_city = models.ForeignKey(City, related_name = 'next') and I have already established the form to create a train, add a city and route at the same time using th e inline formsets like this: forms.py class TrainForm(ModelForm): class Meta: model = Train class CityForm(ModelForm): class Meta: model = City class RouteForm(ModelForm): class Meta: model = Route CityFormSet = inlineformset_factory(Train, City, form=CityForm) RouteFormSet = inlineformset_factory(Train, Route, form=RouteForm) views.py class TrainCreate(CreateView): model = Train class TrainInfoCreate(CreateView): model = Train fields = [] success_url = reverse_lazy('train-list') def get_context_data(self, **kwargs): data = super(TrainInfoCreate, self).get_context_data(**kwargs) if self.request.POST: data['cities'] = CityFormSet(self.request.POST) data['routes'] = RouteFormSet(self.request.POST) else: data['cities'] = CityFormSet() data['routes'] = RouteFormSet() return data def form_valid(self, form): context = self.get_context_data() cities = context['cities'] routes = context['routes'] with transaction.atomic(): self.object = form.save() if cities.is_valid() and routes.is_valid(): cities.instance = self.object routes.instance = self.object cities.save() routes.save() return super(TrainInfoCreate, self).form_valid(form) This has helped me create only the cities and routes but not the travels since the Travel model has 3 different foreign keys and … -
How to redirect in Django with form errors?
In my project, I have an order detail page. This page has multiple forms (return order, deliver order etc.) Each of this forms are handled using different views. For example returning order form has action which calls order_return view which then, if ReturnOrderForm is valid, redirects back to order_detail. The problem is when there are errors in the ReturnOrderForm. I would like to get back to order_detail and show the errors. For now, I just render order_detail inside the order_return view in case there are errors, which works good but the url isn't changed to order_detail url. I would use HttpResponseRedirect but I have no idea how to handle errors. Do you have any ideas? def order_return(request): return_order_form = ReturnOrderForm(request.POST or None) order_id = request.POST.get('order_id') order = Job.objects.get(id=order_id) if request.method == 'POST': if return_order_form.is_valid(): ... order.delivery.return_delivery(notes=customer_notes) return HttpResponseRedirect(reverse("order_detail", args=(order_id,))) return render(request, "ordersapp/order_detail/order-detail.html", context={'return_order_form': return_order_form, ...}) -
Storing reply_channel
I have simple task of saving reply_channel in DB But message.reply_channel has class type Django Channels documentation says that reply_channel is unique pointer to the open WebSocket So, how could I store this unique pointer in DB? -
using jQuery for buttons/ajax requests
I am fairly new to jQuery, and even though there are a lot of tutorials on how to bind to buttons, I believe my set up is a little more complicated (beyond the scope). What I have: -I am using Django to populate my Makes on a view. Here is my template: {% if makes %} {% for make in makes %} <button type="button" name="button" class="btn btn-default" id="{{ make.id }}"> <br /> <img class="center-block" src="[REDACTED]" /> <br /> <p>{{ make.name }}</p> </button> {% endfor %} {% endif %} The Workflow: User sees (35) different buttons to select from. As you can see name, and id are unique, where id is the Primary Key from the database (this is obviously important) I'm trying to capture this key using jQuery using this function (doesn't work for me): $(document).ready(function() { $("button").click(function() { alert($(this).attr('id')); //testing functionality }); }); At the same time, jQuery is going to hide/remove the button elements (trivial) Then I would like to use the id from button clicked to do an AJAX request to my API, where django URL routing is: url(r'^makes/(?P<pk>[\d]+)/$', views.MakesDetail.as_view(), name='makes-instance'), in other words, the AJAX request goes to mysite.com/api/makes/(this.id) and returns a JSON file (already set-up … -
Error Serving a static file in Django
Settings.py STATIC_PATH = '/Users/peter/Desktop/proyectosP/ahqv2/subastas/static' STATIC_URL = "static/" in the template i put {% load static %} <a href="{% static '1.svg' %}" >This is a test</a> <img src="{% static '2.png' %}" > The page renders but no image or download is available -
Eclipse/PyDev/Django not recognizing project app imports
Found something on SO, but couldn't solve my problem, it is slightly different from the ones I saw.. So, here's the deal, I have a Django project, and it runs perfectly.. I'm using Eclipse for IDLE, and there's the problem.. In urls.py and others, I have to import files from the Django Apps.. Like from app1 import views or in 1 app from app1.forms import Form1 And Eclipse gives me Unresolved import If I change it to (using the example above) from projectname.app1 import views or from projectname.app1.forms import Form1, the error goes away, but then I get an error when I run the project: ImportError: No module named 'projectname.app1' What I have done: Already tried this, but with no success..Project, Clean, Reset, and nothing.. -
Django Wagtail pageurl template tag returning incorrect host name
I'm using Wagtail 1.8 and the pageurl template tag on a blog index page to hyperlink the titles of the blogs through to the actual blog pages. Pretty standard stuff. This is a Django 1.10 project. <a class="blog-post-link" href="{% pageurl blog %}"> <h2>{{ blog.title }}</h2> </a> The very strange problem I'm having is that the host name of the site is being replaced by the host name of my server that is hosting the site. For example, a correct link would be: https://beadtrails.com/blog/vernon-bc-what-to-do-on-and-off-the-trails/ However, it is sometime being returned as https://graphicearth.ca/blog/vernon-bc-what-to-do-on-and-off-the-trails/ When I say sometimes, if I go to the wagtail admin sites page, then into the host record and save it, it will fix the problem--for a while. It will then revert back to the incorrect url. As you can imagine, this is not a great situation where your blog links end in a 404 error! For trouble shooting, I've checked the config of both Wagtail and Django sites tables, checked the config files correctly identify the SITE_ID, done a text search through all the source code for 'graphicearth.ca', reviewed the uWSGI and nginx config files, checked that the blog hierarchy is correct within Wagtail relative to the home … -
Python Django: Emailing xlsxwriter with pandas dataframe
I had an old script that pulled some data and manually wrote each line to an excel file in xlsxwriter and followed up by emailing that information. I thought it would be more efficient and easier to make changes if it were in a pandas dataframe. I can't seem to get the file to attach and send as I did in the past. It's now returning this error: Error: <type 'exceptions.AttributeError'> Thanks in advance for your help! views.py def download(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="slotDownload.xlsx"' writer = Write2Excel(FloorTracker.objects.filter(on_floor=1).select_related('user').select_related('showroom_number'),request) response.write(writer) return HttpResponseRedirect('/slotUploader/') def WriteToExcel(data, request): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output) header = workbook.add_format({ 'color': 'black', 'align': 'center', }) dateformat = workbook.add_format({'num_format': 'mm/dd/yyyy'}) worksheet_s = workbook.add_worksheet("download") # add worksheet_s #Write column headers worksheet_s.write_string(0,0, 'Showroom Number', header) worksheet_s.write_string(0,1, 'Brand', header) worksheet_s.write_string(0,2, 'Family', header) worksheet_s.write_string(0,3, 'Mattress', header) worksheet_s.write_string(0,4, 'On Floor', header) worksheet_s.write_string(0,5, 'Size', header) worksheet_s.write_string(0,6, 'Underbed', header) worksheet_s.write_string(0,7, 'lastUpdate', header) worksheet_s.write_string(0,8, 'Rep', header) worksheet_s.write_string(0,9, 'NAM', header) worksheet_s.write_string(0,10, 'City', header) worksheet_s.write_string(0,11, 'State', header) worksheet_s.write_string(0,12, 'Warehouse Name', header) worksheet_s.write_string(0,13, 'Value Zone', header) worksheet_s.write_string(0,14, 'Comparison Center', header) worksheet_s.write_string(0,15, 'Suggested Retail', header) worksheet_s.write_string(0,16, 'Showroom Name', header) worksheet_s.write_string(0,17, 'Company', header) for idx, item in enumerate(data): row = 1 + idx worksheet_s.write_string(row, 0, item.showroom_number.storenumber) worksheet_s.write_string(row, 1, item.brand) … -
How to unregister Group for certain user in Django
I am going to customize the Built-In Django Authentication and Authorization page. In my case I have 2 levels administrators. The lower level administrators can only add/remove users, therefore I am planning to hide the Group from them. admin.site.unregister(Group) works but it unregister Group for all admins. Does anyone know which class should I customize? Thanks! -
How to automate django-background-task
I am trying to use django-background-task package to do some background tasks. I need to know that can I avoid/automate python manage.py process_tasks command so that it should run scheduled task without above command ? -
Django Webpack compiling misc JS in brand new Django/ReactJS app to make 21,500 line file
I have been following the below tutorial to get Django and ReactJS working: http://geezhawk.github.io/using-react-with-django-rest-framework I started a brand new Django project, added an app called home, but have otherwise done nothing else except what is outlined in the tutorial. Anyway, when I compile the JS it creates a file that is about 21,500 lines and 800kb. My ReactJS file is only about 20 lines and there is no other JS to speak of from the Django app. It seems like it is compiling dependencies in the virtualenv or something. Anyway to prevent this? -
Unable to install Docker for Windows for the Divio App
When trying to set up the Divio app, I get this warning screen. DivioSetupWarningScreen However, even though the picture claims I do, I don't have Docker Toolbox installed. When I try to install Docker for Windows on anyways by pressing the "Continue" button as seen in the picture above, I get this. DockerInstallFailed In the second picture, I tried clicking "Contact Support," but that led me to a blank webpage. Also, if I try to install Docker Windows without the Divio App, but it would not let me because I do not have the enterprise Windows OS, just the home. I also tried downloading Boot2Docker Start, but that didn't really help. I'm at a loss as to what to try next. Any help would be appreciated.Thanks! -
Performance impact of reverse relationships in Django
I'm setting up my Models and I'm trying to avoid using ManyToMany Relationships. I have this setup: Model: Human Some Humans (a small percentage) need to have M2M relationships with other Humans. Let's call this relationship "knows" (reverse relationship called "is_known_by"). To avoid setting a ManyToManyField in Humans, I made a Model FamousHumans. FamousHumans are a special class of Human and have a OneToOneField(Human) They also have a ManyToManyField(Humans) to represent the "knows" relationship Here is my question: Since Django creates reverse relationships, I assume that all Humans will have a reverse "is_known_by" relationship to FamousHumans, so there is still a M2M relationship. Is there any performance benefit to my setup? The dataset will be rather large and only a few Humans will need the M2M relationship. My main concern is performance. -
Django: Making an efficient query by removing 340 duplicate queries
I'm graphing a bunch of price data by day. Think stock trades by day. What I want to do: Show the trades by day Show the mean line of the prices to show a general trend Problem: When I look in Django Debug Toolbar at the queries, I see: 346 queries 1498.11ms Looking at the actual queries, I see "Duplicated 340 times" for get_queryset() as it queries each day. How can I make this more efficient so there aren't duplicates? Any tips/tricks on how to make this as efficient as possible would be greatly appreciated. How: I have a view that inherits from a GraphView I've made to return the data necessary to graph the prices of the objects returned. With this request returning potentially thousands of results, getting this query as efficient as possible is important for the load times. Tools used: Django 1.10.1 Postgres Plotly to graph the results in the template Django debug toolbar Views & query: class GraphView(TemplateView): def get_dates(self): dates = [] if self.get_queryset(): start = self.get_queryset()[0][2].date() end = datetime.today().date() delta = end - start for i in range(delta.days + 1): dates.append(start + timedelta(days=i)) return dates def data_points(self): trades = self.get_queryset() dates = self.get_dates() data_x … -
Django REST API create a combination of URLs
I have the following tables: -Parent -Child With my API I have the following URLS.py url(r'^parent/$', views.parent.as_view(), name='parent-list'), url(r'^parent/(?P<pk>[\d]+)/$', views.parentDetail.as_view(), name='parent-instance'), and the same for child. however, I would like to make an instance where my URL is: /parent/?P<pk>[\d]+)/$'/child/?P<pk>[\d]+)/$' or even more simply parent_id/child_id where this prints the specific child relative to the parent. How do I go about this using DRF (Django Rest Framework)? -
How to connect button and field value with jQuery for object in for loop from template
When I post form, any quanity updates with value from first quantity field. I don't know how to connect quantity value and particular submit button for this value. My form in template.html {% for item in cart %} <form action="{% url 'product_update' item.product.id %}" method="POST"> {% csrf_token %} <input type="number" class="form-control" id='quantity' value="{{ item.quantity }}"> <button type="submit" class="btn btn-link update-product"> <span class="glyphicon glyphicon-refresh"> </span> </button> </form> {% endif %} My view (I use django-cart for my cart) def product_update(request, id): product = Product.objects.get(id=id) cart = Cart(request) quantity = request.POST['quantity'] unit_price = product.price cart.update(product, quantity, unit_price) return JsonResponse({'status': 'success'}) My javascript function updateProductQuantity(){ $('button.update-product').click(function(){ var link = $(this).parents('form') var quantity = $('#quantity').val() //I think my problem is here $.ajax({ 'url': link.attr('action'), 'type': 'POST', 'dataType': 'json', 'data': { 'quantity': quantity, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val() }, 'success': function(data, status, xhr){ alert(data['status']); return false; } }); return false; }); } -
mysql error whlie running django on virtual host
when i runserver on virtualhost i face this error django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module: 'No module named 'django.contrib.messagpip install mysqlclientes'' and i've already installed python 3.4 django 1.10 mysqlclient and here is my configuration in setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'busineti_businet', 'USER': 'busineti_django', 'PASSWORD': str(db_password), 'HOST': 'localhost', 'PORT': '3306', } } can somebody help me how to fix it? -
Django post_save signal can't find related object
This has worked for me in the past, but for some reason it isn't now. @receiver(post_save, sender=Purchase) def set_static_values_for_purchase(sender, update_fields, created, instance, **kwargs): print(instance.supplier) if created: weights = instance.supplier.market.weights In this case, supplier is a fk relation on the model: supplier = models.ForeignKey(Company, null=True, related_name="supplier") However, when the object is created, with a valid supplier selected, the signal spits out None instead of the related object on the print line. If I create the object without the signal, it works just fine: class CreateRecordTest(TestCase): @classmethod def setUpTestData(cls): base_data(cls) c = Client() def test_create_record(self): response = self.c.post(reverse_lazy("Inventory:create_record"), { 'branch_name': self.HOME.name, 'invoice': '2000', 'variety_name': self.GB.name, 'supplier_name': self.ACME.name, }) purchase = Purchase.objects.get(invoice="2000") print(purchase.supplier) This successfully returns the supplier's name (Acme). However, if I enable the signal and run the same test, I get the error: AttributeError: 'NoneType' object has no attribute 'market' Which points back to the fact that the FK relationship isn't being detected in the signal. What am I missing?