Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Returning a list with python magic methods in django models.py
I needed to select multiple items in a models.py (subjects app) which is linked with ForeignKey to another models.py (tutors). I get an error while trying to add items to the database after selecting multiple items in a topics var: "str expects a string but got a list". How do I use the python magic method or some other method in my models.py to return a list of selection and add same to the database? See below my models.py: from django.db import models from multiselectfield import MultiSelectField # Create your models here. class Subject(models.Model): TOPICS = ( ('SAT', 'SAT'), ('ACT', 'ACT'), ('GED', 'GED'), ('GRE', 'GRE'), ('READING', 'READING'), ('WRITING', 'WRITING'), ('ESL/ESOL', 'ESL/ESOL'), ('ALGEBRA', 'ALGEBRA'), ('CALCULUS', 'CALCULUS'), ('TRIG', 'TRIG'), ('GEOMETRY', 'GEOMETRY'), ('CHEMISTRY', 'CHEMISTRY'), ('PHYSICS', 'PHYSICS'), ('BIOLOGY', 'BIOLOGY'), ('CODING', 'CODING'), ('STATISTICS', 'STATISTICS'), ('FRENCH', 'FRENCH'), ('SPED', 'SPED'), ) topics = MultiSelectField(choices = TOPICS,blank=True) level = models.IntegerField(default=1) def __str__(self): return self.topics Thanks for assisting as I have come to my wits end. Done a lot of research online without luck -
Importing data in database using django
I have the resource file look like this. class UmuryangoResource(resources.ModelResource): cell = fields.Field(column_name='cell', attribute='cell',widget=ForeignKeyWidget(Cell, 'name')) village = fields.Field(column_name='village', attribute='village',widget=ForeignKeyWidget(Village, 'name')) class Meta: model = Umuryango class Umuryango(models.Model): sector = models.ForeignKey(Sector, on_delete=models.CASCADE) cell = models.ForeignKey(Cell, on_delete=models.CASCADE) village = models.ForeignKey(Village, on_delete=models.CASCADE, related_name='village_cell') the above model field are foreign key, and because cell has it village such that the village #can be duplicated in Village model, but assign to different cells. This lead to, when i import #xslx file without village has not more than one village_name in a Village it's imported #successfully. while my xslx file contain the village__name that has the same name in model. con #not be import. any one can tell me how i can initialize and save village according to it cell??? and ignore #that one from another cell i have initialize the village field in resource.py but still don't work, any one can help me. -
Order queryset filter in django using orderby and supplying a function
I am trying to return some locations from my sql db, ordered by distance from my current long lat. I have built an external function that takes my long/lat and somewhere else's long/lat and returns a float. However, struggling with getting this to run in my query. My query currently looks like this: class GallaryView(viewsets.ModelViewSet): queryset = Place.objects.filter(business="Gallary"). order_by( long_lat_distance(51.501521, -0.141944,Place.lattitude,Place.longitude)) serializer_class = PlaceSerializer With this, I get DifferedAttribute errors. I'm pretty lost on this. If anyone's got any pointers I'd be very grateful Cheers! -
Django forms styling input field for login page
I am working with Django templets and I am trying to create a beautiful login page. I want to use this snippet to beautify my login page input fields. <div class="form-label-group"> <input type="username" id="inputuser" class="form-control" placeholder="Email address" required autofocus> <label for="inputuser">Username</label> </div> <div class="form-label-group"> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required> <label for="inputPassword">Password</label> </div> </div> where should I keep my {{form.username}} and {{form.password}} in the above snippet The input fields UI should look like : But my UI looks like : my urls.py has : path('login/', auth_views.LoginView.as_view(template_name='post/login.html'), name='login'), Where should i add the form fields so that i can get the desired UI for my input fields -
Django Jsignature not passing the form.is_valid() - Part 2
I have exactly the same problem as Michael Ababao (Django Jsignature not passing the form.is_valid()) had and my ubuntu server tells me its upto date so I am not sure if I need to do what he did to resolve my problem. More importantly, what i have to do if my system is upto date. It appears that if i try to add the image pad to a form with other fields, say a form that needs a signature, the pad does not display. If i display it as per the way outlined by Michael Ababao (Django Jsignature not passing the form.is_valid()) then it displays and i am ble to sign but it never returns to the calling view for validation. Ian Shelvingdon seems to have solved Michaels problem. 1. I am not sure how to check to see if i can use the same solution. 2. Whether this jsignature solution can be used as i want to, as part of a form called from a view which is signed by the user. Can you shed any light on this Ian (https://stackoverflow.com/users/548562/iain-shelvington) SITUATION It displays the pad, i am able to sign it and click submit. Nothing happens after that. … -
Fontawesome refused to load Django project to heroku
I bought a template that i'm trying to adapt to my Django project. When I run it locally, it run correctly and now I did all the Django-Heroku setup correctly and now tried to push the project to Heroku it failed. I did : git push heroku master result : first screenshot Then run python manage.py collectstatic result: first screensho2 first screensho3 I tried some search and people who got the same issue and fix, said they replace some paths in the CSS file. if it is correctly where and how to do that. Please I'm novice in CSS and want a detail explanation. My assets folder as (ajax, css, img, js, scss and vendor) files.Thanks -
Django: ASGI app to process messages from message queue
I have a collection of Django apps that I deploy using an internal Cloud Foundry service. The apps don't do anything special. They just ask users to fill out some forms, store the information on the DB, and put some message on a message queue (ActiveMQ using STOMP) Now, to process the messages, I have to retrieve them from the ActiveMQ, and run a large number of jobs on a bunch of Linux machines. These machines are isolated from the Cloud Foundry service. I need to write an app to do this task. I am not sure how to write this app on the Linux side. Two options I am thinking about: Should I write a python script using stomp.py to retrieve the message, launch the jobs? This script will run as a daemon to constantly monitor the message queue. Each job will be responsible for storing the results back into the DB upon completion. I write a Django app that does the same functionality as 1) but I use ASGI server (Uvicorn) to run it on a Linux machine with some worker processes. Then each message is processed by one worker only. Can anyone advise which one is the … -
How to encrypt\decrypt files\images Fields in django?
I am trying to understand what is the best practice to encrypt a file\image using django drf. In my app the user upload sensitive data which I later on store in the cloud. The data contains files and images. I wish to encrypt the files in a way that even if someone hack the cloud the data is encrypt. as a code exmaple # models.py class FilesHandler(models.Model): name = models.TextField(blank=True, null=True) # -- File is save in the cloud, use djagno-storages -- #want to add encrypt feature my_file= models.FileField(storage=MediaStorage(), upload_to=get_upload_path, blank=True) processed = models.BooleanField(default=False) After a long research I only found the django-encrypted-filefield repo which last commit was done about 2 years ago.In addition I found small amount of data on the topic (could not find even one code example beside the repo mention above). Can someone share what is the best pratice to encrypt the data on the server side before sending to the cloud storage? a Django code example link would be appreciated -
How to only display model field value with same data only once in Django templates?
This is my models.py class report(models.Model): Citizennumber = models.IntegerField() Subject = models.CharField(max_length=100) Patientfile = models.FileField(upload_to="Report") Description= models.CharField(max_length=200) Hospitalname= models.CharField(max_length=50, default="blank") uploaddate = models.DateField(default=datetime.date.today) How do I loop through this models in django templates so that if 'report.Hospitalname' has same value in multiple objects and I only want to print it once in templates? -
Multiple JSON Bokeh Plots in Django Template -- Possible?
I feel that I'm almost there on this one, but on the other hand I might be going about this completely wrong. I am trying to generate several JSON items to load as bokeh plots in my Django template. I'm getting really hung up on the warning that says Bokeh isn't defined in my script that embeds it, despite having the stylesheets and scripts and jQuery scripts that seem necessary. It continually says "Bokeh is not defined" and advises me to define it or to add it as a global variable. Is this way the wrong way? Should I be using a Bokeh server? <script> ... Bokeh.embed.embed_item(json_dict.year); #ERROR IS HERE, DOESN'T RECOGNIZE BOKEH ... </script> Essentially, my question is: what is the best way to embed multiple bokeh plots into a django template? Is it even advisable? Please forgive my confusion, I've been staring at documentation for far too long. -
Reverse for *view* with arguments '('',)' not found
I am trying to create a simple search form(search by zip code): <form action="{% url 'search_results' query %}" method="post"> <div> {% csrf_token %} <input type = 'text' name = 'query' placeholder="Zip Code" /> <button type="submit" name="button">Find Jobs</button> </div> </form> urls.py: path('search_results/<str:query>', job_views.search_results, name = 'search_results'), views.py: def search_results(request, query): query = request.GET['query'] return HttpResponse(query) # just trying to see if this view has access to 'query' I'm not sure what is going on here. This returns raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'search_results' with a rguments '('',)' not found. 1 pattern(s) tried: ['search_results\\/(?P<que ry>[^/]+)$'] Thanks for any help! -
Dropdown list in Django
I have copied all the code from this post Dropdown in Django Model What do I have to do to make this list visible? When I run manage.py makemigrations or managepy migrate it tells that there are no changes. My code. views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('<h1>Witamy w aplikacji dla najlepszych inwestorów!</h1>') class CreateMyModelView(CreateView): model = MyModel form_class = MyModelForm template_name = 'myapp/template.html' success_url = 'myapp/success.html' models.py from django.db import models from multiselectfield import MultiSelectField COLOR_CHOICES = ( ('green','GREEN'), ('blue', 'BLUE'), ('red','RED'), ('orange','ORANGE'), ('black','BLACK'), ) class MyModel(models.Model): color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['color'] template.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Create" /> </form> Everything is the same and when I run my server only this appears What might be an issue? -
Django replica data save to many databases
From django documentation, is possible create replica from database and define where it will write or read. (django multiple-database). Then, it wrote the code for it, configuring my DATABASE like: DATABASES = { 'default': { 'NAME': 'my_write_database', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'writedatabase', }, 'replica': { 'NAME': 'replica', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'readdatabase', }, } And create the router: class ReplicaDatabaseWriteRead(object): route_app_labels = {..all_possible_applications} def db_for_read(self, model, **hints): return 'replica' # O just wanna read from 'replica' def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' # I wanna write in default and 'reflect' to 'replica' return None def allow_relation(self, obj1, obj2, **hints): db_list = (..all_possible_apps) if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True But this not works correctly. When I is writing, it just write in 'default', does not reflecting to 'replica'. Then when I read the 'replica', the values does not exits. Shouldn't he have written in the 'default' and replicated the value in the 'replica'? This code is very similarity of documentation, I don't know what's wrong. Or I don't understanded the django documentation -
Record video by django
how can I make a record video by framweork django I have been told to develop an app can record videos with length at most 30 second and after record user can type the price of goods like snapchat on the video, which technique I should do and any tutorial that explain how I make that thanks -
Pass user input as parameter to next view
I am trying to set up a website where users can search for a job by zip code/city/state etc. I am having difficulty passing the search value to a view (I have seen this question asked before, but only when the url is expecting a value from an object i.e job.id, but I am trying to get input from a user). Here is my code: urls.py: path('search_results/<str:search_input>', job_views.search_results, name = 'search_results'), views.py: def search_results(request, search_input): return HttpResponse(search_input) # just trying to see if I have the search_input value template (form is in index.html): <form action="{% url 'search_results' search_input %}" method="post"> Right now I get Reverse for 'search_results' with arguments '('',)' not found. 1 pattern(s) tried: ['search_results\\/(?P<search_input>[^/]+)$']. Thanks for any help. -
Inline Formset with many to many relation in django CreateView
I am unable to make it worked. I have two models "Course" and "Outcome". I want to make OutcomeForm form as inline form in CourseForm. My models.py file looks as below: class Outcome(models.Model): # some fields course_outcome = models.ForeignKey( "course.Course", on_delete=models.SET_NULL, blank=True, null=True ) class Course(models.Model): # some fields course_outcome = models.ManyToManyField( Outcome, verbose_name=COURSE_SINGULAR + " outcome", blank=True ) And inline formset is created as: OutcomeFormSet = inlineformset_factory( parent_model=Course, model=Outcome, form=OutcomeForm, extra=1, can_delete=True, ) And views.py file is: class CourseCreateForm(CreateView): model = Course template_name = "course/course_form.html" form_class = CourseForm success_url = reverse_lazy("course") def get_context_data(self, **kwargs): context = super(CourseCreateForm, self).get_context_data(**kwargs) if self.request.POST: context["outcomes"] = OutcomeFormSet(self.request.POST) else: context["outcomes"] = OutcomeFormSet() return context def form_valid(self, form, **kwargs): super(CourseCreateForm, self).get_context_data(**kwargs) context = self.get_context_data() outcomes = context["outcomes"] with transaction.atomic(): if outcomes.is_valid(): self.object = form.save() outcomes.instance = self.object outcomes.save() form.instance.course_outcome.set( Outcome.objects.filter(course_outcome=self.object) ) form.save() return super().form_valid(form) The problem is: All data of model Outcome and Course is saved except m2m field of Course model. I am stuck at this point. Any pointer in right direction will be highly appreciated. Thanks in advance -
Django - how to assign custom object as model property and get that model instance in that object?
I want to separate some logic from model and group it in a property, just like Django does with model managers (object property). I fact, something like ForeignKey but without database representation. I have something like this: class Remote(object): def __init(self, *args, **kwargs) self.post = ... # how to get to post instance? def synchronize(self): # this function requires Post object access print(self.post.name) class Post(models.Model): name = models.CharField(max_length=100) remote = Remote() ... for post in Post.objects.all(): post.remote.synchronize() Question How to modify above code to get access to Post object in Remote object? Additional question Is it possible to determine if Remote object has been called from Post instance (post.remote... – like above) or Post class (Post.remote...)? -
Staticfiles inaccessible after DEBUG=False django. Even after configuring static_root while collectstatic is successfully done
settings.py Click to see the folder structure of the application STATIC_URL = '/static/' MEDIA_URL = '/media/' print(os.path.join(BASE_DIR, 'static]')) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] [24/Jan/2020 18:06:31] "GET /static/css/navbar.css HTTP/1.1" 404 77 [24/Jan/2020 18:06:31] "GET /static/css/login.css HTTP/1.1" 404 77 -
How to access the dictionary created in Django views in html
I have created a dictionary in Django views by fetching data from database. However, I am unable to comprehend how to use it to print it in the html as a table. Given below are the relevant files. Views.py if 'form1' in request.POST: d={} vendor_choice = request.POST["inlineDefaultRadiosExample"] date_choice = request.POST["inlineDefaultRadiosExample1"] x = employee.objects.all() count=0 for i in x: if date_choice == 1: d[count]=transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=30)) count+=1 elif date_choice == 2: d[count]=transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=60)) count+=1 else: d[count]=transaction.objects.filter(vendor_id=vendor_choice, emp_id = i.id, timestamp__gte = datetime.date.today() - datetime.timedelta(days=180)) count+=1 return render(request, 'profiles/adminKaLogin.html', {'model':d}) The models.py class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(("Date"), default=datetime.date.today) The HTML {% if model %} <table> <thead> <tr> <th style = "padding: 20px;">Vendor ID</th> <th style = "padding: 20px;">Employee ID</th> <th style = "padding: 20px;">Debit</th> <th style = "padding: 20px;">Credit</th> <th style = "padding: 20px;">Time of transaction</th> </tr> </thead> <tbody> {% for i in model %} <tr> <td style="text-align: center;">{{ i.vendor_id.id }}</td> <td style="text-align: … -
django block templates are not functioning?
I started learning django and when i use more than one block templates in the html file then it didn't work please help out my code <!DOCTYPE html> {% extends "user/base.html" %} {%block anchor} <a href="#">Im a link in index.html</a> {%endblock anchor%} {% block body_block %} <h1>hello in am in body of index.html</h1> {% endblock body_block %} </body> </html> When i run this in browser i get an error saying 'endblock'. Did you forget to register or load this tag? Thanks in advance -
How to find the children from a django queryset
I have two django models One for blog pages and one for the blog listing: a list of all blogs. The blogpage has a ForeignKey reference to the listing page. class BlogListingPage(Page): ... class BlogDetailPage(Page): blog_listing = models.ForeignKey(BlogListingPage, on_delete=models.PROTECT, blank=True, null=True, related_name='+',) In views.py I have tried to look at the queryset object, but I cannot find a refernce to the detail pages. def blog(request): context = {'data': BlogListingPage.objects.all()} query_set = context['data'] for item in query_set: print(item.__dict__) It does correctly tell me the number of detail pages in numchild How can I access the children themselves? -
Django: create a separate set of models in in-memory SQLite DB on the flight
What I'm trying to do: I have a general huge set of models in my Django (v2.3.3) application in PostgreSQL DB, but now for a specific task I need to create a rather complicated aggregation of DB objects. And it would be much easier to work with them if I could only in that thread/process that handles this specific web-request create an in-memory SQLite DB, define a new set of model-classes there (without foreign keys to the global set of models of course), create some objects in that DB, do my calculations and kill that DB upon the response serving. For consistency I would like to use Django models for this small DB as well. Is this possible? Or do you have some better ideas how to approach this? -
Jinja/Django how can i filters from jinja?
Now the question is, through jinja I want to flirt data in html, there are two companies, I want one company to be shown in another place and the second in another place I’m stuck here, here it displays everything, but I want to filter by company, I know that views.py can be done, but I want through jinja I ask for help models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Buses(models.Model): company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) name = models.CharField(max_length=200) state_number = models.CharField(max_length=200) route = models.IntegerField() phone = models.IntegerField(blank=True) paid_until = models.IntegerField(blank=True) photo_person = models.ImageField(upload_to='photos/%Y/%m/%d/', default='avatar.jpg') photo_front = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_back = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_car_pass = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_license = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_route = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') def __str__(self): return self.name index.html <ul class="list-group collapse show" id="collapseM"> {% for bus in buses %} <li class="list-group-item"> <div class="row"> <div class="col-lg-4"> <a class="" href='#'><b>{{bus.name}}</b></a> </div> <div class="col-lg-4"> {{bus.state_number}} </div> <div class="col-lg-4"> {{bus.route}} </div> </div> </li> {% endfor %} </ul> views.py from django.shortcuts import get_object_or_404, render from .models import Buses def index(request): buses = Buses.objects.all() context = { 'buses': buses } return render(request, 'buses/index.html', context) -
Django compare data between a model and a mysql query
In my django project i have a model with some field like thisone: models.py class UserComPfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User") p_title = models.CharField(max_length=200) p_year = models.CharField(max_length=4) p_descr = models.TextField() p_link = models.CharField(max_length=100) def __str__(self): return self.p_title well, i have an external mysql db with a table with same table fields name, I have to execute a query on that data and compare results with my models data, the mysql table is the master and i have adapt data in my model to data in mysql (add new rows, delete rows that does not exist anymore or modify it) i use pymysql and do: .... mycursor.execute("SELECT * FROM u_customers") myresult = mycursor.fetchall() for x in myresult: at this point i don't know what is the best way to compare and align my model to external table data So many thanks in advance -
In Django trigger post_save after related object has been created?
I am using 'DRF Writable Nested' https://github.com/beda-software/drf-writable-nested to write nested serializer, where 'final_amount' depends on related objects. The 'post_save' signal for 'Invoice' triggers just when it gets saved as expected but at that moment related objects don't exist. I know that first 'Invoice' gets saved and then its 'pk' is used by 'InvoiceItem' in its invoice field. My requirement is to trigger signal only when related objects have been created. class Invoice(models.Model): customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='orders') products = models.ManyToManyField(Product, through='InvoiceItem') @property def final_amount(self): ''' Total invoice amount ''' return self.invoice_items\ .aggregate(total=Sum('item_details__amount'))['total'] class InvoiceItem(models.Model): invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name='invoice_items') product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='invoice_items') @property def total_quantity(self): ''' Total quantity for a particular product with all its sizes taken together. ''' return self.item_details\ .aggregate(total=Sum('quantity'))['total'] @property def total_amount(self): ''' The total amount for a particular product with all its sizes taken together. ''' return self.item_details\ .aggregate(total=Sum('amount'))['total']