Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create intermediate model object, by connect patient, treatment, disease, and symptom objects
I am creating a medical app and I have a intermediate model that I use the connect that patient, treatment, disease, and symptom objects. Problem : After the set of all patient, treatment, disease, and symptom objects have been created, I cannot connect them to create the consultation object in the appropriate order. Using the shell I was able to connect them u1 = User.objects.create(email='qeng@gmail.com') p1 = Patient.objects.create(NIS='I902456',first_name='Andre',last_name='iivri', contact='908-2456',born='1991-02-15',gender='Male',email_address='dlt@gmail.com', location='Quey',user=u1) p1.save() c1 = Consultation.objects.create() p1.consultation_set.add(c1) s1 = Symptom.objects.create(identity='id',description='des') s1.consultation_set.add(c1) d1 = Disease.objects.create(identity='id', description='desc') d1.consultation_set.add(c1) When I attempt to replicate this with each view in my views.py document I just keep creating a new consultation object which is not what I want to do. This is the code views.py ++++++++++ Imports from script.models import Treatment, Symptom, Disease, Consultation, Patient from django.shortcuts import render, redirect from django.views.generic import CreateView, ListView, DetailView, TemplateView from script.forms import IdentityForm, ConditionForm, DiseaseForm, TreatmentForm Create Patient view class IdentityCreate(CreateView): template_ = 'script/patient_form.html' def get(self, request): document = IdentityForm() patient = Patient.objects.filter(user = request.user) context = {'form':document, 'patient':patient} return render(request, self.template_, context) def post(self, request): document = IdentityForm(request.POST) patient_medical_id = None if document.is_valid(): patient_document_authentication = document.save(commit=False) patient_document_authentication.user = request.user patient_document_authentication.save() # Creates consultation object patient_consult = Consultation.objects.create() #Add … -
passing value to get_context_data from Django template
I am working on a Django template associated with a particular model. Within the view for this template, I am trying to access a record from a different model (Terms containing scientific terms), based on the parameter I would pass in the template. I tried being using get_context_data to query a random term in the database, and then use a custom filter tag to replace the term to the one I want from within the template. Django is smarter, though and wouldn't let me do that. Currently, I am trying to define the context within my views.py class ArticlesView(DetailView): model = models.Articles template_name = 'web/articles-details.html' context_object_name = 'Articles_details' def get_context_data(self, *args, **kwargs): ctx = super(ArticlesView, self).get_context_data(*args, **kwargs) ctx['featured']=Articles.objects.filter(featured=True) ctx['term','arg']=Articles.objects.filter('slug'=='arg') return ctx In the above code, the 'featured' context works fine, but not the 'term' one. It is clearly wrong; I know that... but I can't figure out what the correct syntax would be, and how I would provide the parameter from within the template. (I am trying to print out just the slug of the 'scientific term' in this example). Any thoughts? I know that I can set a ForeignKey within my models to connect them. The problem with that … -
How to store social usernames/links in Django?
I have a personal blog written with Django. I want to make my social links/usernames dynamic so I can change them whenever I want. I'm doing this with charfields. I'm adding new charfield for each social username/link field then my template's getting these usernames to show them in a tags. It's okay but I think it's not the easiest way. Am I wrong or there is a better way to do this? -
Can't initialise GIT SCM on Mac OS High Sierra.
I am a complete novice in programming. Please don't make fun of me. I am trying to learn programming in Django. I wish to use GIT SCM to manage version control of my project. I seem to have succeeded in installing GIT SCM but I am not being able to initialise it and move forward. Could someone please help me ? Below you can find the error message thrown at me by the terminal. MacBook Pro (13 inch, early 2011) MacOS High Sierra (version 10.13.3) $ git init xcrun: error: active developer path ("/Applications/Xcode-beta.app/Contents/Developer") does not exist Usesudo xcode-select --switch path/to/Xcode.appto specify the Xcode that you wish to use for command line developer tools, or usexcode-select --installto install the standalone command line developer tools. Seeman xcode-selectfor more details. -
Django cannot import name _imaging
I'm trying to deploy a Django application, however, during deployment, I'm getting the following error: Apache Error Logs: https://pastebin.com/3MzEkaws Any help would be greatly appreciated. -
Django CreateView with AJAX
I want to create, update and delete objects through generic views and modals using AJAX in Django. The official documentation of Django talk about AjaxableResponseMixin and show this code: from django.http import JsonResponse from django.views.generic.edit import CreateView from myapp.models import Author class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super().form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, } return JsonResponse(data) else: return response class AuthorCreate(AjaxableResponseMixin, CreateView): model = Author fields = ['name'] (I have a model which looks like this) However I don't understand how to implement it in a modal. I do have this form that I'm currently using but it's a web page, not a modal: <form method="post" novalidate> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn btn-success">AJouter</button> </form> Is there a simple way to implement it in a modal using some ajax and jquery? -
Django model formsets saving object creator error: "null value in column "creator_id" violates not-null constraint"
When I try to save model formset and another related form in my view, i get the mentioned error. I now that it is because of I don't save user to the Ad model before saving it, but it seems I do that in my code... Anyways I guess the saving might be even different since my user's id is inherited from default django User model. views.py Ad model in models.py Image model in models.py Both forms i try to save The error I'm getting -
Jquery function not working properly in my Django template
I am trying to show all courses in a faculty when clicked on faculty name and that is working properly. But also, I was trying to show all the courses from a specific department. Now, I managed to show the courses in a department also, but courses from faculties or previous accessed departments won't go hidden and all will show one under another. Problem is, I don't know how to fix my function. I hope I am also rendering it right. http://pasted.co/b1babe18 -
Django: Integrating django-taggit and django-autocomplete-light outside admin
I want to integrate django-taggit outside admin and use django-autocomplete-light for auto-completion. As per the documentation, here, it appears as if it is possible to generate suggestions for tagging outside admin. However, I am unable to generate any suggestion following the instructions. #forms.py class ProblemDetailsTagForm(autocomplete.FutureModelForm): class Meta: model = Problem fields = ['topic_tags'] widgets = { 'topic_tags': autocomplete.TaggitSelect2('tag_autocomplete') } #models.py class Problem(CreateUpdateDateModel): topic_tags = TaggableManager() #urls.py url(r'^tag-complete/$', views.TagAutocomplete.as_view(), name='tag_autocomplete'), I have checked if my code matches to the documentation but no help. -
how to merge two different annotate in django?
I have two models like this: class Item(models.Model): title = models.CharField(max_length=128) class Order(models.Model): item = models.ForeignKey(Item) user = models.ForeignKey('users.User',null=True) gift_code = models.CharField(max_length=20,default='') I need to annotate two different query: Order.objects.filter(gift_code__isnull=False, gift_code__gt='').values('item__title').annotate(the_count=Count('item__title')) Order.objects.filter(gift_code__isnull=False, gift_code__gt='', user__isnull=False).values('item__title').annotate(the_count=Count('item__title')) the problem is I can't find a way to merge this two query. I tried this method, but both value was the same: all_gift = Count('item__title') used_gift = Count('item__title', filter=Q(user__isnull=False)) gifts = Order.objects.filter(gift_code__isnull=False, gift_code__gt='').values('item__title').annotate(all_gift=all_gift).annotate(used_gift=used_gift) the actual output: [{'item__title': 'title', 'used_gift': 500, 'all_gift': 500},...] my expected output is: [{'item__title': 'title', 'used_gift': 60, 'all_gift': 500},...] -
Context manager decorator never runs __exit__ if setUp fails inside test
I'm trying to solve a bug in django. The bug involves a class called TextContextDecorator which can be used a class decorator and/or context manager. As the bug description mentions, when using TextContextDecorator as class decorator enable is called just before Test.setUp, and disable is called after Test.tearDown.unfortunately, tearDown is not called in the event of a failure inside setUp. This can result in unexpected behaviour. One of the proposed solutions is that to use addCleanUp inside the setUp of TestContextDecorator, but I'm having difficulties in calling that function inside of decorator class. Here is the sample code provided to reproduce the bug.. class example_decorator(TestContextDecorator): some_var = False def enable(self): self.__class__.some_var = True def disable(self): self.__class__.some_var = False class Example1TestCase(TestCase): def test_var_is_false(self): # some_var will be False self.assertFalse(example_decorator.some_var) @example_decorator() class Example2TestCase(TestCase): def setUp(self): raise Exception def test_var_is_true(self): # won't be hit due to exception in setUp self.assertTrue(example_decorator.some_var) class Example3TestCase(TestCase): def test_var_is_false(self): # some_var will be True now due to no cleanup in Example2TestCase self.assertFalse(example_decorator.some_var) So far i have used try and except inside the setUp of TestContextDecorator and that seems to solve the bug but i'm not sure if its the best way to do it. Here are the changes … -
How add two model filed in class Meta:
I'm necessary add new field in User model. I create new model 'UserProfile', make inline and re-registration and add in model = User, UserProfile. Arises problem: AttributeError: 'tuple' object has no attribute '_meta' How fix this problem? Models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) avatar = models.ImageField(upload_to='images/users', blank=False) def __unicode__(self): return self.userenter code here forms class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, help_text='Please enter your email', widget=forms.TextInput(attrs={'placeholder': 'example@gmail.com'}), validators=[RegexValidator(regex=r'([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}', message='Incorrect email')]) first_name = forms.CharField(max_length=30, required=True, validators=[RegexValidator(regex='[a-z]', message='Incorrect name')]) class Imagefield(UserProfile): avatar = forms.ImageField(required=True) class Meta: model = User, UserProfile fields = ('username', 'first_name', 'avatar', 'password1', 'password2', ) -
Error: could not determine PostgreSQL version from '10.1' failed with error code 1 in /tmp/pip-build-07yg4mvk/psycopg2/
I want to push my Django app on heroku server and I installed my all rquirements.txt file which given below asgiref==1.1.2 asn1crypto==0.24.0 attrs==17.4.0 autobahn==17.10.1 Automat==0.6.0 beautifulsoup4==4.6.0 braintree==3.19.0 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 chromedriver-installer==0.0.6 constantly==15.1.0 cryptography==2.1.4 defusedxml==0.5.0 dj-database-url==0.4.2 Django==1.11 django-allauth==0.33.0 django-amp-tools==0.1.1 django-crispy-forms==1.5.0 django-filter==0.11.0 django-registration-redux==1.2 djangorestframework==3.7.1 gTTS==1.2.2 gTTS-token==1.1.1 gunicorn==19.7.1 hyperlink==17.3.1 idna==2.6 incremental==17.5.0 numpy==1.13.3 oauthlib==2.0.4 opencv-python==3.3.0.10 Pillow==5.0.0 psycopg2==2.7.4 PyAudio==0.2.11 pycparser==2.18 PyJWT==1.5.3 pyOpenSSL==17.5.0 python-decouple==3.1 python-social-auth==0.3.6 python3-openid==3.1.0 pyttsx==1.1 pytz==2017.3 requests==2.7.0 requests-oauthlib==0.8.0 selenium==3.7.0 six==1.11.0 social-auth-app-django==1.2.0 social-auth-core==1.4.0 SpeechRecognition==3.7.1 txaio==2.8.2 urllib3==1.22 virtualenv==15.1.0 whitenoise==3.3.1 zope.interface==4.4.3 After this I run this command git-push heroku maste I am getting Error: could not determine PostgreSQL version from '10.1' remote: remote: ---------------------------------------- remote: Command python setup.py egg_info" failed with error code 1 in /tmp/pip-build-07yg4mvk/psycopg2/ remote: ! Push rejected, failed to compile Python app. I have been unable to figure this out, please help. -
JSONB output from object.query() results in syntax error on raw sql
I am quite new to django and JSONB and I use this following syntax to excecute a search on JSONB data fields: obj=SomeModel.objects.filter(data__0__fieldX__contains=search_term) .. and it works as intended. Now, I print out the obj.query for the above statement and I get: SELECT * FROM "somemodel_some_model" WHERE ("somemodel_some_model"."data" #> ['0', 'fieldX']) @> '"some lane"' However, when I excecute the above using: obj=P2A_SomeModel.objects.raw(`query statement above`) I get an error: django.db.utils.ProgrammingError: syntax error at or near "[" LINE 3: #> ['0', 'fieldX']) @> '"some lane"' I presume I am not escaping the "[", and I have tried using a backslash before, but it does not seem to help. -
How can i generate pdf from a table in django using print button
Mainly i want to generate a pdf of output table in django framework by clicking the print button.Can any one help? or give some effective link or code ? -
How to display relevant information to instance of a ModelFormSet
I am using a ModelFormSet to allow the user to edit any of the entries on my Election model. I am generating the following formset in the view: election_formset = modelformset_factory(Election, fields=('CandidateReg','VotingOpen','FlipGrid')) The formset is of this model: class Election(models.Model): Name = models.CharField(max_length=20) # Allow to register / vote when True CandidateReg = models.BooleanField(default=True) VotingOpen = models.BooleanField(default=False) Description = models.CharField(max_length=255, null=True, blank=True) FlipGrid = models.URLField(null=True, blank=True) Complete = models.BooleanField(default=False) def __str__(self): return self.Name I'm rendering it in the template as follows: <div class="card-body"> <h4>Toggle election settings:</h4> <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} <!-- <h4> Display the Name field of the Election being edited </h4> --> <p>Allow candidates to register: {{form.CandidateReg}}</p> <p>Allow voting: {{form.VotingOpen}}</p> <p>Videos link: {{form.FlipGrid}}</p> {% endfor %} </form> </div> What I want to do is render the value in the Name field of the Election instance that is relevant to the below form (as indicated in the above template). I don't want the user to be able to edit the name, however. Is there a convenient way to do this? -
uWSGI + builded Go .so not working
I've build Go module with go build -buildmode=c-shared -o output.so input.go to call it in Python with from ctypes import cdll lib = cdll.LoadLibrary('path_to_library', 'output.so') When django project is served via uWSGI the request handler that calling Go library freezes, causing future 504 in Nginx. After getting in "so called freeze", uWSGI is locked there and only restarting helps to enliven app. No logs AT ALL! It just freezes. Everything works correctly when i run in python interpreter on the same machine. My thoughts: i've tried to debug this and put a lot of log messages in library, but it won't give much info because everything is fine with library(because it works in interpreter). Library loads correctly, because some log messages that i've putted in library. I think it some sort of uWSGI limitation. I don't think putting uwsgi.ini file is somehow helpful. Additional info: Go dependencies: fmt github.com/360EntSecGroup-Skylar/excelize log encoding/json OS: CentOS 6.9 Python: Python 3.6.2 uWSGI: 2.0.15 What limitations can be in uWSGI in that type of shared object work and if there a way to overcome them? -
Can't find file that got created in Command prompt
I'm trying to install the version module in Python 3. I am running the command pip install version. It then shows me an Import error cannot import name 'izip_longest'. I already know that I have to take out the i of izip in python 3, but I cannot find the file, where I can change it. It tells me the file (version.py) would lay in 'C:\Users\myname\AppData\Local\Temp\pip-build-p619-k9v6\version\version.py', but the folder pip-build-p619-k9v6 does not exist in my Temp directory. Any Ideas how I can get access to the file? Thanks -
Move file on django storage s3
I'm using django-storages with amazon s3, with a configuration close to this guide: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html Now I have a situation where I want to rename a lot of files when the model is saved, before implemented the s3 storage backend I simply called os.rename: os.rename(initial_path, new_path) Since that obviously doesnt work with django-storages, is there a a way of doing that differently using the storage's capabilities? -
django: how to specify database dynamically for factory boy
I am setting up a Django application with a lot of databases, and some of them are using the same models (they are not replicas). I already configured my routers and everything is working great. The problem appears when making the tests as I want to use factory-boy. On a different project I could setup the database inside Meta but now, I have to select on which database to create an instance dynamically (if not, I would have to create a DjangoModelFactory for each database, which wouldn't be pretty). Is there an (easier) way to specify the database dynamically for each creation? -
How can I relate a model to a celery task result?
I'm using django 1.11, with django-celery-results installed to store celery task results in the database. I'd like to have my model as: class Thing(model.Model, StatusMixin): # My model fields here task_result = ForeignKey('django_celery_results.TaskResult', SET_NULL, blank=True, null=True, related_name='thing') @property def status(self): """Current processing status of the task assigned to this model :return: the processing status, determined by checking the task_result """ # I want more complicated monitoring, but minimum example something like: return 'succeeded' if task_result.success else 'failed' So that I can launch a processing task that manipulates the contents of Thing... but when querying for Thing in the meantime, elegantly serialise out the processing status via the relation. Question: How and where should I set and save the task_result field in my model? I'd thought of something like this (where the task is executed): from tasks import my_task def my_view(request): # General view stuff to initialise a thing # ... thing_instance.save() # Launch an async task async_result = my_task.delay(thing.id) # Set the task result thing.task_result = TaskResult.objects.get(task_id=async_result.id) thing.save() But I'm struggling to understand the celery task.delay() method's inner workings - can I be certain the task result will be immediately available for use in the example above? -
Quickest way to get element by index in QuerySet
I'm trying to create time-efficient searching function for my system in Django considering that there are approximately 5 million objects. This is how i set query up: objects_found = (Model.objects.extra(where=["CHAR_LENGTH(attribute) > 300"])).filter(attribute__trigram_similar=message) I know that this QuerySet is yet not completely evaluated, and that's exactly what i don't want. For example, to complete evaluate the set up QuerySet like this: list(objects_found) It takes around ~60 seconds. If i want to get first item of the set up QuerySet in a classical way, it will still take ~60 seconds, since complete query is done: objects_found[0] But if i utilize methods like first(): objects_found.first() It takes around ~9 seconds, meaning that full QuerySet is not evaluated. Let's consider that objects_found has 500 objects. What if i need to do something like this: objects_found[40] or this: objects_found[:15] in a time efficient way? Therefore instead of searching through all 500 objects, the code will only search through 40 or 15 objects. Is there any implementation in Django QuerySet for this to be done? -
Django-importing excel file into django models
I need user to upload an excel file via the form provided and i need to process that uploaded excel file to save the data in my model. models.py class Patient_Record(models.Model): Patient_id=models.IntegerField(unique=True) Patient_sex=models.CharField(max_length=1,choices=Gender) Patient_name=models.CharField(max_length=20) Patient_sugar=models.DecimalField(decimal_places=3,max_digits=6) Patient_chlorestrol=models.DecimalField(decimal_places=3,max_digits=6) Patient_iron=models.DecimalField(decimal_places=3,max_digits=6) Patient_haemoglobin=models.DecimalField(decimal_places=3,max_digits=6) def __str__(self): return self.pat_name I have simple form to upload the file. <form method="POST" class="post-form" action="../Uploaded_file" enctype="multipart/form-data" name="myfile">{% csrf_token %} {{ upload_form.as_p }} <input type="submit" value="Upload" name="Upload" class="btn btn-primary"> </form> Can someone help me with the code to parse a excel file using POST to this model. I tried using many different methods but couldn't succeed in it. -
In django-tables2, change number of rows depending on screen size?
When using django-tables2, I limit the number of rows to display using the paginate parameter. For instance, if I have the table my_table, then in views.py I change the number of rows as follows: RequestConfig(request, paginate={'per_page':10}).configure(my_table) My problem is in my app I want the number of rows shown per page to depend on how big the user's screen is. For instance, 10 rows for mobile devices, but 25 rows for desktop screens. I am imagining doing in views.py what you can do with style sheets using the media rule (e.g., @media(max-height: 480px) {do something}). Related general discussion Interestingly, I haven't seen a lot of discussion of adapting table row count to media type, but there is obviously tons of more general discussion of responsive media-sensitive design: Responsive design with media query : screen size? https://developer.mozilla.org/en-US/docs/Web/CSS/@media -
How to represent foreign key lookup table in Django unit test?
I'm building three Django models that will allow users to create lists of items that represent activities (e.g. movies, concerts, and sporting events) they want to attend. Since each user can include one or more items (i.e. activities) in a list and multiple users may have the same item (activity) in one of their lists, there's a many-to-many relationship between lists and items: The 'list_type' table is a foreign key lookup table that identifies what types of activity items (movies, etc.) are stored in a list. I pre-populate this table via a Django migration when I run my initial migrations that create my tables. # list/models.py class ListType(models.Model): LIST_TYPES = ( (1, 'Movie'), (2, 'Concert'), (3, 'Sport'), ) type = models.CharField(_('type'), max_length=16) class Meta: db_table = 'list_type' class List(models.Model): user = models.ForeignKey(User) type = models.ForeignKey(ListType, help_text=_('Type of list')) name = models.CharField(_('list'), max_length=128, help_text=_('Name of list')) class Meta: db_table = 'list' unique_together = (('user', 'type', 'name'), ) class Item(models.Model): # value contains the pk of a movie, concert, or sporting event record lists = models.ManyToManyField(List, related_name='items'). value = models.IntegerField(_('item'), help_text=_('Item in list')) class Meta: db_table = 'item' I've been trying to represent the Type table with a factory-boy factory: import factory …