Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django value inside javascript json
i have a javascript json var new ={ input:{ 'mdata':{ label:'properties', properties:{ name:{ label:'name', type : 'text' }, value:{ label:'value', type:'number', defaultValue:100 } } } } } now i hard coded default Value has 100 ,but i wanted to get from django tags, how can i get this???? -
Django: Read from serial port
I want my Django app to read from serial port, and if some specific data arrives, it should render a specific view, or just render a template is enough too. Is there some solution without celery? I tried this in views.py : def handle_data(data): if data == "SPECIAL": return specialview() # i need request object here def read_from_port(ser): while True: reading = ser.readline().decode() handle_data(reading) thread = threading.Thread(target=read_from_port, args=( serial_port,)) thread.start() def specialview(request): blah blah blah I though if I could just acces the current request object, I can pass it, but the solutions I found here: https://nedbatchelder.com/blog/201008/global_django_requests.html does not work. I am open to any solution except use of celery. -
How do you limit choices in a Django Inlineformset_factory based on User?
I have a Timesheet app and I want to limit the Projects a User can allocate their time to the Projects they are working on. MODELS My models look like this class Project (models.Model): name = models.CharField( verbose_name = 'Project Title', max_length = 80 ) code = models.CharField( verbose_name = 'Project Code', max_length = 15 ) supervisor = models.ForeignKey ( User, on_delete=models.CASCADE ) staff = models.ManyToManyField ( User, related_name= "project_resources" ) def __str__(self): return u'%s' % (self.name) class Meta: ordering = ['name'] class Timesheet (models.Model): user = models.ForeignKey ( User, on_delete=models.CASCADE) start_date = models.DateField ( verbose_name = "Start Date" ) def __str__(self): return u'%s | %s' % (self.user, self.start_date) class Meta: ordering = ['user','start_date'] class TimesheetRow (models.Model): ''' specifies a timesheet row which is unique based on Timesheet, Project and Labour Category ''' timesheet = models.ForeignKey( Timesheet, on_delete=models.CASCADE ) project = models.ForeignKey( Project, on_delete=models.CASCADE ) labor = models.ForeignKey( LaborCategory, on_delete=models.CASCADE ) sunday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) monday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) tuesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) wednesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) thursday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) friday = models.DecimalField (default = 0, max_digits=4, decimal_places=2) saturday … -
django - creating a model from a python class
is anyone aware of a way to create a django model from an existing python class without creating it by hand? Or if not, what is the best method to approach this problem? At the moment I'm searching a way to save the objects returned from libnmap (e.g. NmapHost) in django without creating a wrapper functions which converts a libnmap.objects.NmapHost into the according model. In addition, the django model should inherit all the functions and relationship of the original class. (e.g. a NmapHost has several NmapService objects linked to it) -
Django 1.8 request.user is removed
I am using django 1.8 along with mongoengine and a custom Middleware that is supposed to add a user and a toked to a django request. These two are passed in the header of the request. The middleware class is the following : from models import MongoToken class TokenAuthenticationMiddleware(object): def process_request(self, request): if "HTTP_AUTHORIZATION" not in request.META: return tokenkey = get_authorization_header(request).split()[1] token = MongoToken.objects.get(key=tokenkey) user = User.objects.get(username=request.META.get("HTTP_USERNAME")) if token.key == tokenkey and token.user.is_active: request.user = user request.token = tokenkey I also put this in my MIDDLEWARE_CLASSES bloc of the settings.py files: MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'myproject.middleware.MongoAuthenticationMiddleware', 'myproject.middleware.TokenAuthenticationMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And when the considered view is reached, my token is here because thanks to the header params but the user is Null. Then I am wondering if I did something wrong with this because it does not work. Thank you for your help. Alex. -
button dropdown list-item type="submit"
I am working on a django application and have a form inside my page. I have one action called "move" (next to delete, archive...) and based on the value that is given ( an ID) the right ID is passed through to my application: HTML (bootstrap): <button class="SelectionAction" type="submit" name="move" value="id1">Move to id1</button> <button class="SelectionAction" type="submit" name="move" value="id2">Move to id2</button> <button class="SelectionAction" type="submit" name="move" value="id3">Move to id3</button> views.py: tag_selection_form = TagSelectionForm(request.POST or None) if tag_selection_form.is_valid(): if 'move' in request.POST: new_tag_id = request.POST['move'] new_tag_list = Tag.objects.get(user = request.user, id = new_tag_id) for item in tag_selection_form.cleaned_data['my_object']: item.tag_list.remove(tag_list) item.tag_list.add(new_tag_list) if 'delete' in request.POST: ... if 'archive' in request.POST: ... ... My Problem: I want to "stack" all the individual move buttons underneath one foldable (dropdown) button, something like this. The dropdown on its own works, but I can not add type="submit" to an <li><a>something</a></li> and placing <button></button> inside the <li></li> messes up the css. <div class="dropdown div-inline SelectionAction"> <button class="btn dropdown-toggle" type="button" data-toggle="dropdown">Example <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><button class="SelectionAction" type="submit" name="move" value="id1">Move</button></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> What is the best way forward for this matter? -
How to handle multiple input elements with the same name in django
I'm working on an admin system with django and I need to use a repeating form elemets in stets to have many of the same record like for example contact persons for an establishment as seen below <div id="m_repeater_2"> <div class="form-group m-form__group row" id="m_repeater_1"> <label class="col-lg-2 col-form-label">Contact People:</label> <div data-repeater-list="" class="col-lg-10"> <div data-repeater-item="" class="form-group m-form__group row align-items-center"> <div class="col-md-12"> <div class="form-group m-form__group"> <label for="example_input_full_name">Contact Name:</label> <input name = 'contactName' type="name" class="form-control m-input" placeholder="John Doe" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Designation:</label> <input name = 'contactDesignation' type="text" class="form-control m-input" placeholder="Managing Director" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Email:</label> <input name = "contactEmail" type="email" class="form-control m-input" placeholder="john@sf.com" > </div> <div class="form-group m-form__group"> <label for="example_input_full_name">Number:</label> <input name = "contactNumber" type="number" class="form-control m-input" placeholder="0965555555" > </div> <div class="d-md-none m--margin-bottom-10"></div> </div> <div class="col-md-4"> <div data-repeater-delete="" class="btn-sm btn btn-danger m-btn m-btn--icon m-btn--pill"> <span> <i class="la la-trash-o"></i> <span>Delete</span> </span> </div> </div> </div> </div> </div> <div class="m-form__group form-group row"> <label class="col-lg-2 col-form-label"></label> <div class="col-lg-4"> <div data-repeater-create="" class="btn btn btn-sm btn-brand m-btn m-btn--icon m-btn--pill m-btn--wide"> <span> <i class="la la-plus"></i> <span>Add</span> </span> </div> </div> </div> </div> My problem is when two or more of the 'm_repeater_2' are generated I need to know the best way to go about getting each … -
Django: Adding many-to-many relations within post_save
I'm working on a Django 2.0 and I'm trying to create a simple Event app with auto opt-in functionality. I.e. Members with certain statuses are automatically signed up for the Event when it is created. To do that, I used Django's post_save signal to create a queryset of the affected Members and add them to the Event's many-to-many field, participants. @receiver(signal=post_save, sender='events.Event') def auto_opt_in(sender, instance, created, **kwargs): # Only applies to new Events that are opt-out if created and instance.is_opt_out: from database.models import Member # Build queryset of affected members members = Member.objects.none() for status in instance.opt_out_member_statuses: members = members.union(Member.objects.filter(member_status=status)) # Add members to Event instance.participants.add(*members) instance.save() My problem now is that the Members are not actually added to the Event. If I put print(instance.participants.all()) after the last line, it outputs the correct result. However, the changes do not appear to be committed to the database. What am I missing? Are you not allowed to make changes to the instance? If so, what's the point? Thanks -
Calculate Min and Max of Sum of an annotated field over a grouped by query in Django ORM?
To keep it simple I have four tables(A,B,Category and Relation), Relation table stores the intensity of A in B and Category stores the type of B. I need to query A, group by the query by Category and calculate Sum of Intensity of A in each category (which is possible using Django ORM), then I want to annotate Min and Max of calculated Sum in each category. My code is something like: A.objects.all().values('B_id').annotate(AcSum=Sum(Intensity)).annotate(Max(AcSum)) Which throws the error: django.core.exceptions.FieldError: Cannot compute Min('AcRiskIntensity'): 'AcRiskIntensity' is an aggregate Django-group-by package with the same error. For further information please also see this stackoverflow question. I am using Django 1.11 and PostgreSQL. Is there a way to achieve this using ORM, if there is not, what would be the solution using raw SQL expression? -
Django Signals and celery , is Sync
I am using celery to scrap some URLs , and pushing the scrap data to an API but because of quick calls on this API i need to use Django Signals if it Sync -
How to Add Image to PDF using WeasyPrint in Django? (Not static images but user uploaded images!)
I'm working on a Django project named 'cDoctorAssistant'. Here, a doctor can upload an image(say a patient's image). The images are in 'cDoctorAssistant/media/profile_pic' directory. Now, I need to create a pdf file about patient report. The report contains images. I an using WeasyPrint to create pdfs. But I can't add images to the pdf. Does any one know how to solve it? I only found how to add static images in google. But these images aren't saved in static directory. So I really need some help! Thanks in advance! :) -
CategoryView is not shown
CategoryView is not shown.I wrote in views.py like class CategoryView(ListView): model = Category def get_object(self): category_name = self.kwargs['category'] return Category.objects.get(name=category_name) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() return context in detail.html <div> <p>{{ object.text }}</p> </div> <div> <a href="#" class="list-group-item active"> Category </a> <div> {% for category in get_object.comment_set.all %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> But now in detail.html no category data is shown.I really cannot understand why this happens.I think I can get data by using get_object.comment_set.all in template but it is wrong.How should I fix this?What is wrong in my code? -
Django: How to write a mock/patch test for object creation?
I gave it a go, but I got the error message AttributeError: Mock object has no attribute '_state' for the code below. Not sure what I am doing wrong. Do note at the end of the question I mention that I have tried using patches, without much more luck. Model.py class Sale(models.Model): from_product = models.ForeignKey(Product) from_til = models.ForeignKey(Til) price = models.DecimalField(max_digits=8, decimal_places=2) create_date = models.DateTimeField('sale_date', editable=False) def __str__(self): return "%s %s %s" % (self.from_product, self.price, self.create_date) def save(self, *args, **kwargs): if not self.id: self.create_date = timezone.now() super(Sale, self).save(*args, **kwargs) test_models.py class SaleModelTestCase(TestCase): @classmethod def setUpClass(cls): super(SaleModelTestCase, cls).setUpClass() cls.product = MagicMock(spec=Product) cls.til = MagicMock(spec=Til) cls.price = 2.34 def test_create_sale(self): now = datetime.now() with mock.patch('django.utils.datetime_safe.datetime') as dt_mock: dt_mock.now().return_value = now new_sale = Sale.objects.create(from_product=self.product, from_til = self.til, price=self.price) self.assertTrue(isinstance(new_sale, Sale)) self.assertEqual(new_sale.create_date, now) I have been reading around and getting quite confused. If I understood correctly I can replace Sale.objects with @patch('app.models.Sale.objects'), which is placed above class SaleModelTestCase(TestCase): and include an extra mock_sale parameter. I gave that a go too, but self.assertTrue(isinstance(new_sale, Sale)) returns False is not true. If anyone is about to show me where I am going wrong, I would be very grateful. -
Override Django widgets default templates
I want to override the Django (2.01) widget templates, because I need to add classes for each input, label, and position them differently app - templates - app - django - forms - widgets - input.html or app - templates - django - forms - widgets - input.html or template project directory: - templates - django - forms - widgets - input.html None of them works, (even if I this is how is recommended in docs, and from an answer that I saw on stackoverflow), it still loads from default. Being general widgets templates, I'm preferring to put them in the template project directory, but from what I reed by default for widgets search only in installed apps. -
why does `Model.objects.get(id=model.ForeignKeyField).IntegerField` not return an integer?
I'm trying to get the value of an IntegerField from a queryset object based on the value of a ForeignKeyField so I can 1 to it like this. all = Comment.objects.filter(video=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] for comment in all: comment.indent = Comment.objects.get(id=comment.replyto).indent + 1; However it seems to cause an error saying: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Comment' Why is this? What am I doing wrong? comment model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') video = models.ForeignKey(Video, on_delete=models.CASCADE) description = models.TextField(default="none") replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments... indent = models.IntegerField(default=0) -
How to create an Inline through a chain of foreign keys in Django admin?
Supposing I have these Django models: class Genre(models.Model): name = models.CharField(max_length=255) class Author(models.Model): name = models.CharField(max_length=255) genre = models.ForeignKey('Genre') class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey('Author') I want to define inlines in Django Admin for a Genre instance showing all related books. How can I do it? I tried this way: class BookInline(admin.TabularInline): model = Book extra = 0 class GenreAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Genre, GenreAdmin) that brought me the error: ValueError: 'Book' has no ForeignKey to 'Genre' How can I define the inline correctly? -
How do I not let the pdf file to download, instead email it to me in django?
I have this function html_to_pdf_view that generates pdf file. But whenever I open the url linked to that view, it downloads the pdf file. I don't want the file to be downloaded, instead the file should be sent to my email. def html_to_pdf_view(request): paragraphs = ['first paragraph', 'second paragraph', 'third paragraph'] html_string = render_to_string('blog/pdf_template.html', {'paragraphs': paragraphs}) html = HTML(string=html_string) html.write_pdf(target='/tmp/mypdf.pdf'); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response return response -
FileNotFoundError: [Errno 2] No such file or directory: 'media/GeoLite2-City.mmdb'
I have a file in the media/ directory: When I in a test.py file to get it by GeoIP(): from pygeoip import GeoIP def getLatLon(ip): gi = GeoIP('media/GeoLite2-City.mmdb') data = gi.record_by_addr(ip) return data getLatLon("113.210.32.76") There comes issue: File "/Users/luowensheng/Desktop/TestIOS/TestPython/testDemo02/ipaddr/tests.py", line 16, in <module> getLatLon("103.200.32.76") File "/Users/luowensheng/Desktop/TestIOS/TestPython/testDemo02/ipaddr/tests.py", line 10, in getLatLon gi = GeoIP('media/GeoLite2-City.mmdb') File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pygeoip/__init__.py", line 118, in __init__ self._fp = codecs.open(filename, 'rb', ENCODING) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 895, in open file = builtins.open(filename, mode, buffering) FileNotFoundError: [Errno 2] No such file or directory: 'media/GeoLite2-City.mmdb' It says the FileNotFoundError. why there comes this error? -
Where I can add hook after restarting Django server?
I want to add extra hook to cleanup some data but for that I need Django server running or some other services running that I added in Django restart commands. -
Django: Remember url parameters in django-tables2 with django-filter
Hello this is my view: class FilteredReclamationListView(FilterView, SingleTableView): table_class = ReclamationTable model = ReclamationMainModel template_name = 'reclamation_table/index.html' filterset_class = ReclamationFilter table_pagination = { 'per_page': 50 } def get_table_data(self): return self.object_list def get_queryset(self): return self.model.objects.filter(archive=False).order_by('-id') Is this any possible to remember the url parameter in this case? I would like to have situation that user go to another view and when he is back he will see his last query/filter. I reading about sessions and request.GET.urlencode() but I can't apply that in my view. -
Render subtemplate inside a template in Django [duplicate]
This question already has an answer here: Django use a variable within a template tag 2 answers I have a bootstrap modal element that changes it's contents depending on different application states and user preferences. I have a view rendering the 'main' template and passing essential data and a form to it, but I want to populate the contents of modal dynamically. Contents of this modal should sometimes be other forms and sometimes just plain data representation. It is possible to do bunch of conditional statements inside a template and do something like: <div class="modal-content"> {% if something %} {% include 'foo.html' %} {% elif something_else %} {% include 'bar.html' %} {% else %} ... {% endif %} </div> But such approach obviously is very much hard-coded and only solves a problem of rendering plain html templates, so I tried to pass template as a parameter to 'main' template: class Homepage(View): def get(self, request): ... sub_template = 'foo.html' return render(..., {...,'sub_template': sub_template}) And then render the inside of modal element like you normally access argument passed to template: <div class="modal-content"> {% include {{sub_template}} %} </div> But this approach didn't work. Is there a way to pass template as argument to … -
Using django autocomplete light with form tools preview
I try to use django autocomplete light outside the admin panel in combination with form tools. I accomplished to use autocomplete inside the admin panel and to use regular forms in the django form tools. But the last step, to use autocomplete inside outside the admin panel will not work. This is from my forms.py: class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('user',) widgets = { 'user': autocomplete.ModelSelect2(url='autocomplete-person') } [...] class MessageForm(forms.Form): user = PersonForm() I guess the error must be here, but I am not sure. What I think, what this should do: * Inherits from ModelForm * changes the widgets to the fitting aoutocomplete widget * Uses correct model and fields * In MessageForm this should be used. Instead nothing shoes on the screen. Can someone help? I can provide other parts of my code if necessary. -
Django & React Application on AWS Lambda
I am building a project with Django at the back and React at the front. I will be prepackaging the react files and serving them as plane static files without a NodeJS server (plain django static files from S3 and Cloudfront). The root url renders a blank template and pulls in the necessary JS files and react handles the rest of it. I also have APIs written using DRF which is accessed by React. I am basically following this architecture style - https://github.com/Seedstars/django-react-redux-base So I would like to know if and how this can be implemented in AWS Lambda? -
how to use signal in thread
I want to run a function in background. so I use Threading in my code. but return error ValueError: signal only works in main thread and don't know about two things: what is the main thread how to solve this problem :) views.py def callback(update): print('I received', update) def message_poll_start(): try: client = TelegramClient('phone', api_id, api_hash, update_workers=1, spawn_read_thread=False) client.connect() client.add_update_handler(callback) client.idle() except TypeNotFoundError: pass def message_poll_start_thread(request): t = threading.Thread(target=message_poll_start, args=(), kwargs={}) t.setDaemon(True) t.start() return HttpResponse("message polling started") urls.py urlpatterns = [ path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"), ] -
Multiple Objects Returned
I'm beginner in python and Django rest And I stuck when I fetch data. Here is my API :- http://127.0.0.1:8000/subjects/course/23/ I want a all subject data according to course which I select..When I hit this api if single data present working awesome but when inside course_id multiple subject present then gives me error such as : Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Subject -- it returned 2! Here is my model.py class Subject(models.Model): course = models.CharField(max_length=255, blank=False, unique=False) subject = models.CharField(max_length=255, blank=False, unique=False) description = models.CharField(max_length=255, blank=False, unique=False) amount = models.CharField(max_length=255, blank=False) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.title) Here is my serializer.py class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = ('id', 'course', 'subject', 'description', 'amount', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') lookup_field = 'course' Here is my views.py class ViewSubjectAccordingCourse(generics.RetrieveUpdateDestroyAPIView): """This class handles the GET and POSt requests of our rest api.""" queryset = Subject.objects.all() serializer_class = SubjectSerializer lookup_field = 'course' Here is my urls.py url(r'^subjects/course/(?P<course>[0-9]+)/$', ViewSubjectAccordingCourse.as_view(), name="details"),