Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
errow with set_all() in models.py Django, how to fix this exactly in models?
I need to make the counter of the scanned series, and add that number of values that it will count! When I add to the views it issues this error series_watched_count = user.userwatching__set.all().count() AttributeError: 'User' object has no attribute 'userwatching__set' class UserWathching(models.Model): user = models.ForeignKey(User, default=None, blank=True, null=True) serie = models.ForeignKey(Series, default=None, blank=True, null=True) #preview_of_serial_for_watched = models.ForeignKey(Serial, default=None, blank=True, null=True) #rus_name_of_serial = models.ForeignKey(Serial, default=None, blank=True, null=True) #eng_name_of_serial = models.ForeignKey(Serial, default=None, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def user_watching_post_save(sender, instance, created, **kwargs): user = instance.user series_watched_count = user.userwatching_set.all().count() user_profile = user.userprofile user_profile.series_watched_nmb = series_watched_count user_profile.save(force_update=True) post_save.connect(user_watching_post_save, sender=UserWathching) class UserProfile(models.Model): user = models.OneToOneField(User, default=1) serials_watched_nmb = models.IntegerField(default=0) series_watched_nmb = models.IntegerField(default=0) minutes_wathced_nmb = models.IntegerField(default=0) -
django - Find max using two foreign keys, and using __in
I am pretty new on Django and Python and I have a problem. Here are my models : class Similarity(models.Model): score = models.FloatField(max_length=10) mother_fk = models.ForeignKey('MotherCompound', on_delete=models.CASCADE) father_fk= models.ForeignKey('FatherCompound',on_delete=models.CASCADE) Using this view (only the important part) : mothers =XXXXX_set.all() #queryset of mothers fathers =XXXXX_set.all() #queryset of fathers couple= Similarity.objects.filter(mother_fk__in=mothers,father_fk__in=fathers) At the end, I will have a table of this shape, different combinations between these two foreign keys. M1/F1 = 1.0 M1/F2 = 0.9 M2/F1 = 0.6 M3/F1 = 0.5 M2/F3 = 0.3 M3/F2 = 0.1 I want depending of the min(len(mothers),len(fathers))( let's say "3") to obtain three couple of Mother/Father with this filter : You look for the best score where a mother and a father is involved in. I mean, a mother and a father can be involved on different combination, but I want to display only one example of them based on the best score. On this example, final output should be : M1/F1 = 1.0 M2/F3 = 0.3 M3/F2 = 0.1 My question is, is it possible to make it in one line, within the query, or if after the query line , I have to make a loop and try to find the max for each … -
I'ts possible accumulate value with increment in a template django?
I would like to know if there is any way to sum values in a variable in template Django using {% for obj in objects %}...Something like this: for student in students: notes += student.note Using the "mathfilters" or something similar to make the sum Thanks! -
Passing url parameter to another url
I am attempting to pass a URL parameter to another view within my app. I currently have a function (EntryListView) that identifies what month you select, and then only shows the contents for that month. However, I would like the month to also be shown in the detail URL. This will enable a "go-back" button to navigate back to the month's page, as opposed to erroring out or navigating back to the landing page. urls.py As Is: url(r'entry/list/(?P<month>\w+)$', views.EntryListView.as_view(), name='entry-list'), url(r'entry/detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), urls.py To Be: url(r'entry/list/(?P<month>\w+)$', views.EntryListView.as_view(), name='entry-list'), url(r'entry/detail/(?P<month>\w+)/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), views.py class DetailView(generic.DetailView): model = Entry template_name = 'argent/detail.html' class EntryListView(generic.ListView): template_name = 'argent/index_list.html' queryset = Entry.objects.all() def get_context_data(self, **kwargs): month = self.kwargs.get('month') ctx = super(EntryListView, self).get_context_data(**kwargs) # January if month == 'January': ctx['January17_qs'] = Entry.objects.filter(date__range=('2017-1-1', '2017-1-31')) return ctx template <a href="{% url 'argent:entry-list' %}"> <button type="button" class="btn btn-primary">Go Back </button> </a> I currently get this error when using {% url 'argent:entry-list' %}: Reverse for 'entry-list' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tracker/entry/list/(?P<month>\\w+)$'] Thanks in advance for your help! -
django/python count number of row inserted in specific month
Purchase_History model class Purchase_History(models.Model): barcode = models.BigIntegerField() email = models.CharField(max_length=100) bill_no = models.IntegerField() longitude = models.CharField(max_length=500) latitude = models.CharField(max_length=500) timestamp = models.DateTimeField(auto_now_add = True, auto_now = False) i want to count number of rows from specific month i tried something like m=Purchase_History.objects.filter(timestamp="month").count() and m=Purchase_History.objects.filter(timestamp=["2017-01-01", "2017-01-31"]).count() its good practice to use timestamp field, please help me, if you have any solution to it. thanks in advance -
Slug issue with Wordpress Data Migration To Django
I am migrating Wordpress Data into Django. The current site title, content, slug are in Hindi. I am using wordpress_xmlrpc to import data from WordPress via xmlrpc. All the content title, content are in Hindi as well, and they are accessed and saved Okay. instance.name = post.title instance.content = post.content While there is issue with Django slugs. Have the tried the following, does not work. instance.slug = unicode(post.slug) instance.slug = post.slug Does anybody know how to reslove this issue. -
Django filter multiple value in the same column
I have set up the column where one of the table is called Establishment_Type Now, I am trying to filter according to Establishment_Type. Here is my view.py code class ShopDetailAPIView(ListAPIView): serializer_class = ShopDetailSerializer def get_queryset(self): queryset = Shop.objects.all() type = self.request.query_params.get('type', None) type2 = self.request.query_params.get('type2', None) if type is not None and type2 is None: queryset = queryset.filter(Establishment_Type = type) elif type is not None and type2 is not None: queryset = queryset.filter(Q(Establishment_Type = type) | Q(Establishment_Type = type2)) return queryset In the url, i query by typing http://127.0.0.1:8000/shop/search/?type=Restaurant&?=Petrol%20Station Which only filter Establishment_Type = Restaurant but not include Establishment_Type = Petrol Station Here is my url.py within my app called shop urlpatterns = [ url(r'^$', ShopListAPIView.as_view(), name = 'list' ), ##### url(r'^create/$', ShopCreateAPIView.as_view(), name = 'create' ), url(r'^search/$', ShopDetailAPIView.as_view(), name = 'detail'), ] Was my url for filtering 2 Establishment type wrong? Do I need to change something in my code in order to filter 2 values in column Establishment_Type? Thank you -
Easiest way to authenticate burning board Php forum via django authentication
We have a django app that currently serves the entire website. We want to add a forum (burning boards by wolfram) which is Php. So you visit example.com/forum and the Php burning board forum displays. When you visit the forum if you are logged into django, the Php forum should be logged in, as it should use the django authentication. Can anyone suggest the easiest way to accomplish this. Best way to integrate PHP forum into Django site? The above has suggestions about mixing Php and django on same site but doesn't discuss authentication. -
How to generate documentation for a Class-based View?
In Django documentation there's a short info on how to document models, views and other files to make it easily available in the Django Admin. But it lacks info on how to do this for class-based views. Say I have simple DetailView: class MyDetailView(DetailView): model = MyModel I write something like: class MyDetailView(DetailView): """ Displays single :model:`myApp.MyModel` with all details. :template:`myApp/mymodel_detail.html` """ model = MyModel But this won't show as a doc text with references to models/templates. How should I do that? -
Django double input on form
I'm fairly new to django programming as I am doing an internship. I have made a model class Dish(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) type = models.CharField(max_length=255, blank=True) Then I made a table containing all the dishes like <td>{{dish.name}}</td> <td>{{dish.price}}</td> <td><input type="number" name="qnty_input" pattern=" 0+\.[0-9]*[1-9][0-9]*$" min="0" onkeypress="return event.charCode >= 48 && event.charCode <= 57" class="form-control input-lg"></td> <td><input type="text" name="comments" class="form-control input-lg"></td> Now what I need to do is let people be able to insert a quantity in the first input and then a comment in the second input, afterwords press a submit button to order the dish(es). Now I have found I can do this with forms but I am only able to format this like: Label:input Label:input Label:input Is there a way so I can put the table in a form so that I get the exact same structure as I would just make the table without forms? -
Django Custom clean method for saving/updating user in admin panel
I want to use phone number as username for Django built-in User Model and I want to check the phone number (username) while creating or updating a user model in admin panel: I tried code below but no success: from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import (UserCreationForm, UserChangeForm) import re class MyUserChangeForm(UserChangeForm): def clean_username(self): username = self.cleaned_data.get('username') if not re.match('^09[\d]{9}$', username): raise ValidationError('Bad phone number') return username class MyUserCreationForm(UserCreationForm): def clean_username(self): username = self.cleaned_data.get('username') if not re.match('^09[\d]{9}$', username): raise ValidationError('Bad phone number') return username class MyUserAdmin(UserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm admin.site.register(UserAdmin, MyUserAdmin) TypeError: 'MediaDefiningClass' object is not iterable -
AJAX dont update page
I have strange problem in my project. Can someone say why it happens and how to fix it. I have function in view for edit/update object (function_edit). Also I use AJAX to update list of objects (function_list) after success edit and also I use django-reversion app to controll the changes of each object. The function_list has part which is visable only to users with a special role (request_user_is_business_analyst). When I use request_user_is_business_analyst in view it raise error and when I dont use it view function works fine. Also when I didnt use django-reversion request_user_is_business_analyst worked fine. urs.py: url(r'^(?P<project_code>[0-9a-f-]+)/(?P<function_code>[0-9a-f-]+)/edit/$', function_edit, name='function_edit'), views.py: @reversion.create_revision() def function_edit(request, project_code, function_code): data = dict() project = get_object_or_404(Project, pk=project_code) request_user_is_business_analyst = project.member_set.filter(user=request.user, role='business_analyst').exists() function = get_object_or_404(Function, pk=function_code) if request.method == 'POST': form = FunctionAddForm(request.POST, instance=function) if form.is_valid(): form.save() data['form_is_valid'] = True functions = Function.objects.filter(project=project_code) data['html_function'] = render_to_string('project/function_list.html', {'functions': functions, 'request_user_is_business_analyst': request_user_is_business_analyst}) # Store some meta-information for reversion. reversion.set_user(request.user) reversion.set_comment('EDIT') else: data['form_is_valid'] = False else: form = FunctionAddForm(instance=function) context = {'project': project, 'function': function, 'form': form} data['html_function_form'] = render_to_string('project/function_edit.html', context, request=request) return JsonResponse(data) function_list.html: {% for function in functions %} <tr> <td class="text-center">{{ function.code }}</td> <td>{{ function.name }}</td> {% if request_user_is_business_analyst %} <td> <a class="btn btn-warning button-handlers" … -
Migration conflict after merging branches
I ran into a migration issue where a couple of migration files have the same number: 0077_auto__add_field_whatever.py 0077_auto__add_modelwhatever.py I just found out about this, didn't really notice before, but I guess this happened because each migration was produced in a different branch and then merged into the main branch. This can eventually cause a migration conflict. I suppose this is a common scenario, so there has to be a solution. How can I solve this issue in a clean way? -
Adding Model field from django views
I am using django-rest-framework with pandas to make an api and my models.py file looks like this class Health(models.Model): Name = models.CharField(max_length=30,null=True,blank=True) Age = models.IntegerField(null=True,blank=True) Weight = models.FloatField(null=True,blank=True) Height = models.FloatField(null=True,blank=True) Sugar = models.FloatField(null=True,blank=True) def __str__(self): return self.Name and my views.py file looks like this @api_view(['GET']) def my_view(request,id): qs = Health.objects.filter(id = id) df = read_frame(qs) df['x-Mean'] = abs(df['Age'] - df['Age'].mean()) df['1.96*std'] = 1.96*df['Age'].std() df['Outlier'] = abs(df['Age'] - df['Age'].mean()) > 1.96*df['Age'].std() df['BMI'] = df['Weight']/(df['Height']/100)**2 a = df.fillna(0) a = a.to_dict(orient = 'records') return Response(a) As you can see that i have no model field named BMI as I am creating it in my views using pandas dataframe and I want to save the field and it's corresponding data in my django database from django views. can anyone help me to achieve this task or suggest an appropriate way to do this. -
converting sql to Django ORM
How to convert this SQL to Django ORM SELECT `saenger_statuschange`.*, `SCP`.* FROM `saenger_statuschange` INNER JOIN `SCP` ON (`saenger_statuschange`.`scp_id` = `SCP`.`id`) INNER JOIN (SELECT scp_id, MAX(date) AS max_date FROM saenger_statuschange WHERE date <= CURRENT_DATE GROUP BY scp_id) grouped ON saenger_statuschange.scp_id = grouped.scp_id AND saenger_statuschange.date = grouped.max_date WHERE `saenger_statuschange`.`scp_id` IN (73, 74) ORDER BY `saenger_statuschange`.`date` ASC I tried with annotate, but unsuccessful -
Raw Update Query inside a while loop in Django Python
Ok im new to python especially django so please be easy on me. i just want to iterate through my resultset per row, then use its values for update query inside the while loop. so far i have this code. def orprocesspost(request, pk): cursor = connection.cursor() #this query returns 2 rows cursor.execute('select ord_recno, orm_recno, account_code, debit, credit, created_by, posted, remarks, origin, sort_order from or_details where orm_recno=%s', [pk]) row = cursor.fetchone() while row is not None: cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]]) row = cursor.fetchone() if i remove this line cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]]) the loop executes fine and i can see the second row being read but when i try to use the update query it only updates 1 row... i don't know whats happening here. i've been searching for the solution for hours.. by the way i followed this tutorial Fetching row by row from MySQL in Python Thanks and regards -
How to set different label for different view for a single model usign CreateView
I have a model that i am using in two view for two purpose. how can i set different lebel for a field. class ChapterCreate(CreateView): model = models.Chapter fields = [ 'title', 'content', 'order', ] I have tried with class Chapter(models.Model): order = models.IntegerField(verbose_name= _('Chapter number')) but this changes to my model itself. But i want to use same model in different view with different label field -
I cant call the functions on my django using react, mobx, axios, django
The function in my mobx store is being called but axios cant find my django function. store.jsx import { autorun, observable, action, computed } from 'mobx'; import axios from 'axios'; axios.defaults.xsrfHeaderName = "X-CSRFToken"; class ProductyTypeStore { @observable producttypelist = []; @action addProductType(description){ console.log("before store add"); axios.post('/addproducttype/') .then(function( res ){ console.log(res); }) // then .catch(function(err){ console.log(err); }) console.log("after store add"); } } var store1 = window.store = new ProductyTypeStore export default store1 urls.py urlpatterns = [ url(r'^', erp, name="erp"), url(r'^addproducttype/$', addProductType, name = "addProductType") ] views.py def erp(request): context = {} template = 'index.html' return render( request, template, context ) def addProductType(request): print("here @ add") log on my manage.py runserver --Starting development server at http://127.0.0.1:8000/ --Quit the server with CONTROL-C. --[30/Mar/2017 03:51:19] "GET / HTTP/1.1" 200 524 --[30/Mar/2017 03:51:19] "GET /static/bundles/local/vendors.js HTTP/1.1" 200 366564 --[30/Mar/2017 03:51:19] "GET /static/bundles/local/erp-2a384599697b15811b6c.js HTTP/1.1" 200 2088371 --[30/Mar/2017 03:51:22] "POST /addproducttype/ HTTP/1.1" 200 524 My print("here @ add") in the django view is never printed. I have no idea whats wrong with my code. -
Redirect to a page after timeout period in Django
I am building a quiz application where the user can take up a quiz from a list of available quizzes. The quiz should be completed within a stipulated time (which is set by the author of quiz). So once the user starts a quiz, I want a timer to start running and once the timer completes, I want the user to be redirected to his/her home page. I can't use session timeout because that would logout the user from the application. Is there anything that Django provides out of the box for such use case? If not, is there any way to achieve this? An enhancement to this feature (at some later point of time) would be to save the quiz without completing it, and resuming it later. So if the total duration for quiz is 5 minutes, I can take the test for 2 minutes and then resume sometime later. In which case, while resuming, the total available time should be 3 minutes for me. This means I will also have to save the state of timer. -
Django Environment Variables is not recognized
Going through a tutorial at Obey The Testing Goat and I'm getting errors using environmental variables. Using Django 1.11, Selenium 3, and Python 3.6. (py36) C:\testgoat\superlists>STAGING_SERVER=superlists-staging.ottg.eu python manage.py test functional_tests 'STAGING_SERVER' is not recognized as an internal or external command, operable program or batch file. If I understand the tutorial correctly, an environmental variable, STAGING_SERVER, is used run tests using a real server instead of Django's test server. django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException import time import unittest import sys import os MAX_WAIT = 10 class NewVisitorTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() staging_server = os.environ.get('STAGING_SERVER') if staging_server: setattr(self, 'live_server_url', 'http://' + staging_server) [...] -
one to one relation in django
I have two table user and address. User has many requests. class User(models.Model): user_id=models.AutoField(primary_key = True) catcher_fname = models.CharField(max_length = 128, blank = True) catcher_lname = models.CharField(max_length = 128, blank = True) api_key = models.CharField(max_length = 100, blank = False) class Address (models.Model): address_id=models.AutoField(primary_key = True) address = models.CharField(max_length = 150) city = models.CharField(max_length = 255) user = models.ForeignKey(Catcher) When I hit a user table, I want his address also and return as JSON. user = User.obejcts.get(pk=2) it's return me only user data not address :( -
TypeError: cyclic object value
I just started learning react + mobx + axios + django and I dont have any what causing this error. store.jsx class ProductyTypeStore { @observable producttypelist = []; @action addProductType(description){ console.log("before store add"); axios.post('/addproducttype/') .then(function( res ){ console.log(res); }) // then .catch(function(err){ console.log(err); }) console.log("after store add"); } } views.py def erp(request): context = {} template = 'index.html' return render( request, template, context ) urls.py urlpatterns = [ url(r'^', erp, name="erp"), url(r'^addproducttype', addProductType, name = "addProductType"), ] I have observed that this error occurs in axios.post function but I dont have any idea whats causing this. I tried putting logs before and after the axios.post function and the messages appears in the log. Thanks -
How to get a list of name arguments in Django's urlpatterns
Suppose I have two apps, App1 and App2. I want to get the list of names of each url in urlpatterns. App1 urls.py: urlpatterns = ( url(regex=r'^$', view=views.index_view, name='index_url'), url(regex=r'^about/$', view=views.about_view, name='about_url'), url(regex=r'^contact/$', view=views.contact_view, name='contact_url'), ) In App2, I want to get the following list: ['index_url', 'about_url', 'contact_url'] I can get individual names: >>> import App1.urls >>> App1.urls.urlpatterns[1].name 'index_url' Technically, I can go over a loop to collect each name in a list. But is there a direct way to get them, like: App1.urls.urlpatterns.names? -
from django.core.management.base import NoArgsCommand, CommandError ImportError: cannot import name 'NoArgsCommand'
Traceback (most recent call last): File "prototypes.py", line 39, in <module> execute_from_command_line(sys.argv) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-package/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/leo/Desktop/prototypes/sitebuilder/management/commands/build.py", line 42, in handle call_command('compress',interactive=False,force=True) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 113, in call_command command = load_command_class(app_name, command_name) File "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/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 "/home/leo/Desktop/learning_log/ll_env/lib/python3.5/site-packages/compressor/management/commands/compress.py", line 9, in <module> from django.core.management.base import NoArgsCommand, CommandError ImportError: cannot import name 'NoArgsCommand' When I run python3 prototypes.py build i got this problem. i just want to compressor the css and js file. and this is my setting. import os import sys from django.conf import settings BASE_DIR = os.path.dirname(__file__) settings.configure( DEBUG=True, SECRET_KEY='plasq@qb+&t-@=x56@=ss=+y-4kp*hj1wy5p!+$cinzhnd+erb', ROOT_URLCONF='sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'sitebuilder', 'compressor', ), TEMPLATES=( { 'BACKEND':'django.template.backends.django.DjangoTemplates', 'DIRS':[], 'APP_DIRS':True, }, ), STATIC_URL='/static/', SITE_PAGES_DIRECTORY=os.path.join( BASE_DIR,'pages'), SITE_OUTPUT_DIRECTORY=os.path.join( BASE_DIR,'_build'), STATIC_ROOT=os.path.join( … -
Shopify Embedded App SDK App Bar Button Form Submission
I want to submit a form when a header app bar button is pressed. The docs say: On any form, you can add the attribute data-shopify-app-submit with the value matching the message value of one of the title bar buttons. When the button is clicked, it will automatically submit that form. My form looks like this: <form data-shopify-app-submit="submitrequest" method="post"> <input name='csrfmiddlewaretoken' type='hidden' value='...'> [... some form fields in form groups ...] <div class="form-group"> <div class="controls"> <input class="btn btn-primary btn primary" id="submit-id-submit" name="submit" type="submit" value="Submit"> </div> </div> </form> In my header where I initialize the app bar I have the following button: buttons: { primary: { label: 'Process', message: 'submitrequest', loading: true } } This renders a Shopify app bar button, but when I click the button the header bar loading triggers but the form does not submit, I get this error in the console: Uncaught TypeError: s.submit is not a function