Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving to database with one query
I have standard django User model and I have an extended model Member. The Member model is connected to Subscription model. class Type(models.Model): limit = models.IntegerField() name = models.CharField(max_length=50) default = models.BooleanField() def __str__(self): return self.name class Subscription(models.Model): started = models.DateField() type = models.OneToOneField(Type) def __str__(self): return self.type.name class Member(models.Model): user = models.ForeignKey(to=User) number = models.CharField(max_length=10) match_code = models.CharField(max_length=50) parent = models.ForeignKey("self", null=True, blank=True) name = models.CharField(max_length=100) address = models.CharField(max_length=255) postcode = models.CharField(max_length=10) city = models.CharField(max_length=100) country = models.ForeignKey(to=Country, null=True) language = models.ForeignKey(to=Language) telephone = models.CharField(max_length=50) mobile = models.CharField(max_length=50) main_email = models.EmailField(null=True, blank=True) active = models.BooleanField() subscription = models.ForeignKey(Subscription) def __str__(self): return self.name When I create a new user, and when I want to save it to database I do it as follows : language = Language.objects.get(key="EN") country = Country.objects.get(key="BE") # Add to user model user = User() user.username = request.POST['email'] user.first_name = request.POST['firstname'] user.last_name = request.POST['lastname'] user.email = request.POST['email'] user.set_password(request.POST['password']) user.save() # Add subscription subscription = Subscription() subscription.started = datetime.date.today() subscription.type = Type.objects.filter(default=True) last_subscription = Subscription.objects.all().order_by('-id')[0] # Get the last field from user model last_user = User.objects.all().order_by('-id')[0] # Add to member model with the last user member = Member() member.number = request.POST['member_id'] member.address = request.POST['address'] member.postcode = request.POST['postcode'] member.city … -
Mysql error on Django
I am trying to export a csv file after a mysql query. I get the following error; (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1") import csv from django.db import connections from django.http import HttpResponse from django.views.generic import ListView from testing.models import TrRunSummary, TrDetails class ExportCsv(ListView): """Displays the different tests performed on the specified test request""" template_name = 'testing/tr_export_csv.html' context_object_name = 'export_csv' def get_context_data(self, **kwargs): context = super(ExportCsv,self).get_context_data(**kwargs) context['tr_info'] = self.tr_info() return context def get_queryset(self): qtr_id = self.kwargs['trID'] s = str(qtr_id) print s print type(s) cursor = connections['default'].cursor() query ="SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, " "test_functionality.test_functionality_code, test_cases.test_case_no, " "SCRIPT.option_name AS script_result, POST.option_name AS post_result, " "results_tests.started, results_tests.stopped, results_tests.test_duration, builds.baseline, " "builds.build_type, stb_hw_info.stb_type, defects.defect_name, parser_output, log_url, " "script_health_score, post_health_score FROM results_stbs " "JOIN tr_test_cases " "ON tr_test_cases.tr_test_case_id=results_stbs.tr_test_case_id " "JOIN test_cases " "ON test_cases.test_case_id=tr_test_cases.test_case_id " "JOIN test_functionality " "ON test_functionality.test_functionality_id=test_cases.test_functionality_id " "LEFT JOIN stb_inv " "ON results_stbs.stb_id=stb_inv.stb_id " "LEFT JOIN result_options AS SCRIPT " "ON results_stbs.script_result=SCRIPT.result_option_id " "LEFT JOIN result_options AS POST " "ON results_stbs.post_result=POST.result_option_id " "JOIN results_tests " "ON results_stbs.results_test_id=results_tests.results_test_id " "JOIN builds " "ON builds.build_id=results_stbs.build_id " "JOIN stb_hw_info_ids " … -
nginx django uwsgi page not found error
I am trying to setup uswgsi and django on nginx but showing page not found error and errorlogs are empty . I cannot identify the error because error logs empty erro log path /var/log/nginx/error.log -rw-r--r-- 1 www-data root 0 Feb 26 12:31 error.log uswgi is running properly because i tested this on following method uwsgi --http :8080 --home /home/flybegins/python/django/venv/ --chdir /home/flybegins/python/django/sample -w sample.wsgi virtual host server { listen 80; server_name test.aaaaaaa.com; error_log /var/log/nginx/error.log location /static/ { root /home/flybegins/python/django/sample/ } location / { include uwsgi_params; uwsgi_pass unix:/home/flybegins/python/django/sample/sample.sock; } } Virtual host permission -rw-r--r-- 1 root root 333 Feb 27 08:54 test.aaaa.com Thanks advance -
Django OneToOneRelation
I have three models in django as follows : class Type(models.Model): limit = models.IntegerField() name = models.CharField(max_length=50) default = models.BooleanField() def __str__(self): return self.name class Subscription(models.Model): started = models.DateField(auto_now=True) type = models.OneToOneField(Type) def __str__(self): return self.type.name class Member(models.Model): user = models.ForeignKey(to=User) address = models.CharField(max_length=255) active = models.BooleanField() subscription = models.OneToOneField(Subscription) def __str__(self): return self.name I want that one member can have only one subscription and that one subscription can have only one type. But when I try to create a member with a subscription type that already exists, I get an error. I could maybe do it as follows : class Member(models.Model): user = models.ForeignKey(to=User) address = models.CharField(max_length=255) active = models.BooleanField() def __str__(self): return self.name class Subscription(models.Model): started = models.DateField(auto_now=True) member = models.OneToOneField(Member) class Type(models.Model): limit = models.IntegerField() name = models.CharField(max_length=50) default = models.BooleanField() subscription = models.OneToOneField(Subscription) def __str__(self): return self.name But then I cannot choose subscription when I try to add a member in django admin. Any advice? -
Automatically set logged-in user as the author in django using createview and modelform
I am building a frontend form that allows someone to post an article without accessing the admin. When the user is logged in, I would like for him/her to be able to write an article. Upon saving, I would like that user to automatically be set as the author of the article. models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone class Article(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=65) text = HTMLField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class ArticleImage(models.Model): image = CloudinaryField('image') image_name = models.CharField(max_length=55, default='') article = models.ForeignKey(Article) def __str__(self): return self.image_name class ArticleTag(models.Model): slug = models.SlugField(max_length=50, unique=True) article = models.ForeignKey(Article) def __str__(self): return self.slug class ArticleCategory(models.Model): slug = models.SlugField(max_length=20, unique=True) article = models.ForeignKey(Article) def __str__(self): return self.slug forms.py class ArticleCreationForm(ModelForm): class Meta: model = Article fields = ['title', 'text'] widgets = { 'title': forms.TextInput(attrs={'placeholder': 'Please add a title. Max: 65 characters'}), 'text': forms.Textarea(attrs={'cols': 80, 'rows': 40, 'placeholder': 'Starting typing your article...'}) } ArticleImageFormSet = inlineformset_factory(Article, ArticleImage, fields=('image', 'image_name',), extra=1, max_num=1, widgets={'image_name': forms.TextInput(attrs={'placeholder': 'Image name'})}) ArticleTagFormSet = inlineformset_factory(Article, ArticleTag, fields=('slug',), extra=1, max_num=1) ArticleCategoryFormSet = inlineformset_factory(Article, ArticleCategory, fields=('slug',), extra=1, max_num=1) … -
How to intercept all read queries to DB in Django?
I need to intercept all queries to DB and write them to the file log. So, if base operations like DELETE, UPDATE and CREATE I can intercept with signals framework. But what about READ queries? How can I catch them with signals? -
customise Authentication model in django?
i am trying to implement authentication mechanism for my project. but django has admin authentication mechanism. and i want to trying to get username and password from my model database not from django admin User model.so anyone have the solution for this -
Trouble retrieving data from REST endpoint using Angular -- URL keeps showing static/
I'm currently having an issue that has been driving me crazy for the past 30-40 mins. I've successfully created a products api using Django/Django REST framework. But when I call the endpoint to try and consume it with angular, I get a 404 error. When I open the console I am greeted with an error that states GET http://localhost:8000/static/api/products/ 404 (Not Found). However, when I navigate to the URL manually in browser I get the browsable api menu. I'm not exactly sure what's going on here...but I'm thinking it could be because of my angular static URLs/roots. Here is the current code for the main area URLs of the app: from django.conf.urls import url,include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('customerreview_rest.urls', namespace='api')), url(r'^api/',include ('products_rest.urls', namespace='api')), url(r'^', include('GemStore_App.urls',namespace='frontend')), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) Here is the products URL/root for the endpoint: from django.conf.urls import url,include from rest_framework import routers from products_rest.viewsets import ProductsViewsets router = routers.DefaultRouter() router.register('products',ProductsViewsets,'products') urlpatterns = [ url(r'^', include(router.urls)) #base router ] Lastly, here is the code for the static angular files: from django.conf.urls import url, include from django.views.generic.base import RedirectView urlpatterns = [ url(r'^$', RedirectView.as_view(url='static/index.html', … -
django template, String managment
I have several template that use limited number of string many times, so I'm thinking of reusing strings in some way instead of hard coding in templates. I found two way, but both of them has limitation, so I'm asking of better way to do this or probably standard way to managing String in Django templates. first and simply: storing them in Database, it work good if i create simple model below and send all of them in views (about 500 objects), for all rendered template. further more I can categorize them, and send just related category in each template class Subject(models.Model): key = models.CharField() trans = models.TextField() type = models.SmallIntegerField(choices=string.types) pros: simplicity even users with admin access can manage them, and there is no need to me for changing simple text can store translation (for future, if more languages needed) Cons: increasing database access fear of unknown security issues two: using {% with x="done" %} tag I can use "with" tag in base template, and extend it in other templates, so i have access to all of tag with standard django. pros: simple no DB access probably safe Cons: with tag need all of it its entry in one … -
Django debug toolbar shows multiple duplications
Django Debug Toolbar shows multiple duplications in 'get_username' custom_tag. I've learned select_related hits database few times, but it didn't change multiplication issue. Same result. here is the code: @register.filter(name='get_username') def get_username(value): #Test1 p = User.objects.select_related('scans').get(id=value) username = p.username print username return username #Test2 return User.objects.filter(id=value).values_list('username',flat=True)[0] -
Render an html page that shows data present in other files of that directory on demand
I have a certain file which has the following structure: dir1/ index.html dir2/ info dir3/ info The index.html renders graphs for data in dir2 and dir3. dir1 is available as a tar file on a specific external server. My django app needs to download this tar file on request and render index.html. How do I go about this? -
how to show progress bar using boto in django templates
I am using boto to upload file on s3.I want to show progress bar in django templates about file upload status.I have tried django progress bar module but it's not working. -
Filtering using URL with DRF
I am trying to do basic filtering using my URL. I have tried several solutions without success. Please propose a straight forward solution. Here is my code: Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) level = models.IntegerField("Level", null=True, blank=True) Views.py class TagFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(owner=request.user) Urls.py router.register(r'tag', TagViewSet) I want to be able to filter like this: xyz.com/tag?level=40/ To display all items with a level of 40 only. Using django-filter (not to be mistaken for DjangoFilterS), I created a new filters.py file. However, the results never get filtered. When I hit the API url, it just gives me all results. Filter.py from rest_framework import generics from django_filters import rest_framework as filters from Tril.models import Tag from .serializers import TagSerializer class TagFilter(filters.FilterSet): min_price = filters.NumberFilter(level="level", lookup_expr='gte') max_price = filters.NumberFilter(level="level", lookup_expr='lte') class Meta: model = Tag fields = ['taglevel', 'name'] class ProductList(generics.ListAPIView): queryset = Tag.objects.all() serializer_class = TagSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = TagFilter -
UnicodeDecodeError when use django
Traceback (most recent call last): File "/usr/lib/python2.7/SocketServer.py", line 596, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 99, in __init__ super(WSGIRequestHandler, self).__init__(*args, **kwargs) File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__ self.handle() File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 176, in handle self.rfile, self.wfile, self.get_stderr(), self.get_environ() File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 150, in get_environ if '?' in path: UnicodeDecodeError: 'utf8' codec can't decode byte 0xa8 in position 28: invalid start byte help,please.I dont konw how to solve this problem I tried to search , but no answer -
django+celery+ansibleApi return None
python call ansibleApi with celery return None,I have searched a few days.It works well with call deploy function without celery ,but with celery my code call ansibleApi return None. reproduce steps. 1.tasks.py from celery import shared_task from .deploy_tomcat2 import django_process @shared_task def deploy(jira_num): #return 'hello world {0}'.format(jira_num) #rdb.set_trace() return django_process(jira_num) 2.deploy_tomcat2.py from .AnsibleApi import CallApi def django_process(jira_num): server = '10.10.10.30' name = 'abc' port = 11011 code = 'efs' jdk = '1.12.13' jvm = 'xxxx' if str.isdigit(jira_num): # import pdb # pdb.set_trace() call = CallApi(server,name,port,code,jdk,jvm) return call.run_task() 3.AnsibleApi.py #!/usr/bin/env python import logging from .Logger import Logger from django.conf import settings from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars import VariableManager from ansible.inventory import Inventory from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.plugins.callback import CallbackBase Log = Logger('/tmp/auto_deploy_tomcat.log',logging.INFO) class ResultCallback(CallbackBase): def __init__(self, *args, **kwargs): super(ResultCallback ,self).__init__(*args, **kwargs) self.host_ok = {} self.host_unreachable = {} self.host_failed = {} def v2_runner_on_unreachable(self, result): self.host_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs): self.host_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs): self.host_failed[result._host.get_name()] = result class CallApi(object): user = settings.SSH_USER ssh_private_key_file = settings.SSH_PRIVATE_KEY_FILE results_callback = ResultCallback() Options = namedtuple('Options', ['connection', 'module_path', 'private_key_file', 'forks', 'become', 'become_method', 'become_user', 'check']) def __init__(self,ip,name,port,code,jdk,jvm): self.ip = ip self.name = … -
Django. How to add an extra field in User model and have it displayed in the admin interface
I'm learning Django and need some help. I need to include an extra boolean field in my User Model (auth_user table in the db I believe) and have it be displayed in the admin interface when managing users, like the staff status field in this image... 127:0.0.1:8000/admin/user : https://i.stack.imgur.com/f26vR.png and... 127.0.0.1:8000/admin/auth/user/2/change/ : https://i.stack.imgur.com/bPq6o.png I'm unsure on how to approach this. I understand I'll have to extend the AbstractUser model and then perhaps manually add the field into the db, but then how do I update the new field for the view, form and templates for the admin interface? Will I have to rewrite the django admin source code for all of these or is there an simpler way? -
Remove keys' quotes of a dictionary in template
I am creating this dictionary in the view : [{'data': [[1487635200000.0, 665270], [1487376000000.0, 665073]], 'name': 'page_fans' }, {'data': [[1487635200000.0, 170100], [1487376000000.0, 170100]], 'name': 'page_posts_impressions' }] I would like to pass it to my javascript code in the template, i need to have it in this format : [{data: [[1487635200000.0, 665270], [1487376000000.0, 665073]], name: 'page_fans' }, {data: [[1487635200000.0, 170100], [1487376000000.0, 170100]], name: 'page_posts_impressions' }] Basically, how can I remove the quotes only from the keys ? (note that i need to keep the quotes for the name value). -
Django: TypeError: 'datetime.date' object has no attribute 'get'
I have TransactionForm as follows: class TransactionForm(ModelForm): start_date = forms.DateField(widget=SelectDateWidget) duration = forms.ChoiceField(choices=duration_choices) class Meta: model=Transaction fields=( 'start_date', 'duration', ) def clean(self): date = self.cleaned_data.get("start_date") if date < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return date It has a method clean which checks if date entered is at least todays or greater. When some date in past is inserted it shows error on remplate as expected. But when a valid date is entered, I get the following error. 'datetime.date' object has no attribute 'get' Here is my view.py file def packages(req): if req.method == 'POST': form = completeForm(req.POST) tf = TransactionForm(req.POST) if tf.is_valid(): return HttpResponse("Some page") else: errorList = tf.errors['__all__'] args={'form':form, 'errors':errorList, 'tf':tf} return render(req,'main/common/packages.html',args) else: form = completeForm() tf = TransactionForm() args={'form':form, 'counter':1, 'tf':tf} return render(req,'main/common/packages.html',args) If I remove clean method from form it works fine but I need to validate date without using JavaScript validation. I found this question closest to mine but its solution is not working or me. Could you please what am I doing wrong? -
Marshmallow Nested Serializer KeyError: u'Manager'
I'm using Marshmallow's nested serializers and getting the error "KeyError: u'manager'". Here's my code: class ShiftSerializer(Schema): agent = fields.String() date = fields.String() end = fields.String() status = fields.String() class KPIShiftSerializer(Schema): interval = fields.DateTime() incoming = fields.Integer() duration = fields.Decimal() shifts_future = fields.Nested(ShiftSerializer, many=True) shifts_current = fields.Nested(ShiftSerializer, many=True) shifts_ending = fields.Nested(ShiftSerializer, many=True) Thank you in advance for the help =)! -
how to explode text from excel in django?
I have a problem while import file excel into django model. I have a file excel with one column, and i want to explode its text then input it to two field in my django models. this is my views def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( model=Transaksi, mapdict=['Keterangan', 'Code'], ) return HttpResponse("OK", status=200) else: return HttpResponseBadRequest('Gagal Upload') else: form = UploadFileForm() return render(request, 'kastransaksi/transaksi_formupload.html', {'form': form}) and this is my column in excel keterangan (column name) 944448800010303287-SPP Syarifah Najla 944448800010303275-SPP Miftakhul Ihyaril Ulum -
issue with running Django server
I get an error when running Django. When I run Django in local mode using the runserver command video files are not loaded in the browser. An error occurred trying to load the resource. All other static files serve fine such as images, javascript and css. -
Django ORM and pre_init signal
I have a class which has two children def MyChild1(models.Model): attr1 = models.CharField(default='default value') def MyChild2(models.Model): pass def MyParent(models.Model): child1 = models.ForeignKey(Child1) child2 = models.ForeignKey(Child2) In my package, I require the value of attr1 - and in order to make sure it exists, I initialize the parent with a signal: def init_my_parent(sender, *args, **kwargs): child1 = MyChild1() child2 = MyChild2() signals.pre_init.connect(init_my_parent,sender=MyParent) This seems to work fine to ensure that child1 and child2 are always instantiated. However, even when I manually set child1 and child2 (my_parent.child1 = child1 etc), child1_id and child2_id do not get set and the db throws an error django.db.utils.IntegrityError: NOT NULL constraint failed: myparent.child1 I'm wondering what is causing this behavior? Somehow connecting that signal is causing a problem, but I'm not sure why. Both of the values set in init_my_parent should be overwritten, and thus it shouldn't have an effect? -
Error during WebSocket….Unexpected response code: 404 + Django Channels + Deploy AWS
I'm trying to deploy my project on AWS(Django Channels), it run very well on my local; but not in production enviroment. I created my chat using the Channels examples's @andrewgodwin here and to deploy I was using this documentation My Daphne is runing very well, according the last documentation; I created a Redis's cluster(Amazon ElastiCache) and I called redis; but I don''t know if I have to make any change on the setting to indicate it; or something. Please, help me, I don't have more ideas. Thanks you very much!!! -
custom template not working in django formtools
I have been trying to add a multi page form in my Django application using the formtools wizard. I need to setup custom forms for each step. There are 2 steps in total. Here is the code that I have: views.py TEMPLATES = {"initial": "my_app/form_initial.html", "final": "my_app/form_last.html"} class ModelCreateView(SessionWizardView): model = MyModel template_name = "my_app/model_form.html" file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'custom')) def get_template_names(self): return [TEMPLATES[self.steps.current]] my_app/model_form.html {% extends "my_app/base.html" %} {% block extra_css %} {{ wizard.form.media }} {% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ wizard.management_form }} <h1>{{ wizard }}</h1> {% if wizard.form.forms %} <h1>{{ wizard.form.forms }}</h1> {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} <input type="submit" value="submit"/> </form> {% endblock content %} my_app/form_initial.html <-- custom form template for step 1 --> my_app/form_last.html <-- custom form template for step 2 --> if I understand it correctly, the custom form templates will replace the {{ form }} tag in the base template being called(my_app/model_form.html). My problem here is that, with the current code, the my_app/form_initial.html is being called directly. Also if I try to just include {{ wizard.management_form }} in my_app/form_initial.html … -
how do I sort the queryset by a property's property? django
I have a function which returns a queryset but now I would like to sort the queryset but I am not sure how this can be done. def get_queryset(self): print('--------------------------------') # print(self.request.basket.all_lines()[0].product.upc) print('--------------------------------') return self.request.basket.all_lines() self.request.basket.all_lines() would return me a queryset but I would like to sort it by it's product's upc I am able to get the upc by print(self.request.basket.all_lines()[0].product.upc) I made sure that .product.upc does exist and I am in the right direction. Can someone please give me a hand?