Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use old database backup
I have 2 servers: production (master branch) and test (dev branch). On my local machine I work on dev branch, it has all the latest features and the newest DB schema. Now I need to inspect some problems that occurred on the production server. For that I want to download DB backup from production server onto my local machine and do some manipulations with it. On my local machine I have a postgres running and that is where my local DB is stored. What I usually do is drop local DB, apply the backup instead of what I've deleted and that works fine. I am able to work with the database. However, if the production database is several migrations behind the local database (which happens often) than I get Django migration errors when I try to apply all the latest migrations. The errors are usually like some_relation / some_column already exists. Probably, that happens because Django tries to apply all migrations starting at the very first one. To work this around I usually run all migrations with --fake option, than make small changes in models (like blank=True), just enough to create new migration which I apply then. After that I … -
Can I convert html in dict?
How can I paste/convert code html. I get code from file .txt and function like {for} etc. it's paste as text. respone = { "Pic" : str(File_read_to_div.readline()), "h1" : str(File_read_to_div.readline()), "WpisChild" : File_read_to_div.readline(), "Messags" : list(Messages) } return JsonResponse(respone, safe=False) And now in site I see {for} as text in div. Objects are not displayed. -
Django template data update using ajax
I am trying to update my data periodically (10 seconds) on a Django template using ajax scripts. I am relatively new in developing the front end. Using other articles, I am able to do so. But everytime page refreshes, multiple threads for page refreshing are created and update requests are doubled every 10 secods. Following is my django template snippet: <body id="page-top"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr class="table-info"> <th style="text-align:center">Parameter</th> <th style="text-align:center">A</th> <th style="text-align:center">B</th> </tr> </thead> <tbody> {% for para, details in manualData.items %} <tr> <th style="text-align:center" scope="row">{{ details.1.name }}</th> {% for key, entity in details.items %} <td style="text-align:center"> <font color="white" size="4px">{{ entity.value }}</font> </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </body> I am using ajax script as follows: <script type="text/javascript"> function refresh() { var_ref = $.ajax({ success: function (data) { $('#page-top').html(data); } }); } $(function () { setInterval('refresh()', 10000); }); </script> Conclusively, all I need is to once the refreshing process is defined, new process should not be created or else past process to be aborted if new process is to be defined. Kindly help me to attain the same. Thanks in advance Nakul -
Django: How to load dynamic data to chartjs
I want to load my models' data into a chart, using chartjs. Curiously, only the 'dummy-data' is working, that looks as follow: data: { labels: ['red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 7], My raw data looks like this: labels = ['/truck-alerts-analysis/fleet-history', '/truck-alerts-analysis/map-view', '/truck-alerts-analysis/fleet-status', '/truck-alerts-analy sis/truck-history', '/truck-alerts-analysis/truck-history', '/truck-alerts- analysis/fleet-status', '/truck-alerts-analysis/truck-histor y', '/setup/QCFcKp', '/reset-password', '/login'] data = [251, 243, 238, 220, 174, 158, 151, 88, 87, 86] Using django, I defined these values in views.py as follow: def pages(request): showData = start_date pageV = PageView.objects.all() FPage = FinalPage.objects.all() typeUser = list(FinalPage.objects.values_list('page', flat=True)) count = list(FinalPage.objects.values_list('sessionCount', flat=True)) # manipulation in order to get the right labels that I want t=[] for i in typeUser: new = i.split("?", 1)[0] t.append(new) k = t[-10:] c = count[-10:] # Where the labels and data is being returned return render(request, 'gaapp/pages.html', {"showData": showData, "labels": k, "data": c}) The curious behaviour is that, when calling for {{labels}} and {{data}} in the HTML file (where the chart is being processed), only the {{data}} is being excepted? In other words, the {{labels}} aren't valid. I don't understand why? Please help My HTML: <div class="PageMines"> <canvas id="myChart1" width="40" height="30"></canvas> … -
Why my modal in django not show me autocomplete values?
I have a data table in which in the last column there is the button"edit" that give me the possibility to modify the value of each row data with a ajax query. All works fine, but I want that when I click on the button "edit" the modal pop-up is autofilled with row value, that after I can manually modify. I attached below the part of the code that I think does not work: <tr id="element-{{element.id}}"> <td class="elementcodice userData" name="codice">{{element.codice}}</td> <td class="elementtipologia userData" name="tipologia">{{element.tipologia}}</td> <td class="elementsottocategoria userData" name="sottocategoria">{{element.sottocategoria}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> Modifica</button> </td> </tr> and jquery code: function editUser(id) { if (id) { tr_id = "#element-" + id; codice = $(tr_id).find(".elementcodice").text(); tipologia = $(tr_id).find(".elementtipologia").text(); sottocategoria = $(tr_id).find(".elementsottocategoria").text(); $('#form-id').val(id); $('#form-codice').val(codice); $('#form-tipologia').val(tipologia); $('#form-sottocateogira').val(sottocategoria); } } Where is the problem? -
Can I use django conditionals inside css?
I have a static css file in my django app static directory. I have multiple views running of the same css file, since otherwise there would be A LOT of copy and pasting, but I need just a few things to be different depending on the page I'm currently on. Is it possible to use the django conditional statements like {% if request.path == ... so on inside the static css file? Or if not what would be a sensible alternative that would achieve the same result? Because the class header.masthead is used about 10 times in the CSS file and if I had to write a new, let's say, header.mastheadcookiepage and assign the same functionality, and do this for multiple new pages, that would be really annoying. Perhaps this is a stupid question and I'm approaching this problem the wrong way, but I'm quite new to web developement, so any help is appreciated! -
Unable to receive mail but submit successfully: Contact Form Django
I was trying to make contact form for my website, its loading, working and submitting successfully but i'm not receiving any mail from my website. I also created a form like that for reset password its working but not this why? my html <div class="blog_list"> <form method="POST"> {% csrf_token %} <h2 class="blog_heading">Contact Us</h2> <fieldset class="form-group"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> my views.py def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] messages.success(request,f'Message sent successfully!') return redirect('Love Travel-home') try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, "shop/contact.html", {'form': form}) my forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER = os.environ.get('django_user') EMAIL_HOST_PASSWORD = os.environ.get('django_pass') I made contact form it submits it successfully but i didn't receive mail, can anyone please help me? -
Pagination issue in Django
I have a database in my Django project on which I am making queries. I would like to display the responses in different pages. If the request is "none", the pagination works flawlessly. But whenever I pass a query, first page displays the responses I am looking for but next pages are behaving like request were "none". Here is my views.py def search(request): query = request.GET.get('query') if not query: products_list= Product.objects.all() else: products_list = Product.objects.filter(name__icontains=query) if not products_list.exists(): products_list = Product.objects.filter(brand__icontains=query) title = "Results: %s" % query paginator = Paginator(products_list, 9) page = request.GET.get('page',1) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context = { 'products': products, 'title': title, 'paginate': True, } return render(request, 'finder/search.html', context) And the html: <nav aria-label=""> <ul class="pager"> {% if products.has_previous %} <li><a href="?page={{ products.previous_page_number }}">Previous</a></li> {% endif %} {% if products.has_next %} <li><a href="?page={{ products.next_page_number }}">Next</a></li> {% endif %} </ul> </nav> -
Python About using regular expression in pandas for integer search
I used django for a search feature improvement,Enter the character you want to search in the screen that the user enters, convert it to an integer to match the specified field, file and convert it to dataframe, so it has been done so far new_fmt = int(new_fmt) some1 = df[(df[19].str[:8] == new_fmt )] user input is new_fmt, but user need to input the exact corresponding input, so what I want to ask is like, when user input 26660000, The code separates The first four inputs and assigns The last four to [0-9] [0-9] [0-9] [0-9], after using regular expression input to four matches, such as user input: 26660000, The matches of 26660000-26669999 are displayed in dataframe,Instead of just matching the output 26660000 . When I looked up other materials, I learned that re can only be used for str, while the table I imported in pd is int, so this bothers me a lot. I hope to get a solution, thank you -
Django - Vue.js cascading dropdown
I’m trying to make a cascading dropdown. I’m using Vuejs, Django and django Rest Framework. I tried with this example : https://jsfiddle.net/mani04/Lgxrcc5p/ but I don’t understand how to implements the « places » (in example attached) with my own objects from API. To understand you can fin below : Model.py class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) class Meta: managed = True db_table = 'affaires' def __str__(self): return '{} - {}'.format(self.id, self.nom) class AffairesOfs(models.Model): idaffaire = models.ForeignKey(Affaires, models.DO_NOTHING, db_column='idAffaire') # Field name made lowercase. nom = models.CharField(max_length=50) class Meta: managed = False db_table = 'affaires_ofs' def __str__(self): return '{}'.format(self.id) This is my HTML & scripts : <div id="starting"> <div class="container"> <div class="row"> <form class="form-group"> <label>N° d'affaire</label> <select class="col"> <option value="choisir">Choisir :</option> <option v-for="affaire in affaires" value="${affaire.id}">${affaire.id} - ${affaire.nom}</option> </select> <label>N° d'OF</label> <select class="col"> <option value="choisir">Choisir :</option> <option v-for="of in ofs" value="${of.id}">${of.id} - ${of.nom}</option> </select> <input type="submit" value="Valider" class="btn btn-success" /> </form> </div> </div> <div class="loading" v-if="loading===true">Loading&#8230;/div> </div> <script type="text/javascript"> new Vue({ el: '#starting', delimiters: ['${','}'], data: { ncs: [], affaires: [], ofs: [], loading: false, currentNc: {}, message:null, newNc: {'idof': null, 'idrepere': null }, }, mounted: function() { this.getNcs(); this.getAffaires(); this.getOfs(); }, methods: { getNcs: function() { this.loading = … -
Make django handle subdomain suffix
We're hosting several dockerized web-apps on our webserver, let's call it group.example.com. Our subdomains are handled via nginx as suffixes though, which translates to something like group.example.com/app1/ group.example.com/app2/ as root urls. When using Django, we run into problems though, as all its urls generated by url in the templates such as <a href="{% url 'index' %}">home</a> will be relative links, so rendered to <a href="/">home</a>. This relative link will not be interpreted correctly, leading to the main, non-app page group.example.com. So the goal is to have an app based prefix such as /app1/ for all links. I can hardcode these for static links, but there has to be a more elegant way. Also this leads to problem for the used forms submitting to the wrong page - redirecting again back to the main, non-app page group.example.com. I tried adding /app1/ to all registered urls as prefix, but that doesn't seem to work either - that way the app is running but user would need to visit group.example.com/app1/app1/ to get to the index, and the relative links still don't work correctly. In the app docker-container we're running the web-app with nginx and uwsgi. It works fine when using correct subdomains such … -
Trying to understand django url namespacing
I was going through the Django docs, here they're talking about removing hardcoding in urls so that its easier to modify urls in the future. This is how a hardcoded url looks like <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> After removal of hardcoded string <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> This is all well and done. What's confusing me is the namespacing part from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here the app_name variable is introduced to store the app name, polls in this case. But in the view they have gone and specified <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> Isn't this the same as before? I mean the hardcoded URL issue is right there... What is the design pattern behind this. Why can't they just look at the app folder and get the app name from there? -
How do I access separate Django-entangled JSONField items in a form with jinja?
does someone have an idea how I get individual entangled_field items into my form? Here's my code, I'll explain further down (in form.html) where I'm having issues. models.py class Project(Model): """Project Data""" eeg = JSONField() meg = JSONField() forms.py class ProjectForm(EntangledModelForm): """HTML form for Project objects https://github.com/jrief/django-entangled""" nosessions = IntegerField(required=False) sessionduration = IntegerField(required=False) hoursrequired = IntegerField(required=False) esthourspermonth = IntegerField(required=False) class Meta: model = Project entangled_fields = { "eeg": [ "nosessions", "sessionduration", "hoursrequired", "esthourspermonth", ], "meg": [ "nosessions", "sessionduration", "hoursrequired", "esthourspermonth", ], } untangled_fields = [..working fields..] Django object proj112 = Project.objects.get(name='112_test') for k,v in proj112.eeg.items(): print(k,v) nosessions 5 hoursrequired 10 sessionduration 2 esthourspermonth 10 for k,v in proj112.meg.items(): print(k,v) nosessions 10 hoursrequired 20 sessionduration 2 esthourspermonth 20 detail.html - I can successfully access/list the keys and values for both 'eeg' and 'meg' once they are created (manually via the api or database). <table> <b>EEG</b> {% for key,value in project.eeg.items %} <tr> <td>{{key}}</td><td>{{value}}</td> </tr> {% endfor %} </table> <table> <b>MEG</b> {% for key,value in project.meg.items %} <tr> <td>{{key}}</td><td>{{value}}</td> </tr> {% endfor %} </table> form.html - This displays the field correctly but inserts data to both 'eeg' and 'meg'. {{ form.nosessions|as_crispy_field }} I want to reference them separately as I have a … -
I am facing a problem while trying to deploy python django app to heroku
-----> Python app detected cp: cannot stat '/tmp/build_f87e66a969d68e5390ddccb6b44523c7/requirements.txt': No such file or directory it constantly gives me this error and the app wont run its getting frustrated now can anyone help?? -
Django taggit with Count: the example from book
I am trying to understand the example from book "Django by Example". There is a blog application with tags. models.py class Post(models.Model): # ... tags = TaggableManager() views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post_detail.html', {'post': post, 'similar_posts': similar_posts}) From my point of view, annotate(same_tags=Count('tags')) will count all tags in each post in similar_post Queryset. Why does it pick and sum only the same tags as in my post? Thanks in advance -
How to groupby nested object elements In Django Rest FrameWork
How to use group-by for nested objects class RequirementInfo(models.Model): name = models.ForeignKey(PostJobRequirement, on_delete=models.CASCADE) class CandidataInfo(models.Model): name = models.ForeignKey(CandidateList, on_delete=models.CASCADE) rate = models.FloatField(null=True, blank=True) class SubmittedCandidateInfo(models.Model): requirement = models.ArrayField(model_container=RequirementInfo) candidate = models.ArrayField(model_container=CandidataInfo) def __str__(self): return str(self.requirement[0]) class SubmittedCandidate(CreateModificationDateMixin): submitted_candidate_id = models.IntegerField(default=sub_id, editable=False, primary_key=True) submit_candidate = models.ArrayField(model_container=SubmittedCandidateInfo) def __str__(self): return str(self.submitted_candidate_id) class Meta: verbose_name_plural = "submitted_candidates" db_table = "submitted_candidate" Serializer: class RequirementInfoSerializer(DjongoModelSerializer): class Meta: model = RequirementInfo exclude = ('id', ) depth = 1 class CandidataInfoSerializer(DjongoModelSerializer): class Meta: model = CandidataInfo exclude = ('id', ) depth = 1 class SubmittedCandidateInfoSerializer(DjongoModelSerializer): requirement = RequirementInfoSerializer(many=True, required=False) candidate = CandidataInfoSerializer(many=True, required=False) class Meta: model = SubmittedCandidateInfo fields = ('requirement','candidate') For Submitting candidates Here am generating number of records based on requirment*candidate computation class SubmittedCandidateSerializer(DjongoModelSerializer): class Meta: model = SubmittedCandidate fields = ('submitted_candidate_id','submit_candidate') def create(self, validated_data): submit_candidate = validated_data['submit_candidate'][0] submit_candidate_copy = submit_candidate['candidate'].copy() for _item in submit_candidate['requirement']: for index, _val in enumerate(submit_candidate_copy): validated_data['submit_candidate'][0]['requirement'] = [dict(_item)] validated_data['submit_candidate'][0]['candidate'] = [dict(_val)] message_obj = super().create(validated_data) return message_obj For viewing submitted candidates class ViewSubmittedCandidateSerializer(DjongoModelSerializer): submit_candidate = SubmittedCandidateInfoSerializer(many=True, required=False) class Meta: model = SubmittedCandidate fields = ('submitted_candidate_id','submit_candidate', 'interview_status', 'modification') Views: class SubmittedCandidateViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = SubmittedCandidate.objects.all() serializer_class = SubmittedCandidateSerializer class ViewSubmittedCandidateViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = SubmittedCandidate.objects.all() serializer_class = ViewSubmittedCandidateSerializer My … -
How to fix Page not found (404) error django2.0 for profile pages
How to fix Page not found (404) error django2.0 for profile pages this code views code ''' def profile(request, slug): profile = Profile.objects.get(slug=slug) context = { 'profile':profile, } return render(request, 'registration/profile.html' ,context) ''' and this urls.py ''' from django.urls import path,re_path from . import views from django.contrib.auth.views import LoginView,logout #login app_name='accounts' urlpatterns = [ path(r'', views.home, name ='home'), # path(r'^login/$', login, {'template_name':'registration/login.html'}), path('login/', LoginView.as_view(), name="login"), path(r'^logout/$', logout, name='logout'), # path(r'^signup/$', views.register, name='register'), path('signup/', views.register, name='signup'), path(r'^(?P<slug>[-\w]+)/$', views.profile, name='profile'), # path(r'^(?P<slug>[-\w]+)/edit$', views.edit_profile, name='edit_profile'), ] ''' profile.html page in templates /registration folder -
I do exactly as the tutorial says and my code has no syntax errors - but things still don't work
I do exactly as the tutorial says and my code has no syntax errors - but things still don't work. I need to verify a few things, can someone help with me in a chat please? It shouldn't take more than 5 minutes I'm sure. Would highly appreciate it, thanks! -
(1048, "Column 'cnic' cannot be null" , duplicate entry error, etc value cannot be saved in database through add_ser_save function
here is add_user_save function in managerviews.py def add_user_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") cnic=request.POST.get("cnic") contact_number=request.POST.get("contact_number") gender=request.POST.get("gender") #try: user=CustomUser.objects.create_user(username=username,password=password,email=email,last_name=last_name,first_name=first_name, user_type=3) user.passenger.cnic=cnic user.passenger.first_name=first_name user.passenger.last_name=last_name user.passenger.email=email user.passenger.contact_number=contact_number user.passenger.gender=gender user.passenger.save() user.save() #messages.success(request,"Successfully Added User") #return HttpResponseRedirect(reverse("add_user")) #except: #messages.error(request,"Failed to Add User") #return HttpResponseRedirect(reverse("add_user")) here is my models.py passsenger table class Passenger(models.Model): cnic=models.BigIntegerField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE, blank=False, null=True) manager_id=models.ForeignKey(Manager,on_delete=models.CASCADE, blank=True, null=True) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE, blank=True, null=True) fisrt_name=models.CharField(max_length=255, default='non') last_name=models.CharField(max_length=255, default='non') email=models.CharField(max_length=255, default='non') contact_number=models.IntegerField( null=True) gender=models.CharField(max_length=255, default='non') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.cnic do i have to change in the below function? I dont know what to add here (usertype =3 is passenger user) @receiver(post_save,sender=CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type==1: Manager.objects.create(admin=instance) if instance.user_type==2: Staff.objects.create(admin=instance) if instance.user_type==3: Passenger.objects.create(admin=instance) Problem is value is not added in database i trued a lot by adding blank=true, null=true but error changes every time. Sometimes comes on duplicate key on admin and sometimes like cnic cannot be null all that. Is there any issue in models.py? Help kindly so that i can save data from front end template to passenger table. -
Django is-instance is not working properly For UUID [closed]
I have UUID4 value= "2626df07-1854-4ff1-9296-fa43bc896950" for this value am trying import uuid print((isinstance(value, uuid.UUID))) Result is:- False can anyone please explain me the reason behind this. Note:-value is a proper UUId4 -
Python IF Statement using "Or" and "And"
Code Picture def delete(request, id): destroy = Appointment.objects.get(id=id) if destroy.status == "Done" or "Missed" or "Pending" and request.session["userid"] == destroy.user.id: destroy.delete() return redirect('/update/table') So my delete function works. However the code doesn't do what I'm wanting it to exactly. I want to do a triple check of the 3 strings("Done", "Missed" and "Pending") individually with the "and request.session["userid"] == destroy.user.id:" If I put: if destroy.status == "Pending" and request.session["userid"] == destroy.user.id: destroy.delete() Then it will only delete the object on the table I have created which has "Pending" in its status. So that works good. However... If I put: if destroy.status == "Pending" or "Done" and request.session["userid"] == destroy.user.id: destroy.delete() If I click my delete button on what ever has "Pending" it deletes, great. If I click on anything that has "Done", deleted, great. However if I click my delete button on anything that has "Missed" it still deletes it?? So my code is redundant by adding the 3rd string "Missed". I can't wrap my brain right now on why it still deletes the "Missed" if I leave it out. How do I clean this code up so it does what I'm wanting it to do. -
How can I save the django variable in the cookie for further usage?
Following is the output JSON data I'm getting when I hit the API, {'test_1': {'test_name': 'FASTING SUGAR', 'results': '121.00', 'units': 'mg%', 'low_range': 70.0, 'high_range': 110.0}} <tbody> {% for key, value in data.items %} <tr class="gradeX"> <td>{{ value.test_name }}</td> <td>{{ value.results }}</td> <td>{{ value.units }}</td> <td>{{ value.low_range }}</td> <td>{{ value.high_range }}</td> </tr> {% endfor %} </tbody> I'm getting the {{ data }} from the API that I want to save it in the cookie so that I can use the old value of {{ data }} to append it with the new one using jquery. -
Facing issues while converting django-cms into Headless CMS
My company is using django-cms as the CMS. However, recently we need to convert it into headless CMS so that we can have our custom view layer to improve speed and performance. I got a very few articles online but none of them helped Here is what I have understood till now: The core team for django-cms had started development for headless mode but it was not completed or is not supported now (visit article: https://www.django-cms.org/en/blog/2017/03/14/headless-django-cms/ for more details). I found 2 plugins such: djangocms-rest-api which was archived and it recommends using djangocms-spa djangocms-spa which looks like is a good choice but I am not finding any good documentation for the usage. Also, the git repository looks like is not frequently updated. There is django-rest-framework which seems can be integrated and used. Tried integrating it but there were a lot of errors. Requirement: Any plugin which can be easily integrated without frontend developers having the need to learn django/python in detail code wise (I am mainly looking for this option) If django-cms is not the best option then do I have another alternative cms which can easily accommodate this, is secure and performant. My impression is that djangocms-spa and django-rest-framework … -
Relative and Absolute Path in Python Django
I have succesfully, seperated my settings file to Development and Production settings. While trying to import from base (common to the two) I always get path error. When I try to do this in prod.py file from src.psm_website.settings.base import * and try to compile with the IDE, it works well ( I used a print statement to print from a variable from the base file) But when I try to deploy to Heroku, I get the error from src.psm_website.settings.base import * remote: ModuleNotFoundError: No module named 'src' remote: Then when I change the import statement to this from .base import * I get this error when trying to deploy in heroku raise KeyError(key) from None remote: KeyError: 'SECRET_KEY' Secret key is a variable in base file, meaning base was not imported and I get this error when I try to run from the IDE. from .base import * ImportError: attempted relative import with no known parent package I have init.py in all parent directory, making them pakages from what I have read. How can I solve this Python Version: 3.7.7 -
How to remove default delete confirmation message from django admin on overriding delete queryset method?
I want to override the default delete_queryset method in admin to prevent deleting last object. def delete_queryset(self, request, queryset): warehouses = self.model.objects.all() if warehouses.count() == 1: messages.error(request, "Can't delete last object") return False return super(WarehouseModelAdmin, self).delete_queryset(request, queryset) The deletiion is working fine but along with the error message, "Successfully deleted 1 Warehouse.", this message is also being displayed. How can I remove this success message?