Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make edit function to have the previous prepopulated content
I am trying to make the existing content to be the initial value of the textarea (i.e what the user typed before while adding that page should show when the user wants to edit the page.) when the user clicks on the Edit button. When I click on edit, the content previously written tends to go to the title page in the url. Can you please help show me why? VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) class EditPageForm(forms.Form): content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) def edit_page(request, title): entry = util.get_entry(title) if request.method == "GET": form = EditPageForm(request.POST, initial={ "content": entry }) else: form = EditPageForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return redirect('encyclopedia:entrypage', title) return render(request, 'encyclopedia/editpage.html', {'form': form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Edit</a> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") … -
Knockout js form is not saving in django
productscreate.html <form> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: $data.save" >Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script type="text/javascript"> var ViewModel = function () { var self = this; self.title = ko.observable(""); self.description = ko.observable(""); var PerData = { name: self.name, description: self.description, }; self.save = function () { //Ajax call to Insert the Employee $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: PerData, contentType: "application/json", headers: {'X-CSRFToken': csrftoken}, //cache: false, mimeType: "multipart/form-data", //processData: false, success: function () { window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new … -
Same Django Models Shared in two different Projects hosted at different urls
I have hosted a django project with one app on heroku. I have few models with too many data inside it . Now I wanted an another django project that will be hosted at example.herokuapp.com with same settings,views and everything as it is in keshavbits.herokuapp.com. Now the question is how can I access the Database hosted at keshavbits.herokuapp.com in the example.herokuapp.com . Or How can I share databases b/w these two apps at different locations. Kindly Help:) -
Django model with exactly 2 users references
I want to define a 'Game' model in which exactly (and not more) 2 users will compete. Each of this user can compete in another game in parallel or later. I thought about a Manytomanyfield, but I don't know how to restrict the number of users. How to do it? -
How to prefill django form Dynamically
I am trying to display a form in django and pre-filling it dynamically. I want the user of my sample news gathering site to modify an entry. I have my Manual Input form class #forms.py class ManualInputForm(forms.Form): source = forms.CharField(label="Source:", widget = forms.TextInput(attrs={'size': 97})) topic = forms.CharField(label="Topic:", widget = forms.TextInput(attrs={'size': 97})) news = forms.CharField(widget = forms.Textarea(attrs={"rows":5, "cols":100})) link = forms.CharField(label="Link (optional):", required = False, widget = forms.TextInput(attrs={'size': 97})) In the HTML I am going manually because I would like to pre-fill all fields with data coming in from the related function in views.py. #html file <form method="post" class="form-group"> {% csrf_token %} <div class="input-group mb-3"> <div class="container"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} <br> {{ field }} </div> {% endfor %} </div> <div class="input-group"> <p> </p> <button type="submit" class="btn btn-success" name="Submit">Save</button> </div> </div> </form> How do I do it? It's driving me crazy o.O I would like to keep using django's forms because of its integrated error manager (not all fields are required but some are and I'd like for django to keep managing it). Thank your for your suggestions! -
Declaring class name in variable
I am building a project and I am trying to declare class's name in variable before declaring variable. But when I declare variable like :- klassName = MyClass class klassName(models.Model): title = models.CharField(max_length=30) then it is assigning with KlassName Not the variable I referenced to it. Then I tried :- className = 'MyClass' klass = type(className, (object,), {'msg': 'foobarbaz'}) x = className() class x(): title = models.CharField(max_length=30) it is showing NameError: name 'className' is not defined I didn't find any documentation of declaring. I did follow according to This. But none is seemed to work for me. Any help would be much appreciated. Thank You in Advance. -
psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist
I hosted a django website on heroku I am unable to run migrations on it now , I tried resting database , running fake migrations , syncdb and some other possible solutions.Everything is working fine on my machine but migrations are not working on heroku I am unable to even open /admin this is the code . ~ $ python manage.py makemigrations Migrations for 'AIWeb': AIWeb/migrations/0007_alter_digitalnote_subjectname.py - Alter field subjectName on digitalnote Migrations for 'captcha': .heroku/python/lib/python3.9/site-packages/captcha/migrations/0002_alter_captchastore_id.py - Alter field id on captchastore ~ $ python manage.py migrate Operations to perform: Apply all migrations: AIWeb, admin, auth, captcha, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped … -
Django: SQL queries are slow due to complex sub-queries, how to split or speed them up?
I need to execute a query set with complex sub-queries like the one below. It takes a considerable amount of time to execute the query. (8000ms) I think the slowdown is caused by complex subqueries, but is it possible to split or speed up a single SQL query without generating N+1? The db lookup we are using and the slow query set this time # lookups.py class Groonga(Lookup): lookup_name = "groonga" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return "%s &@~ %s" % (lhs, rhs), params # queryset Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), ).filter( Q(title__groonga=value) | Q(tags__pk__in=Tag.objects.filter(name__groonga=value).values_list("pk")), is_public=True, published_at__lte=timezone.now(), ).order_by("-published_at").distinct()[:20] SQL query and EXPLAIN ANALYZE results SELECT DISTINCT "videos_video"."id", "videos_video"."published_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS … -
End a for loop if a certain condition is met in Django using templates
A similar question was asked before but the provided solutions did not work for me. Let's say I receive a list from the django views, for instance: context['requests'] = requests In the template: {% for r in requests %} {% if r.status == "Active" %} //do A {% else %} //do B {% endif %} {% endfor %} The requests list has 10 elements, one of them satisfies the condition of r.status == "Active". (invented example) What I want is: Check the requests list to determine if any of the elements in the list satisfies the condition of r.status == "Active" (or whatever condition, this is just an example) If some element in the list has the status Active the for loop will execute only one iteration, run the //do A code and then the loop will finish/break. If no element in the list has the status Active, the for loop will execute the //do B once and then break. I'm a bit confused and I don't know if there is another default tag to do this type of operation in Django -
pytest for django rest frame work api returns 301
I made simple Django application which returns {'result': 'OK'} for endpoint '/api/v1/test/ping/'. Now I am trying to test it with pytest. My test directory /test conftest.py /test_app test_api.py My conftest.py import pytest from rest_framework.test import APIClient @pytest.fixture def api_client(): return APIClient My test_api.py import pytest def test_api1(api_client): response = api_client().get("/api/v1/test/ping") assert response.status_code == 200 Test script execution fails: test_api.py::test_api1 FAILED [100%] test\test_gml_api\test_api.py:3 (test_api1) 301 != 200 But code works correct if I run server and check it manually! Give me please an advise how to solve this? -
How to youtube-dl video download directly to a user side not download file in local system using python Django?
I am trying to youtube videos to merge with audio(formate_id:140) and video(formate_id:313) using the youtube-dl library. But it downloads files in the local system. I want it directly download to the client side. I don't want to store files in the local system. Client-side means downloading files directly to a user system through a browser. Local system means it's my server. Example ydl_opts = { 'format': '313+140', 'keepvideo':'false', } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=Wt8VRxUYDso']) If any way like merging process and response streaming process work at a time. r = requests.get(videoUrl, stream=True) response = StreamingHttpResponse(streaming_content=r) response['Content-Disposition'] = f'attachement; filename="{fileName}"' return response Please guide me in solving this coding problem. -
default language url not working in Django Debug false mode
When Debug = True everything is working as expected, but when Debug is False, URL opens 404 page for default URL. For example my URL is like that -> www.example.com this is opens www.example.com/**en** automatically when debug true, but when debug is false it doesn't work and opens like that www.example.com/ and shows my custom 404 page. . Site is multilingual and I wrote urls.py like that urlpatterns = i18n.i18n_patterns( path('', include("core.urls")), Any ideas? -
CORS error after adding secondary database(Amazon Redshift) to Django
After adding secondary database(Redshift) to Django, I am getting CORS error 'no access control allow origin' in production environment. Frontend is React. Everything works fine when I run Django server on localhost, but as soon as I push changes, I get cors error on login. By the way login api call uses differnet database(Amazon RDS/MySQL). I have checked django cors headers. Configured VPC and security groups. But I still get the same error? Maybe someone have had similar issue before and could share some widsom or nudge in direction of the problem? Thanks in advance for your help. -
Django | Type error - missing 1 required positional argument: 'file_id'
Hello I'm trying to create a platform that will solve problems and then let the user download a file with the result. I'm having trouble with the downloading part this is the error I'm getting TypeError at /download/ download() missing 1 required positional argument: 'file_id' models.py class Snippet(models.Model): email = models.CharField(max_length=100) file = models.FileField(upload_to='documents/') def __str__(self): return self.email urls.py from . import views from .views import (snippet_detail) app_name = 'app' path('download/<int:file_id>/', views.snippet_detail, name='snippet_detail'), views.py def download(request, file_id): media_path = "/home/me/project/media/documents/" result_path = '/home/me/Desktop/' max_timeout = 1*24*60*60 #days*hours*mins*secs if request.method == 'POST': form = SnippetForm(request.POST, request.FILES) if form.is_valid(): form = Snippet(file=request.FILES['file']) form.save() file_name_final = form.file.name[10:] file_path = media_path + file_name_final ### analysis code ### data_id = test['outputs'][0].get('id') datamap = dict() datamap['0'] = {'src': 'hda', 'id': data_id} results_run = .. results_id = results_run['outputs'] file_id= ''.join(results_id) if file_id !='': filepath= 'result_path' + file_id path = open(filepath, 'rb') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; file_id=%s" % file_id return redirect('/download/{file_id}') else: raise Http404("No result file") download.html <p>Your problem is solved please click here to download <a class="btn btn-default btn-sm" title="Download the file" data-toggle="tooltip" data-placement="right" href="{% url 'app:snippet_detail' file.id %}"> <i class="bi bi-download"></i> </a> </p> -
Table relations with django models
I am having models for subjects like English , Biology and so on. and in the other side I have a model called teachers that store records of teachers .I am working on with Django and the problem is that I don't know how could I create the many to many relationship between teachers and the subjects what am trying to achieve is to assign the responsibility of teachers. I tried to make the models English ,Biology and others into one model called Subjects and later to use Manytomanyfield, but the frequencies are totally different and I stacked. some of my models are listed below. `class English(models.Model): studentID = models.IntegerField() l_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) s_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) r_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) w_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) hw_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) t_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) p_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) l_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) s_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) r_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) w_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) hw_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) t_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) p_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) def get_mark_30_first(self): sum = self.l_1+self.s_1+ self.r_1 + self.w_1 + self.hw_1 + self.t_1 +self.p_1 return sum def get_mark_30_second(self): sum = self.l_2+self.s_2+ … -
Getting : Not Found: /{% url "postQuestion" %} in Django app
So I am running this django app which is a FAQ knowledge base search engine. the app runs on localhost port 8000 whereas the BERT model runs on localhost 5000. Unfortunately, while clicking on "post a question" option on the front end html page, the request doesn't go to the view which is created. My App's view.py code snippet: def postQuestion(request): print ("---------------reposting-----------------") dataOwners=db.dataOwners if request.method=="POST": json_dict={} json_dict['User_ID']=request.user.id json_dict['Question_asked']=request.POST['question'] json_dict['Category']=request.POST['cat'] json_dict['Sub-Category']=request.POST['subCat'] moderator_document = dataOwners.find({'Category' : json_dict['Category']}) mods_list=[] for i in moderator_document: mods_list.append(i['Moderator']) json_dict['Moderators_available']=mods_list json_dict['Moderator_assigned']='null' json_dict['Status']="Pending Assignment" json_dict['Answer_given']= 'null' if 'revision' in request.POST and 'qid' in request.POST: json_dict['Comments']="Query details corrected" questionColl.find_one_and_update({"_id" : ObjectId(request.POST['qid'])}, {"$set": {"Question_asked":json_dict['Question_asked'],"Category":json_dict['Category'] ,"Sub-Category":json_dict['Sub-Category'],"Moderators_available":mods_list,"Comments":json_dict['Comments'],"Status":json_dict['Status'] } },upsert=True) else: json_dict['Comments']=request.POST['comments'] questionColl.insert_one(json_dict) data=json.loads(json_util.dumps(json_dict)) return HttpResponse(data) I idea is that when someone post a question from the html front-end, the control goes to the above function which then puts the question details in a database collection (local mongodb). The data is being collected through a ajax call which should push the question details to "postQuestion" view. However I am getting an error like below: [28/Dec/2021 15:20:27] "POST /%7B%%20url%20%22postQuestion%22%20%%7D HTTP/1.1" 404 5624 Not Found: /{% url "postQuestion" %} My ajax call snippet: // Post a question ajax call // $(document).ready(function(event){ $(document).on("click","#postQuestion",function(event){ event.preventDefault(); //data to … -
This field is required DRF on server side only
I created a django restframe work api which is working fine locally. But when I moved it to the server, it stop working. On server i am getting this { "file_name": [ "This field is required." ] } Here is the code view.py class VideoUploadViews(APIView): def post(self, request): serializer=VideoUploadSerializer(data=request.data)#acess the data if serializer.is_valid():#check validation start=time() vid_path=serializer.data["file_name"] vid_path=os.path.join(settings.S3PATH,vid_path) pred_hr=inference.predicthr(vid_path) end=time() return Response({"status": "success", "predicted hr": pred_hr,'time taken':end-start},\ status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class VideoUploadModel(models.Model): file_name = models.CharField(max_length=100,blank=False, null=False) serializer.py class VideoUploadSerializer(serializers.ModelSerializer): class Meta: model=VideoUploadModel fields='__all__' -
Getting issue while working with django ORM or raw sql query
list_edit_drivers.html -this is html file for showing data at front end $(document).ready(function () { $.extend(true, $.fn.dataTable.defaults, { columnDefs: [ { targets: '_all', defaultContent: '' } ] }); var table = $('#drivers').DataTable({ "pageLength": 100, "serverSide": true, "bSearchable":true, "dom": 'blfrtip', "ajax": "/fleet/dt/editdrivers/?format=datatables&city_id={{city_id}}", "columns": [ { "data": "employee_id", "mRender": function (data, type, full) { return '<a href="/fleet/driver/list_drivers/{{city_id}}/view/' + full.id + '">' + full.employee_id + '</a>'; 123 } }, { "data": "uber_name" }, { "data": "mobile" }, { "data": "uber_device_no" }, { "data": "aadhar_no", "bVisible": false, }, { "data": "location.name" }, { "data": "status" }, { "data": "id", "bSortable": false, "mRender": function (data, type, full) { return '<a class="btn btn-sm btn-primary" href="/fleet/driver/list_drivers/{{city_id}}/edit/' + full.id + '">' + 'Edit' + '</a>'; } }] }); }); urls.py -ajax call DriverViewSet url and html render list_edit_drivers url router.register(r'dt/editdrivers', views.DriverViewSet) path('driver/list_drivers', views.list_edit_drivers, name='list_edit_drivers') views.py @method_decorator(login_required, name='dispatch') class DriverViewSet(viewsets.ModelViewSet): queryset = Driver.objects.filter(is_active=1) serializer_class = DriverEditListSerializer def get_queryset(self): queryset = Driver.objects.filter(is_active=1, city_id=self.request.GET.get('city_id')) return queryset @login_required def list_edit_drivers(request): driver = Driver.objects.filter(city_id=request.session['global_city_id']) context = { 'menu_hiring': 'active', 'submenu_driver_edit_list': 'active', 'driver': driver, 'city_id': request.session['global_city_id'] } return render(request, 'hiringprocess/list_edit_drivers.html', context=context) serializers.py class DriverEditListSerializer(serializers.ModelSerializer): city = CitySerializer(read_only=True) location = LocationSerializer() class Meta: model = Driver fields = ( 'id','employee_id','employer', 'name','uber_name','uber_device_no', 'mobile', 'location', 'city','shift','status', 'aadhar_no') ** … -
HOW TO CONNECT BACKEND WITH FRONT END IN DJNAGO FARMEWORK
I have a front-end team which has made a static website using html, css and javascript. Now i want to add these files in django. How do i add these files -
Connect with django channels from external script
I have a django server with a websocket running, in the same system I have another python application which I can't add in django. I am trying to connect with django channels with python redis SDK. (I am using redis in django channels) My current approach is to find a way to connect to the redis client for django channels and send and receive message through it. (I am not sure even if it is possible) import redis r = redis.Redis(host='localhost', port=6379, db=0) group_name = "MY_GROUP" for x in r.client_list(): print(x) # how to connect to client here and send and receive message? Another solution will be to make a direct websocket connection using websockets lib, but can we do it with redis directly. -
Errno 13 Permission denied: '/home/ubuntu/Demo/website/media/image_banner/download.jpg'
I built a Web site using the Django framework, one of which was to process images uploaded by the admin and save them in a folder for media/image_banner, but encountered an error ([Errno 13] Permission denied: '/home/ubuntu/Demo/website/media/image_banner/download.jpg'. I use python manage.py runserver and it works, but it doesn't work when deployed with Apache2. -
cannot retrieve many to many all objects in django
when i try to retrieve all cart items from order model then click to open cartitem model edit page but i got first cart item only so what is wrong my code Admin Model class OrderAdmin(admin.ModelAdmin): list_display = ('user', 'total_price', 'ordered', 'get_address', 'get_cart') def get_cart(self, obj): for p in obj.items.all(): app_label = p._meta.app_label model_label = p._meta.model_name url = reverse( f'admin:{app_label}_{model_label}_change', args=(p.id,) ) return mark_safe(f'<a href="{url}">{p.item}</a>') get_cart.allow_tags = True get_cart.short_description = "Cart" Order Model class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(CartItem,) ordered = models.BooleanField(default=False) total_price = models.FloatField(default=0) start_date = models.DateTimeField(auto_now_add=True) payment_id = models.CharField(null=True, blank=True, max_length=100) ordered_date = models.DateTimeField() address = models.ForeignKey( Address, on_delete=models.DO_NOTHING, blank=True, null=True) class Meta: ordering = ['-ordered_date'] def __str__(self): return str(self.user.username) + ' '+str(self.total_price) def user_link(self): return '<a href="%s">%s</a>' % (reverse("admin:auth_user_change", args=(self.user.id,)), escape(self.user)) -
Wagtail 'View live' button provides wrong url after page creation while using id as slug
I have a case that uses Page ID as a slug, after creating a new Page, Wagtail provides us a "View live" button but when we click on that button, it provides a wrong URL The right URL should be ".../property-list/<property-id>" I have searched on stack overflow, found this thread but the answer is still a mystery: Wrong 'View live' url in Wagtail admin message after page creation when using id as slug I have followed the Wagtail official document, using Wagtail Hooks to manipulate data. However, no success yet. This is my code: @hooks.register('after_create_page') def set_number_and_slug_after_property_page_created(request, page): page.number = page.slug = str(page.id) page.save() new_revision = page.save_revision() if page.live: new_revision.publish() Please help me, thank you. -
Problem importing ModelResource from tastypie.resources
Good day, I'm currently on the middle of a practice project for django and can't seem to find a solution to a problem when creating an api with tastypie. I'm currently in the middle of learning so any help would be appreciated. I'm using django 4.0 and tastypie 2.8.2. Here's the code which seems to be the problem: from django.db import models from tastypie.resources import ModelResource Here's the full error I'm getting when attempting to execute python3 manage.py runserver on my venv: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/core/management/init.py", line 381, in execute autoreload.check_errors(django.setup)() File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/user/.local/share/virtualenv-path/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "frozen importlib._bootstrap", line 1030, in _gcd_import File "frozen importlib._bootstrap", line 1007, in _find_and_load File "frozen importlib._bootstrap", line 986, in _find_and_load_unlocked File "frozen … -
TypeError: do_something_on_deactivation() missing 1 required positional argument: 'instance_id' in django
Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\activatable_model\models.py", line 109, in save model_activations_changed.send(self.__class__, instance_ids=[self.id], is_active=current_activable_value) File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\django\dispatch\dispatcher.py", line 182, in send for receiver in self._live_receivers(sender) File "C:\Users\OneDrive\Desktop\GFG\gfgvenv\lib\site-packages\django\dispatch\dispatcher.py", line 182, in <listcomp> for receiver in self._live_receivers(sender) TypeError: do_something_on_deactivation() missing 1 required positional argument: 'instance_id' I am getting this error when I am saving my Django custom model object. This is my Model.py file from django.db import models # Create your models here. class MyModel(models.Model): username = models.CharField(max_length=15) pass1 = models.CharField(max_length=50) is_active = models.BooleanField(default=False) In the python manage.py shell I ran >>>from authentication.models import MyModel >>>obj = MyModel.objects.all()[0] >>>obj.is_active = True >>>obj.save() Not sure where I am wrong, even though it throughs an error, the changes are being made