Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: smart-select how to use it in forms.py
I am using smart_selects in Django to filter drop down views. In my admin page, I was successful in doing this using 'ChainedForeignKey' I am now trying to create a user form and implement the same thing. my approach is models.py class LegalDocumentField(models.Model): name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Lĩnh vực văn bản pháp luật' verbose_name_plural = 'Lĩnh vực văn bản pháp luật' class LegalDocumentType(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE, verbose_name="Lĩnh vực") name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Loại văn bản pháp luật' verbose_name_plural = 'Loại văn bản pháp luật' forms.py class LegalDocumentForm(forms.Form): document_field = ModelChoiceField(label=_("Lĩnh vực văn bản"), queryset=LegalDocumentField.objects.all(), empty_label="--Lĩnh vực văn bản--", required=False) #ag document_type = ChainedModelChoiceField( to_app_name="myapp", to_model_name="LegalDocumentType", chained_field="linhvuc", chained_model_field="linhvuc", foreign_key_app_name="myapp", foreign_key_model_name="LegalDocumentType", foreign_key_field_name="linhvuc", show_all=False,auto_choose=True) template.html ... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/bindfields.js' %}"></script> ... <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> i want when someone selects document_field the document_type selections are filtered accordingly.But the document_type selections was empty when i changed document_field value. -
How to POST Django Inline Formset with images via AJAX
I'm trying to process inline formset with images via Ajax: forms.py class UserDogCreateForm(forms.ModelForm): class Meta: model = UserDog fields = ['name', 'breed', 'gender'] class UserDogImageCreateForm(forms.ModelForm): class Meta: model = UserDogImage fields = ['image', 'dog'] labels = {'image': ''} UserDogCreateFormSet = forms.inlineformset_factory( UserDog, UserDogImage, form=UserDogImageCreateForm, extra=3, can_delete=False, can_order=False, ) views.py class UserDogCreateView(LoginRequiredMixin, CreateView): model = UserDog form_class = UserDogCreateForm def get_context_data(self, **kwargs): context = super(UserDogCreateView, self).get_context_data(**kwargs) if self.request.POST: context['dog_image_inlines'] = UserDogCreateFormSet(self.request.POST, self.request.FILES) else: context['dog_image_inlines'] = UserDogCreateFormSet() return context def form_valid(self, form): context = self.get_context_data() inlines = context['dog_image_inlines'] with transaction.atomic(): if inlines.is_valid(): form.instance.user = self.request.user self.object = form.save() inlines.instance = self.object inlines.save() user_dogs = UserDog.objects.filter(user=self.request.user) return JsonResponse({'form_is_valid': True, 'user_dogs': serializers.serialize('json', user_dogs)}) else: return JsonResponse({'form_is_valid': False}) def form_invalid(self, form): return JsonResponse({'form_is_valid': False}) .html <form id="dog-create-form" enctype="multipart/form-data" action="{% url 'dog-create' %}" method="post"> {% csrf_token %} {{ form }} {{ dog_image_inlines.as_p }} <button type="submit">Submit</button> </form> .js var dogCreateForm = $('#dog-create-form'); dogCreateForm.submit(function(e){ e.preventDefault(); var data = new dogCreateForm.serialize(); console.log(data); $.ajax({ url: '/accounts/dog-create/', type: 'post', dataType: 'json', data: data, success: function(data) { if (data.form_is_valid) { console.log('Dog created!'); // <-- This is just a placeholder for now } else { console.log('Dog not created!') } }, }); }) After submit UserDog data saves, but no images saves in UserDogImage … -
Optimization of querys in django eliminating querys duplicates
I'm trying to get the number of products that have each category, but each category is in turn parent of other categories, so I want to know how many children have that category and their daughter categories, I have simplified the query to the maximum in the following way, but in the django debug I keep showing that I have 66 querys duplicates. How can I eliminate these duplications? With the first line of views.py, he managed to get the number of products in a category, but the problem is essentially to tell him to return me from the category and his daughters. models.py class Categoria(models.Model): nombre = models.CharField(max_length=200) slug = models.SlugField(max_length=100) padre = models.ForeignKey('self', blank=True, null=True, related_name='cat_padre') pub_date = models.DateTimeField('date published', auto_now_add=True) upd_date = models.DateTimeField('date updated', auto_now=True) def __str__(self): return self.nombre + ' ' + self.pais.iso class Producto(models.Model): nombre = models.CharField(max_length=200) slug = models.SlugField(max_length=100) categoria = models.ForeignKey(Categoria) views.py cats = Categoria.objects.annotate(num_productos=Count('producto')).filter(pais__iso=pais, padre__isnull=True).order_by('-num_productos') for c in cats: num_p = Producto.objects.filter(categoria__padre=c).count() c.num_productos += num_p contexto = { 'categorias_padre': cats, } return render(request, 'web/pruebitas/product.html', contexto) Django debug: SELECT COUNT(*) AS "__count" FROM "web_producto" INNER JOIN "web_categoria" ON ("web_producto"."categoria_id" = "web_categoria"."id") WHERE "web_categoria"."padre_id" = '790' Duplicated 62 times. Conexión: default /home/luis/PycharmProjects/lco_web/web/middleware.py in __call__(29) … -
JSON POST with cURL / libcurl function doesnt work
I have a Django Server which receives JSON Data via Post and also returns a JSON via response. I tested my Code with the CURL Command with the terminal of macOS and it works. The command is curl -H "Content-Type: application/json" -X POST -d '{"mac":"24:0a:c4:04:fd:28","battery":"100", "message":"You have a message"}' http://192.168.178.34:8000/kalender/returnjson/ Now I want my microcontroller to send the exact same Post like the curl-Command above. The function is written in C-language. int sendCurl(){ CURL *curl; CURLcode res; curl = curl_easy_init(); char* jsonObj = "{ \"mac\" : \"24:0a:c4:04:fd:28\" , \"battery\" : \"100\" , \"message\" : \"You got a message\"}"; struct curl_slist *headers = NULL; curl_slist_append(headers, "Accept: application/json"); curl_slist_append(headers, "Content-Type: application/json"); curl_slist_append(headers, "charsets: utf-8"); curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.178.34:8000/kalender/returnjson/"); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_global_cleanup(); return res; } But my server doesnt get any incoming POST request. (my server does print outs when receiving something, but its not the case) What is wrong with the code written in C? -
Pass data from php to python and get result
I want to send data from php to python and make some computations. After that I want to send result of that. The problem is I cannot send data from php to python. python.php username is working but shell_exec or python have problem <?php if(isset($_POST["username"])){ $nick = $_POST["username"]; echo shell_exec("python new.py '$nick'"); $jsonData = $_POST["prediction" ]; echo $jsonData; } ?> new.py When I run python it prints C:\wamp\www\MLWebsite\website\new.py but it should be parameter import pymysql.cursors import sys import urllib2, urllib import requests x=sys.argv[0] print x I want to get some idea about sending result because end of new.py mydata=[('prediction','BIO')] mydata=urllib.urlencode(mydata) path='http://localhost/MLWebsite/website/python.php' #the url you want to POST to req=urllib2.Request(path, mydata) req.add_header("Content-type", "application/x-www-form-urlencoded") page=urllib2.urlopen(req).read() print page I use Firebug plugin in Firefox and this error is also shown in webpage. ( ! ) Notice: Undefined index: prediction in C:\wamp\www\MLWebsite\website\python.php on line 6 Call Stack #TimeMemoryFunctionLocation 10.0006245144{main}( )..\python.php:0 -
how can I avoid same account login at the same time in django
I use Django, DRF, and JWT.I want to avoid same account login in mobile App at the same time, mobile App and website can login at the same time. how can I do that? there is package can do this? -
Error during Pip Django Install
Yesterday, I installed Django on my aunt's pc and it worked wonders. Today, I'm trying to install it on my pc, and it gives the following error: Exception: Traceback (most recent call last): File "c:\program files\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_f isolated=self.isolated, File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36-32\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Acceso denegado: 'c:\\program files\\python36-32\\Lib\\site-packages\\pytz' I'm counting on you guys. I'm new to this world, and I'm willing to learn. P.D.: "Acceso denegado" = "Access denied" -
Where do Django model fields reside?
I've looked into the source code for some django model fields, in this case DateTimeField. In the tutorial for Django, we are taught to create a DateTimeField like this: from django.db import models field = models.DateTimeField() But looking in the source code, the file where DateTimeField is defined is django/db/models/fields. So, intuitively, if I were to import the field, I would write from django.db.models.fields import DateTimeField. Do you see the difference? In the tutorial, they import it from django/db/models, while it looks like from the location of the source code that it actually resides in django/db/models/fields. Why doesn't the tutorial way of importing DateTimeField crash? -
DJANGO_SETTINGS_MODULE not recognizing my base module when starting a new project with Virtualenvwrapper
I am starting a new Django project with virtualenvwrapper, and for some reason django-admin does not recognize my settings module: $ mkproject djangotest (djangotest) $ pip install Django Collecting Django Using cached Django-2.0-py3-none-any.whl Collecting pytz (from Django) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, Django Successfully installed Django-2.0 pytz-2017.3 (djangotest) $ django-admin The above command works and gives me the menu of django-admin subcommands. However, when I try to set DJANGO_SETTINGS_MODULE, my new djangotest app is not recognized: (djangotest) $ cd ../ (djangotest) $ django-admin startproject djangotest (djangotest) $ cd djangotest (djangotest) $ ls djangotest manage.py (djangotest) $ export DJANGO_SETTINGS_MODULE=djangotest.settings (djangotest) $ django-admin Traceback (most recent call last): File "/Users/sam/Dropbox/.virtualenvs/djangotest/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File … -
How to refer multiple model object using one model field in django?
Suppose, I have Project and Manager model. class Project(models.Model): name = models.CharField(max_length=50) class Manager(models.Model): name = models.CharField(max_length=50) projects = This would be array of Project object. But how can I implement this? PostgreSQL has ArrayField for this implementation. But I want a solution that will work for any database. Any alternative solution would be highly appreciable. -
could not use custom templatetags in Django 2.0
I'm using Django 2.0. I have written few custom template tags to use in the template inside notes/templatetags/note_tags.py file where notes is app directory I have written few custom tags inside this file from django import template from django.template.defaultfilters import stringfilter from notepad.utils import simplify_text from notes.models import Note, ColorLabels register = template.Library() @register.filter(name='note_simplify') @stringfilter def note_simplify(value): return simplify_text(value) @register.filter(name='default_color_label') def default_color_label(): default_label = ColorLabels.objects.filter(default=True).first() print(default_label.value) return default_label and inside the template file, I have loaded the tag as {% load note_tags %} I'm able to use the first tag note_simplify but second tag default_color_label is not being called. I'm using both tags in the same file. One for modifying the passed data and another to simply print something # modify the note.content <p>{{ note.content|truncatechars:200|note_simplify }}</p> # to print some value {{ default_color_label.value }} I have also restared server many times. Is there something wrong? Why the tag is not being called in template? -
TypeError: object of type 'EmailMultiAlternatives' has no len()
Django app, sending an email using a script (using runscript), only on weekdays. Trying to use Google's STMP. Here's the relavent script: import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labschedule.settings") django.setup() import datetime from datetime import date import smtplib from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from labschedule import settings def run(): today = date.today() subject = "Daily Report for %s" % today to = [settings.EMAIL_ADMIN] from_email = 'blahblah@gmail.com' # My email reservations = Event.objects.filter(day=today).order_by('cart') last = Event.objects.latest('day') if today >= today + datetime.timedelta(days=5): countdown = last - datetime.timedelta(today) warning = "Hey! You run out of open slots in %s days" % countdown else: warning = None ctx = ({ 'reservations' : reservations, 'warning' : warning, 'cart_choice' : cart_choice }) html_content = render_to_string('schedule/email.html', ctx) text_content = render_to_string('schedule/email.html', ctx) msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email) msg.attach_alternative(html_content, "text/html") weekend = set([5, 6]) # Python week starts on Monday as 0 if today.weekday() not in weekend and settings.DAILY_EMAIL == True: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(settings.gmail_user, settings.gmail_password) server.sendmail(from_email, to, msg) server.close() print ('Email sent!') else: pass I went mostly of the tutorial here. The error I receive: TypeError: object of type 'EmailMultiAlternatives' has no len() I'm newish, and I know it's something dumb, and would … -
Django uses default reset form instead of my Html
I'm new in Django. Have urlpatterns = [ path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout_then_login, name='logout'), path('reset/', auth_views.password_reset, name='reset'), path('reset/done', auth_views.password_reset_done, name='password_reset_done'), path('reset/<slug:uidb64>/<slug:token>/', auth_views.password_reset_confirm, name='password_reset_confirm'), path('reset/done/', auth_views.password_reset_complete, name='password_reset_complete'), ] in my urls.py and have password_reset_done.html and other files at accounts/templates/registration. But Django uses deafult form for reset, but use my login.html from the same directory. What am i doing wrong? Thanks! -
NoReverseMatch: Reverse for 'detail' not found. (Django Tutorials)
I've been going through the Django 2 tutorials. I got the following error: #Error: #django.urls.exceptions.NoReverseMatch #django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern #name. Did some googling and confirmed that I had named my view 'detail' and also had my app named. Below are my codes. Please tell what is wrong. I am following the tutorial by heart, but this came up. How can I fix it keeping in par with the tutorials? Thank you! Files: mysite/polls/templates/polls/index.html {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} mysite/polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), # ex: /polls/ # path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/polls/views.py def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) Additional: mysite/urls.py urlpatterns = [ path('polls/', include('polls.urls', namespace='polls')), path('admin/', admin.site.urls), ] -
How to annotate queryset with another queryset
Now I'm trying to build complex queryset that uses annotations with conditional related queries. I have the following models: class MenuItemCategory(CreateUpdateModel): name = models.CharField(max_length=255, blank=True, null=True) class MenuItem(CreateUpdateModel): category = models.ForeignKey(MenuItemCategory, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) class LineItem(models.Model): order = models.ForeignKey(Orders, blank=True, null=True) menu_item = models.ForeignKey(MenuItems, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=3) amount = models.DecimalField(max_digits=10, decimal_places=2) class Order(CreateUpdateModel): waiter = models.ForeignKey(Employees, blank=True, null=True) guests_count = models.IntegerField(blank=True, null=True, default=0) closed_at = models.DateTimeField(blank=True, null=True, db_index=True) class Employees(CreateUpdateModel): restaurant = models.ForeignKey(Restaurants, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) My goal is to build json with following scheme: [ { employee_name: 'Jane', menu_item_categories: [ { name: 'Drinks', line_items_quantity: 10, //times when this waiter brings any item from this category to the customer at the period amount: 49.00, // price of all drinks sold by this waiter at the period menu_items: [ name: 'Vodka', amount: 1.00, line_items_quantity: 4, # times when this item has been ordered for this waiter at the period ] } ], visits: 618, guests: 813, cycle_time: 363 } ] With following serializer: class EmployeeSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=255) visits = serializers.SerializerMethodField() guests = serializers.SerializerMethodField() cycle_time = serializers.SerializerMethodField() menu_item_categories = serializers.SerializerMethodField() def get_visits(self, obj): # works def … -
Django many-to-many, display in admin
Please help to understand how to display list of groups in Django admin Person instance in this case: class Person(models.Model): name = models.Charfield(max_length=120) class Group(models.Model): title = models.Charfield(max_length=120) persons = models.ManyToManyField(Person) -
Pass date range in URL in Django Rest
I have a JSON structure like, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] I am using Django Rest Framework. Whenever, I do a GET request to, localhost/namelist/{{name}}/ is returns the JSON where "name": "ab" . Now, I want to return JSON based on date range. I will pass the start date and end date in the url and it should return the value within that specific date range, time should be ignored. Also, we have to consider months also, not only dates. Here, in this example, month is same but in real scenario months might be different. Like, localhost/namelist/{{name}}/{{start_date}}/{{end_date}}/ If the URL is , localhost/namelist/abcd/2017-12-17/2017-12-19/ then it should return, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] views.py :- def get_queryset(self): param = self.kwargs.get('pk') param2 = self.kwargs.get('ak') return namelist.objects.filter(name=param, date = param2) urls.py :- urlpatterns = { url('^namelist/(?P<pk>[\w\-]+)/(?P<ak>[\w\-]+)/$', ListViewParam.as_view()), } I can pass the date in the URL, but what the recommended way to pass the date range ? -
Extract data from range with both empty and filled data
My problem is i need the objects from certain range date . In that i am having filled data for some dates and for some dates there is no data. For one date one form ,if user fill the form and submit then it will store for that date rows = Grades.objects.filter( user_ql__created_at__range=(from_date, to_date).order_by('-user_ql__created_at').values() when I print length of rows I got only 5 objects . Actually the date range is 7 days I am getting only 5 dates object because in that date range only 5 date are filled remaining 2 dates are not filled i need to show that all the objects of rows which are filled not filled dates also -
django cannot connect mysql in docker-compose
I'm very new for docker, now I am trying to run django with mariadb in docker through docker-compose, but I always get this error: I use Docker version 17.09.1-ce, build 19e2cf6, docker-compose version 1.18.0, build 8dd22a9 django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'mariadb55\' (111 "Connection refused")') I can connect db correctly after run docker-compose up db in local or remote, and I even can run python manage.py runserver 0.0.0.0:6001 correctly in anaconda virtual environment to connect db service in docker by setting parameters of settings.py file like below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'belter', # 'HOST': 'mariadb55', 'HOST': '127.0.0.1', 'PORT': '3302', 'PASSWORD': 'belter_2017', 'default-character-set': 'utf8', 'OPTIONS': { 'sql_mode': 'traditional', } } } This is my docker-compose.yml file version: '3' services: db: image: mariadb:5.5 restart: always environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 - MYSQL_ROOT_HOST=% - MYSQL_DATABASE=test - MYSQL_USER=belter - MYSQL_PASSWORD=belter_2017 - MYSQL_ROOT_PASSWORD=123456_abc volumes: - /home/belter/mdbdata/mdb55:/var/lib/mysql ports: - "3302:3306" web: image: onlybelter/django_py35 command: python3 manage.py runserver 0.0.0.0:6001 volumes: - /mnt/data/www/mysite:/djcode ports: - "6001:6001" depends_on: - db links: - db:mariadb55 I almost tried everything I can find, but still cannot figure it out, any help would be nice! What I have tried: Docker compose mysql connection failing … -
Why will django form not summit data to dabase but instead displays result as a url on the broswer
When ever i summit my Django form from the template .I get the result bellow http://127.0.0.1:8000/Search_match_distributors/?csrfmiddlewaretoken=3rDq624irqw2L0WDQCvzFHM5pAux3ep9cXWTeKQ4WlNyd5JWJxQrHVfBOLAPMHI1&CompanyRegisteredName=unine&CompanyRegisteredState=weqeqqw&CompanyRegisteredAddress=qewq&CompanyRegisteredCity=qwqw&CompanyEmail=qweq%40yahoo.com&Country=Belize&RegisteredCompanyType=corperation&title=SeaFood&YouOwnBusiness=Yes&AreaCode=%2B375&WorkPhone=121212&TypeOfDistributorPrefered=IntensiveDistributors data to save in saver is displayed on the browser instead . Does someone has an idea why such happens. My code in views.py ,form.py and model.py and url.py has no error -
Allow staff user to only read the data
I want to allow the staff users to view (read only)the transaction data. But when I login as a staff user, it displays 'You don't have permission to edit anything.' and rest of the page is blank. models.py #models.py from django.db import models from django.contrib.auth.models import Permission, User from django.core.validators import RegexValidator # Create your models here. alphanumeric = RegexValidator(r'^[0-9a-zA-Z-]*$', 'Only alphanumeric characters and "-" are allowed.') TransactionTypes = ( ('P','Purchase'), ('S','Sell'), ) class Transactions(models.Model): client_name = models.OneToOneField(User(is_staff=True)) transaction_type = models.CharField(choices=TransactionTypes,max_length=1) amount = models.IntegerField() transaction_id = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric]) class Meta: permissions = ( ('read_item','Can read item'), ) Admin.py- #admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Transactions # Register your models here. class TransactionAdmin(admin.ModelAdmin): #list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') list_display = ('client_name', 'transaction_type', 'amount', 'transaction_id') def get_readonly_fields(self, request, obj=None): if not request.user.is_superuser and request.user.has_perm('transactionss.read_item'): return [f.name for f in self.model._meta.fields] return super(TransactionAdmin, self).get_readonly_fields( request, obj=obj ) admin.site.register(Transactions, TransactionAdmin) -
Can I change the related_name when I get the nested data in Django-Rest-Framework?
Such as I have two Model, the first is the second's ForeignKey. class MyModel(models.Model): firstDate = models.DateTimeField(auto_now_add=True) another = models.CharField(max_length=30) class MySubModel(models.Model): name = models.CharField(max_length=12) my_model = models.ForeignKey(to=MyModel, related_name="mysubs") In the MyModelSerializer it should be: class MyModelSerializer(ModelSerializer): mysubs = MySubModelSerializer(many=True, read_only=True) class Meta: model = MyModel fields = "__all__" The result will be like bellow: [ { "firstDate":xxxx, "another":xxxx, "mysubs":[ { "name":xxx, } ] } ] I want to replace the key mysubs to children, is it possible to do that? -
How do I access the properties of a many-to-many relationship
How do I access the properties of a many-to-many relationship? and on model. class Courses(models.Model): courses_name = models.CharField(max_length=100) duration = models.CharField(max_length=100) def __str__(self): return u'%s' % (self.courses_name) class Meta: verbose_name_plural = 'Courses' verbose_name = 'Courses' class EducationEntity(models.Model): name = models.CharField(max_length=100) type = models.ForeignKey(EducationEntityType) location_type = models.ForeignKey(LocationType) institute_type = models.ForeignKey(InstituteType) course = models.ManyToManyField(Courses) established=models.DateField(default=datetime.date.today) approved_by=models.CharField(max_length=200) college_facilities=models.CharField(max_length=200) image = models.ImageField(upload_to='images/',default="none") def __str__(self): return u'%s' % (self.name) class Meta: verbose_name_plural = 'Education Entity' verbose_name = 'Education Entity' @property def course_(self): # import ipdb; # ipdb.set_trace() amount='' data = [] duration='' interest_rate='' loan=[] for i in self.course.all(): try: for cou in EducationEntityCourses.objects.filter(course=i): for l in LoanDetails.objects.filter(education_entity_courses__course=i): amount=l.amount for lo in LoanTenure.objects.filter(loan_details__education_entity_courses__course=l): loan.append({"duration": lo.duration,"interest_rate": lo.interest_rate}) except Exception as e: amount='' import ipdb; ipdb.set_trace() data.append({ "courses_name": i.courses_name, "duration":cou.duration, "course_type":cou.course_type, "tution_fees":cou.tution_fees, "hostel_fees":cou.hostel_fees, "other_fees":cou.other_fees, "amount":amount, "loan":loan }) import ipdb; ipdb.set_trace() return data class EducationEntityCourses(models.Model): education_entity = models.ForeignKey(EducationEntity) course = models.ForeignKey(Courses) duration = models.CharField(max_length=100) course_type = models.ForeignKey(CourseType) tution_fees = models.CharField(max_length=100) hostel_fees = models.CharField(max_length=100) other_fees = models.CharField(max_length=100) def __str__(self): return u'%s, %s' % (self.education_entity.name, self.course.courses_name) class Meta: verbose_name_plural = 'Education Entity Courses' verbose_name = 'Education Entity Courses' class LoanDetails (models.Model): education_entity_courses = models.ForeignKey(EducationEntityCourses) # training_coaching=models.ForeignKey(TrainingCoaching,blank=True,null=True) amount = models.CharField(max_length=100) def get_course(self): """ get course name :return: """ return self.education_entity_courses.course.courses_name get_course.short_description="Course Name" … -
Django database routing on request.user
Is it possible to get the user object in Django router class? I'm trying to route query on a database based on the type of user. Is it even possible? Thank you -
How can I run one-off dyno inside another one-off dyno on Heroku using custom django-admin commands?
I need to create one-off dyno in Django application deployed on Heroku using custom django-admin commands. I want to use Heroku Scheduler to run command heroku run python manage.py test_function2. It creates one-off dyno with running function test_function2 in it. Then I would like to use test_function2 function to create more one-off dynos. I added example code below. My problem is associated with line command = 'heroku run:detached myworker2' When I use command = 'heroku run:detached myworker2' in test_function2 I get error sh: 1: heroku: not found. Does anyone have an idea how can I create heroku one-off dyno when I am already in one? test_function2: class Command(BaseCommand): def handle(self, *args, **options): command = 'heroku run:detached myworker2' os.system(command) Procfile: web: sh -c 'gunicorn backend.wsgi --log-file -' myworker2: python manage.py test_function2 myworker2: python manage.py test_function