Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-hvad and modelform_factory()?
Trying to create a form with name booking status as admin user, by using the django-hvad module somehow I'm getting this error as below? Any help will be appreciated. Versions: python 3.6 django 2.2.4 django-hvad 1.8.0 OS:windows settings.py INSTALLED_APPS = [ 'booking', 'booking.tests.test_app', 'hvad' ] models.py from hvad.models import TranslatedFields, TranslatableModel class BookingStatus(TranslationModelMixin, TranslatableModel): """ Master data containing all booking status. For translatable fields check ``BookingStatusTranslation``. :slug: A unique slug identifier. translated: :name: The displayable name for the status. """ slug = models.SlugField( verbose_name=_('Slug', unique=True), ) translations = TranslatedFields( name=models.CharField( max_length=128, verbose_name=_('Name'), ) ) Error TypeError at /admin/booking/bookingstatus/add/ TypeError: modelform_factory() got an unexpected keyword argument 'change' -
How can I change Model values from within Django Admin's response_change?
I have added a custom button to my Django Admin by overriding change_form.html. I'd like this button to read a site_url field from the model itself, and then programatically change the model's form fields (without saving the model).. so it can reviewed and corrected before saving. I have successfully got my button to print the object by overriding response_change. I can also pre-populate the template by using extra_context by overriding change_view. def response_change(self, request, obj): if '_scrape-site' in request.POST: print(obj) return HttpResponseRedirect(".") return super().response_change(request, obj) I'd like to be able to enter a site_url and scrape it using requests/bs4 or scrapy, and then return those values into the change_form in the Title and Summary text boxes (see https://imgur.com/dttzPIt.jpg). Is that possible? -
ModuleNotFoundError: No module named 'django_project.users'
As the title says. I have been through multiple threads of StackOverflow with similar questions as to mine and none of them have given me a working solution. My directories: -
int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest'
I am trying to access form data in a queryset and it throws the following error: int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest' Views.py s_o = form.cleaned_data['sales_order'] MaterialRequest.objects.filter(id=s_o).update(is_allocated = True) in the print statement it says that s_o is 1, but I can't equate it with the id in query? What is it that I am doing wrong and how can I change that? -
How can I add a new field from the other app's models.py to html in Django, Python
I want to change the field. I have email.html of reservation app and order_detail.html of order app. Both files have a word Nursery information: at the bottom of the page. I want to use a field of nursery from service app under the words Nursery information of both html files. I wrote order.nursery but it didn't show up. The other like order.shippingAddress1 could show up. How can I show up order.nursery like any others? My relational app names are reservation, order, service. This is email.html of templates of reservation app. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New Reservation #{{ transaction.id }} - TS</title> <style> table { width: 60%; margin: 0 auto; border-collapse: collapse; } table tr td { border: 1px solid #c1c1c1; } p { padding-right: 50px; padding-left: 50px; } </style> </head> <body> <center> <h1>Thanks for reserve with us</h1> <p>This email is to confirm that you have reserved on the TS.<br>Please make sure that all the details of your order are correct.</p> </center> <br> <table> <tr> <td valign="top" colspan="2" style="width: 50%;"> <b>Your Address:</b><br> {{ transaction.billingName }}<br> {{ transaction.billingAddress1 }}<br> {{ transaction.billingCity }}<br> {{ transaction.billingPostcode }}<br> {{ transaction.billingCountry }}<br> </td> <td valign="top" colspan="2" style="width: 50%;"> <b>Reservation: … -
How to search the grade level and payment-type per grade level and subject using two select option?
\\html <form method="post" action="/newEnroll/"> {% csrf_token %} <table> <tr> <td></td> <td> <input type=submit value="submit" id="enroll" class="enroll" formaction="/newEnroll/"> </td> <td> <input type='button' name='back' value='Back' class='button' onclick="history.back()" /> </td> </tr> </table> <form action="" method="get"> {% csrf_token %} <select name="gradelevel" id="gradelevel"> <option value="0">-- EducationLevel --</option> {% for ylvl in edulevel %} <option value="{{ylvl.id}}" name="gradelevel" >{{ylvl.Description}}</option> {% endfor %} </select> <select name="paymentID" id="paymentID" required="required"> <option name="NULL" value="0" >----Payment Type----</option> {% for pay in payment %} <option name="paymentID" value="{{pay.id}}" >{{pay.Description}}</option> {% endfor %} </select> <input type="submit" value="View" onchange="showResult(this.value)" id="showTxt" formaction=""> </form> <div id="paymentshow"> <tr><th>Subject</th></tr> <tr> </tr> {% for sub in subj %} <tr> <td>{{sub.Description}}</td> </tr> {% endfor %} <tr><th>Payment Type</th></tr> {% for schedule in sched %} <tr> <td>{{schedule.Remark}}</td> <td>Php {{ schedule.Amount|floatformat:2}}</td> </tr> {% endfor %} </form> </form> </body> <script> function showResult(subj) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("POST", "{% url 'enrollmentform' %}?gradelevel="+subj, true); xhttp.send(); } </script> <script> function payment(str) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("paymentshow").innerHTML = this.responseText; } }; xhttp.open("POST", "{% url 'searchpayment' %}?payment="+str, true); xhttp.send(); } </script> \\views paymentID = request.POST.get('paymentID') sched … -
The non-superusers are not able to log in in Django
I've created a view for login but Django only authenticates the superuser. The non-superusers are not able to log in. def logingin(request): if request.method == 'POST': username = request.POST.get('username','') password = request.POST.get('password','') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: return redirect('/signup') return render(request, 'login.html') -
Django - same project need two different types of authetication mechanisms for different APIs - any suggestions of best way to achieve it
We have a multi tenant application where most of the front-end APIs (which get exposed on front end as functionality for end users of any tenant) needs to be authenticated in way that the user is valid & the user has valid access to do that event (get/post/put etc) for that tenant. In the same project we also have some backend tasks which are internal to our code & not specific to any tenant. For the backend APIs we want to use simple authentication header/bearer type of authentication. How do we achieve the two different approaches? -
Sync postgres tables between two databases
We have two Postgres database instances for two regions(Django application). These database instances have common and region-specific tables/data. We have an admin panel, where an administrator modifies a few tables. Given that there are two regions, the administrator has to repeat the same activity in both the regions. To overcome this, we have planned a "master" server where admin modifies the tables in the "master" server and the data must be replicated in both the region servers. These tables have a "modified" timestamp, "last_synced" timestamp and a "reviewed" boolean and only rows marked reviewed and modified date >last_synced needs to be synced with the region servers. The sync process must also not sync certain columns in the table which are region specific. This need not be realtime and can be daily batch. As with any other database, the tables have a lot of foreign keys and all these must be replicated. What would be the best option for this specific datasyc? -
How to export csv data form curent django-filter
How to export csv current data from django-filterset some mycode @view.py django-filter def fourm(request): data_list = FourmAproveCoWeb.objects.all() data_filter = DataFilter2(request.GET, queryset=data_list) return render(request, 'fourmlist.html', {'filter': data_filter}) @filter.py class DataFilter2(django_filters.FilterSet): issue_date = django_filters.DateFromToRangeFilter() qa_follow_up_date = django_filters.DateFromToRangeFilter() class Meta: model = FourmAproveCoWeb fields = ['issue_date','pic_field','status','ecr','number_4m','qa_follow_up_date'] enter code here @view export function I'm want export to data filter already. i't not work def export_as_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' data_list = FourmAproveCoWeb.objects.all() data_filter = DataFilter2(request.GET, queryset=data_list) writer = csv.writer(response) writer.writerow(['PIC','Process']) x = [] for i in data_filter.qs: print(i.ecr) writer.writerow([i.pic_field,i.process]) return response -
URL scheme & Django views for extremely similar API and webpage
I am designing an API for a website I manage which will more or less be the same data shown tabularly on the site as will be served as JSON to clients. Essentially, I hope that the webpages themselves could be rewritten as API clients if I really wanted. I have two primary questions: What is an appropriate URL scheme separation between calls to show HTML webpages and calls to the API? My initial thought is to use the singular form (/city/1) for the webpage and the plural (/cities/1) for the API, as I did not yet know that the plural is the preferred way to structure my URL scheme. Since both the API and the webpage view return such similar data, is there any consolidation that can be done in views.py so that the HTML and JSON outputs use the same code for gathering their queryset? I feel that the API endpoint could call to the webpage view code and then pass its result through a serializer before returning it, but I want to double-check that is a reasonable option. -
How to filter the Parents ID by its children foreign key?
\\views def Parents_login_form(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = ParentsProfile.objects.get(Parent_User=request.POST['p_user']) if m.Parent_Password == request.POST['p_pass']: aa = request.POST['p_user'] parents = ParentsProfile.objects.all().filter(Parent_User=aa) student = request.POST.get('parentsID') students = StudentProfile.objects.filter(Parent_Users = student) print(students) return render(request, 'accounts/ParentsProfile.html', {"parents": parents, "students": students}) except ParentsProfile.DoesNotExist: messages.warning(request, 'Please correct the error below.') return render(request, 'accounts/Plogin_form.html') //html {% for me in parents %} <input type="hidden" value="{{me.id}}" name="parentsID" id="parentsID" onchange="" readonly> {% endfor %} //model class StudentProfile(models.Model): . . . Parent_Users = models.ForeignKey(ParentsProfile, related_name='+', on_delete=models.CASCADE,null=True,blank=True,) -
How do we handle 'View Live' while creating a page/child page in a decoupled wagtail project?
I have a decoupled wagtail project in which front-end is served by ReactJS. Front-end build files are served from /proj_dir/frontend/react and is defined in /proj_dir/settings/base.py as STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj_dir/frontend/react', "build", "static"), ] STATIC_URL = '/static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'projdir/frontend/react')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtail.contrib.settings.context_processors.settings', ], }, }, ] So when I 'build' the react application, this frontend application is served on 'python runserver' How can I handle the 'View Live' scenario when we create a page/child page in this case. In order to reduce the development time is it possible not to write template files for each pagetypes? -
Rewrite URL in Django 1.10
Looking for how to convert this to Django 1.10: ('^plugins/(?P<path>.*)$', 'redirect_to', {'url': '/static/plugins/%(path)s'}), Basically I have ~50 files in a HTML theme that reference files at /plugins/blah-blah and I want to serve via /static/plugins/blah-blah. So any request to /plugins/ should go to /static/plugins - any idea how? -
Django provide GET variable to the filter from template
I have filter which has one field lawyersspec__lawyer_spec. To use this filter there is form which works fine and is available on website A, but I want to have links to this website with filter already set to some value. (i.e. lawyersspec__lawyer_spec=2) filters.py class LawyerFilter(django_filters.FilterSet): class Meta: model = TestPy.models.Lawyer fields = ['lawyersspec__lawyer_spec'] def __init__(self, *args, **kwargs): super(LawyerFilter, self).__init__(*args, **kwargs) views.py object_list = TestPy.models.Lawyer.objects.filter(Q(confirmed=True) & Q(is_active=True)) filter = LawyerFilter(request.GET, queryset=object_list) template.html {% for i, spec in specs.items %} <a href=" {% url 'lawyer-list' %}?lawyersspec__lawyer_spec={{ i }}">{{ spec }}</a> How can I achieve this? I've tried setting url in template as {% url 'lawyer-list' %}?lawyersspec__lawyer_spec=value but it's not working. I mean, the filter is the form is set to proper one, but results aren't filtered. I've checked if the lawyersspec__lawyer_spec is available in GET and it is there, but for some reason filter is not filtering according to those variable. -
How can I make an ORM query that leverages MySQL late row lookups?
In my django application I have defined a model like so: class NamedContainer(models.Model): name = models.CharField(max_length=50) capacity_ml = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name', 'capacity_ml'] Over time, this table has grown big enough to start causing some query performance issues, specifically when relying on limit/offset for slicing. Other slicing methods may have better performance by design, but for now I'm stuck with limit/offset, unfortunately. However, MySQL has a technique called "late row lookups" which greatly helps with my problem and, in short, a raw MySQL query using this technique could look something like SELECT t2.* FROM ( SELECT * FROM `core_namedcontainer` WHERE `updated_at` >= '2019-01-01 05:00:00.000Z' ORDER BY id ASC LIMIT 500 OFFSET 10000 ) AS t1 JOIN `core_namedcontainer` AS t2 ON t1.id = t2.id ORDER BY `name` ASC, `capacity_ml` ASC I have only managed to mangle the ORM query to produce a query like SELECT * FROM `core_namedcontainer` WHERE ( `core_namedcontainer`.`id` IN ( SELECT U0.`id` FROM `core_namedcontainer` U0 WHERE ( U0.`updated_at` >= 2019-01-01 05:00:00 ) ORDER BY U0.`name` ASC, U0.`capacity_ml` ASC LIMIT 500 OFFSET 10000 ) ) ORDER BY `core_namedcontainer`.`name` ASC, `core_namedcontainer`.`capacity_mL` ASC which simply uses a subquery instead of a join to … -
Django not validating values changed with JS
I've been trying to simulate some sort of picklist on Django forms, where there's 3 SelectMultiple involved, all begin in Area field, when Area is changed the field Course_Area is reloaded with the Courses related of the Area selected(this part is already working) and finally the field Course where the problem happens, the Course field should be filled with the non repeated selected objects from Course_Area a task that from what i've searched is better performed with JS, with my actual JS code the selected items from Course_Area are being passed to the Courses field but when the form is submited the Course field dont pass on the validation phase. Any help would be welcome. Form code: class MyEntityForm(forms.ModelForm): area = forms.ModelChoiceField( label='Area', queryset=Area.objects.all(), required=False, empty_label='Area', widget=forms.Select(attrs= {'onchange': "filterCourses();"} ) ) courses_area = forms.ModelMultipleChoiceField( label='Courses by Area', queryset=Curso.objects.none(), required=False, widget=forms.SelectMultiple(attrs= {'onclick': "addCourse();"} ) ) class Meta(): model = Entidade fields = ['area', 'courses_area', 'courses'] The JS code: function filterCourses(){ area_id=document.getElementById('id_area').value; $.ajax({ url: '/myentity/ajax/load_courses/', data: { 'area': area_id, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { $("#id_courses_area").html(data); } }); } function adicionaCurso(){ $("#id_courses").append( $("#id_courses_area option:selected")); } -
Accessing json objects with spaces in html table
Apologies if this has been asked before but I can't seem to find the answer. I'm super new to html/java/django but I feel like this shouldn't be this hard and is a stupid question but I'm going crazy over it. I'm making a web app that pulls json data from firebase so I'm using python/pyrebase/django etc. and I simply need to access a json object from my database and put it into an html table. It all works great, except accessing the child that has spaces in it (unfortunately I need to keep the spaces in for my mobile app purposes). I assumed it would be the same at dot/bracket notation but this doesn't seem to work. I've also tried declaring a variable <script> var score = 'JUDGE A RUN 1: '; </script> and using result.score with no luck but maybe I'm putting it in the wrong spot or something silly. <div class="container"> <h2></h2> <p></p> <table class="table table-striped"> <thead> <tr> <th>BIB</th> <th>Ridername</th> <th>Stance</th> <th>Score</th> </tr> </thead> <tbody> {% for result in data%} <tr> <td>{{ result.bib }}</td> <! works! > <td>{{ result.ridername }}</td> <! works! > <td>{{ result.stance}}</td> <! works! > <td>{{ result['JUDGE A RUN 1: '] }}</td> <! doesn't work … -
Django Stale CSRF Token
I set up my django application to perform email confirmation when a user signs up using the code from this tutorial. When I test it, I go to the sign up page, fill out the required fields, and submit. The page sends me to the login page. I go check my email and click the link provided to activate my account which creates a new tab. Then, I go to the other tab containing the login page (which we were redirected to previously) and enter the information to login. Unfortunately, I am met with an invalid/missing csrf token page. After pressing back, and logging in again, it is successful! What is the problem here? And how do I solve it? When I click the link in the activation email, is a new csrf token generated and the other tab that has the login page has the old csrf token which is causing the issue? How do I fix this? -
Setting bulk_create to a variable (Django)
I'm using bulk_create to create multiple profiles: def bulk_create_and_get(cls, profile_ids): tickets_to_create = [] for profile_id in profile_ids: ticket = cls(profile_id=profile_id) tickets_to_create.append(ticket) cls.objects.bulk_create(tickets_to_create) Were the cls is the Ticket Class model Can I save my bulk_create to a variable and return it? created_tickets = cls.objects.bulk_create(tickets_to_create) Instead of querying for the tickets I just created? created_tickets = cls.objects.filter( Q(profile_id__in=profile_ids) | Q(unregistered_profile_id__in=profile_ids) ) return created_tickets -
How to prevent Django object from sending signal when I use save in the function that receives the post_save?
So I am trying to post process the content of an object after it is saved. @receiver(post_save, sender=Model) def changed_model(instance, **kwargs): ... ... model.data = post_processed_data model.save() And this leads to the function calling itself forever. -
URL to static files with django-storages
I have set Django to serve static files from an S3 bucket using django-storages. Unfortunately the urls to the static files look like: https://[bucket name].s3.amazonaws.com/profile_pics/[filename]?AWSAccessKeyId=[...]&Signature=[...]&Expires=[...] Is there way to encode the urls to avoid revealing the AWS access key and signature? -
How do I get data assume html name is very similar to each other? (Django) (POST method)
Let say I have a dynamic html form (POST method), user can click 'add item' to add as many item as they like. Each item attribute after added is named like this: name="item1", name="item2", name="item3"... What should I do from view.py to loop through this list of items and save each item in my Item model? I know how to get 1 item, but not a list of item since i don't know how many item user is going to add. -
How to perform django full text searchvector on one model object field
I have the following model which has response_results json field which contains large dataset of json objects: My model Response_Grab has only one object with id 8 , i'm strong all data in one object, from django.contrib.postgres.fields import JSONField,ArrayField from django.contrib.postgres.search import SearchVectorField class Response_Grab(models.Model): response_domains = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) response_results = JSONField(blank=True,null=True,default=dict) response_grab_interval = models.IntegerField(default=48) search_vector = SearchVectorField(null=True) response_results jsonfield format example: { "http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}, "https://facebook.com":{"Version":"1.0","Server":"Apache"}, ... ... } Here's what I did so far: >> from elasticapp.models import Response_Grab as rg >> from django.db.models import TextField >> from django.db.models.functions import Cast ### TO Convert JSON to Text >> rg.objects.annotate(search=SearchVector(Cast('response_results',TextField())),).filter(search='http://google.com') <QuerySet [<Response_Grab: default>]> How do I query such that providing following KEY http://google.com should return all its values i.e {"Version": "1.0", "Server": "AkamaiGHost"}? -
Django: Safely Remove Old Migrations?
I've got a Django app with a lot of out-of-date migrations. I'd like to remove the old migrations and start fresh. The app has 14 different "migrations" folders. Here is what a few of them look like: Is it safe to remove all the contents from each of these folders? Or, do I have to make sure to only remove some of the files -- and if so which files?