Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modal popup to delete object in django
I am using django generic DeleteView() for deleting object from my database. The deleteview is working fine. But I want a alert message before deleting the object. I have a ListView for showing the objects list in a table. In that table i have a trash icon, when user presses the trash icon it redirects to delete url and deletes the object. But i dont want to go a different page for my deletion instead I want to stay on that list page and want a popup alert message if i want to delete the object. if i click the yes button it deletes the object staying on that page and refreshes the list table. I have tried several codes for this. <button action="{% url 'employee:employee-delete' employee.id %}" type="button" name="button" class="btn btn-dnager" onclick="document.getElementById('deleteEmployee').style.display='block'"> <span data-feather="trash"></span> </button> <div id="deleteEmployee" class="modal"> <span onclick="document.getElementById('deleteEmployee').style.display='none'" class="close" title="Close Modal">×</span> <div class="modal-content"> <h1>Delete Account</h1> <p>Are you sure you want to delete your account?</p> </div> {% block footer%} {% include 'employee/employee_delete.html' %} {% endblock footer %} </div> currently I have above code for popup message and trash icon. when the icon is clicked a modal opens. employee_delete.html: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> … -
VS CODE: Unable to import - pylint(import:error)
I have a django project. In views.py file, I tried to import my models (or anything from MYAPP) like this: from MYAPP.models import * from MYAPP.api.user.serializers import * It shows me a warning "Unable to import 'MYAPP.~~'". My project is still running normally but VS-Code reported many errors so I don't know if it is true or not. How can I fix it? Thank you ^^. -
Django REST two token expiry periods
I am building an 2 APIs (two apps in the same django project) that will have two sets of users. 1 will be the normal system users e.g android users and and the other group will be other systems talking to my system. For the regular users, I want to set the tokens to expire in 5 hours. For the other systems, I would like their tokens to expire in like 5 days since they make a lot of requests per minute. Is this achievable in django rest in the same application (multiple token expiry durations depending on the application) -
Json data in Django
I'm trying to create a CRUD in Django using json Ajax , but in my views I'm getting an error that "The view accounts.views.create_order didn't return an HttpResponse object. It returned None instead." views.py def create_order(request): initial_date = { 'status':"In Progress" } form = OrderForm(request.POST or None, request.FILES or None,initial=initial_date, user=request.user) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.user = request.user; order.save() form = OrderForm(user=request.user) messages.success(request, "Successfully created") return redirect('/orderlist') context = {'form':form} html_form = render_to_string('accounts/templates/order_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) -
how implement api that call some dependent api?
Suppose admin can add api that later user use this ,api but sometime 2 api that admin added could dependent together how to handle in backend that one of response in for example add to header other api and send request and all things shall is dynamic thx -
Error to add something in database via admin page in Django
how to we solve this problem..?? migrate the database(with no error), but still, have this problem -
How do I return Visualization back in flask and display in html using Ajax/JavaScript?
```@app.route('/Bar',methods=['POST','GET']) def Bar(): x=sns.lineplot(data.da["R&D Spend"],data.da["Profit"]) return send_file(x)``` Now how do I do this. Please answer plain and simple as I'm new to coding. Please don't use database. ``` const xhr=new XMLHttpRequest(); xhr.open('POST','/Bar',true); xhr.getAllResponseHeaders(); xhr.onprogress=function(){ console.log('hello') } xhr.onload=function(){ document.getElementById('table1').innerHTML='<img src="this.responseText"';//Here I want to insert visualization } xhr.send(); } ``` -
Approach/Method/Tool for executing the task performed by an API request at user defined time
I am developing an application in Django which uses REST API. The API request performs a long-running Celery canvas task(chain of tasks- saves the input to the database, performs computation, and then saves the computation result to the database). This long-running task depends on the user's input. Now, I want to add a functionality that facilitates the user with performing this long-running task at a specific time given by the user himself, so how can I do that? i.e. Suppose, there are 2 users making the same API request with their own set of input parameters, and User 1 wants to schedule his task to be executed at 5:00 AM and user 2 at 7:30 AM. How can I achieve this? Frontend: Angular Backend: MySQL, Python (Django, Celery) Any help in this regard will be highly appreciated. -
django signals not creating user profile upon user creation
I'm trying to create a simple signal that creates a Profile object for a User after the user signs up a new account. What am I missing? signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile #from django_cleanup.signals import cleanup_pre_delete #from sorl.thumbnail import delete @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance, bio="", linkedin_URL="", isCoach=False) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() # def sorl_delete(**kwargs): # delete(kwargs['file']) # cleanup_pre_delete.connect(sorl_delete) apps.py from django.apps import AppConfig class EventsConfig(AppConfig): name = 'events' def ready(self): import events.signals -
Accessing Values Within A List Within A Dict Python
I have a formset in django which has multiple forms which I am saving as: manifestData = form.cleaned_data If I print(manifestdata) it returns the below: [{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}] I need to access each ProductCode and pop it from the list. So I am trying the below in my view: ... for item in manifestData: x = manifestData.pop['ProductCode'] #this is highlighted in the error message ... When I do this I get a TypeError reading that "an integer is required". Can anyone explain that to me / how I can navigate this issue? -
The approach to build memberships and subscriptions?
How should my memberships/subscription model look like? I have an app where every user should have a membership and an active subscription from what I've seen usually the approach is building 3 models a Membership, UserMembership and Subscription and they look like this class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, max_length=30,blank=True) price = models.IntegerField(default=15) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.username class Subscription(models.Model): user_membership = models.ForeignKey( UserMembership, on_delete=models.CASCADE) stripe_subscription_id = models.CharField(max_length=40) active = models.BooleanField(default=True) def __str__(self): return self.user_membership.user.username @property def get_created_date(self): subscription = stripe.Subscription.retrieve( self.stripe_subscription_id) return datetime.fromtimestamp(subscription.created) @property def get_next_billing_date(self): subscription = stripe.Subscription.retrieve( self.stripe_subscription_id) return datetime.fromtimestamp(subscription.current_period_end) and a signal that looks like this def post_save_usermembership_create(sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '': new_customer_id = stripe.Customer.create(email=instance.email) free_membership = Membership.objects.get(membership_type='Free') user_membership.stripe_customer_id = new_customer_id['id'] user_membership.membership = free_membership user_membership.save() post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) the stripe part is the gateway that's used in this scenario and this code is built on stripe features but is the model concept is the best here? should I build a membership this to be my models a subscription, membership … -
Should uwsgi.ini be run inside virtualenv or outside for django/nginx/uwsgi project?
I'm new to django; I'm setting up the django/nginx/uwsgi project from old server to new server. This is the command to start uwsgi: sudo uwsgi --ini /usr/share/nginx/html/portal/portal_uwsgi.ini I read https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html, but I want to confirm when I run uwsgi.ini, am I supposed to run it inside virtualenv or outside of virtualenv, or it doesn't matter? Please advise!! Here's the /usr/share/nginx/html/portal/portal_uwsgi.ini [uwsgi] # Django-related settings # the base directory (full path) chdir = /usr/share/nginx/html/portal # Django's wsgi file module = config.wsgi # the virtualenv (full path) home = /usr/share/nginx/html/portal # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /tmp/uwsgi.sock # ... with appropriate permissions - may be needed chmod-socket = 666 # clear environment on exit vacuum = true # Reload worker to avoid memory leak max-requests = 5000 # Recycle worker if a request to it takes longer than specified seconds harakiri = 90 plugins = python3 -
CRUD Using Ajax and Json
I'm following to this tutorial "https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html#listing-books" to to create a form popup window. When I click the create button I want my Order_form.html to popup , but if i click the button i get an empty popup window. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="{% static 'books/js/books.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <head> <title>Cura System</title> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'accounts:order-list' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'accounts:update_profile' %}">Profile</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Upload </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'accounts:upload-list' %}">File Upload</a> <a class="dropdown-item" href="{% url 'accounts:manualupload-order' %}">Manual Upload</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'accounts:logout-page' %}">Log Out</a> </li> </ul> </div> </nav> </head> {% block content %} <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'accounts:order-list' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" … -
NoReverserMatch: 'polls' is not a registered name
I'm learning Django from polls tutorial, when it come to practice a test client, i got an error in shell that don't know how to fix ít, please help me, thanks! NoReverserMatch: 'polls' is not a registered name My urls.py from django.contrib import admin from django.urls import path, include from polls import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('admin/', admin.site.urls), path('polls/<int:pk>/', views.DetailView, name='detail'), path('polls/<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('polls/<int:pk>/vote', views.vote, name='vote'),] My views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404, HttpResponseRedirect from django.template import loader from .models import Question, Choice from django.urls import reverse from django.views import generic class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' # Create your views here. def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.vote += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id))) -
How to test a cache lock in python
I have a django application. Where I am doing following: def important_fun() lock = cache.lock('some_string') if lock.acquire(): if var is None: critical_function(a,b,c) lock.release() else: log('not acquired') def critical_function(a,b,c) #Do critical stuff #var = some_val Now I want to test that if i call important function multiple times in parallel and test if critical_function is called only once (assert_called_once) I tried creating multiple process and threads it didnt work -
Gitlab CI + Django syncing with external static file bucket
I'm using Docker image 19.03.11 and GitLab. What's the right way to sync with an external bucket (I'm using GCP) right after deploying? So in my Dockerfile, I have: pip install -r requirements.txt python manage.py makemigrations python manage.py makemigrations an_app python manage.py migrate This is fine for building and testing but I want to also sync with a third-party bucket when the deploy stage is activated (but not with every build) with: gsutil -m rsync -r ./static gs://some-bucket-public/static I'd obviously need to access the data in the build and there are many ways to do this. What's the most efficient/correct way? -
Django: how do you get clean data from query by removing Decimal( in front of every value?
I want to have a clean list but when I run my query it returns "Decimal(" notation before every digit. This is my query processes = ProcessInfo.objects.filter(user_rel=user_pk).order_by('-id') process_score = processes.filter(user_rel=user_pk).values_list('process_score', flat=True) process_list = list(process_score) print(process_list) What i get is: > [Decimal('3797.00'), Decimal('0.00'), Decimal('301.00'), > Decimal('0.00'), Decimal('144.00'), Decimal('55.00'), > Decimal('181.00'), Decimal('0.00')] Model: process_score = models.DecimalField(default='0', decimal_places=2, max_digits=10, null=True, editable=False) How i am using it in js file : var myChart = new Chart(ctx, { type: 'bar', data: { labels: {{ process_list|safe }}, datasets: [{ label: 'Automation Potential', data: {{ process_list_score|safe }}, How can I get rid of Decimal( ? I am using this data in a js chart -
How can I create multiple polymorphic Django models using the same table
I've got a situation where I have one base Django model Rolls, mapped to the table rolls. There are multiple types of rolls, controlled by a column called type. In the older codebase I'm writing a v2 for (used to be PHP), I created subclasses for each type, that controlled setting their own type value, and it worked fine. I can't figure out how to set this up in Django. I'd like them all to use the same table, and each will derive methods from the base model, but have different implementations for many of those methods. I figure I can write a manager to handle getting back the right values, but I can't figure out how to setup the models. I tried setting a single base model and then derived other models from it, but those created different tables for each of them. Using managed = False seems the wrong way to go, given the subclasses don't represent tables of their own. -
why elastisearch raise exception when trying to rebuild_index with django and haystack
I am not sure why i am not able to use python manage.py rebuild_index using elasticsearch with django. Please find my configuration below: models.py from django.db import models class Hotel(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) def __str__(self): return self.name search_indexes.py from haystack import indexes from .models import Hotel class HotelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') description = indexes.CharField(model_attr='description') def get_model(self): return Hotel def index_queryset(self, using=None): return self.get_model().objects.all() settings.py INSTALLED_APPS = [ 'core', 'haystack', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' urls.py from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace='core')), path('search/', include('haystack.urls')), ] path for .txt file elastic/core/templates/search/indexes/core/hotel_text.txt # `elastic` is the name of the project # `core` is the name of the app Now when i try to python manage.py rebuild_index traceback error it start like this Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 5 hotels GET /haystack/_mapping [status:404 request:0.035s] PUT /haystack [status:406 request:0.015s] POST /haystack/modelresult/_bulk [status:406 request:0.059s] POST /haystack/modelresult/_bulk [status:406 request:0.009s] POST /haystack/modelresult/_bulk … -
Django using a utility/helper class for my CBV
I am new to django, and I am trying to split some logic from a class based view, as I will be using the same logic in a different app, so I am trying to avoid writing the same code over and over. What I did was creating inside the app folder (app_banking) a new file (Helper.py) that looks like this import numpy as np import pandas as pd class Helper(): def method1(row, listCategory,typeOfAmount = None): .... return ... def method2(row): .... return ... @staticmethod def utility_generateDataFrame(self, transactionLST): df = pd.DataFrame(list(transactionLST.values())) .....CODE return df # GET UNIQUE COLUMNS (TO DISPLAY ALL THE CATEGORIES) @staticmethod def utility_generateUniqueCategories(self, df): categories = df.category.explode().unique() return categories # DESIGN TABLE FOR CREDITS AND DEBITS (FRONT END) @staticmethod def utility_generateDataFrameGroupinng(self, df): df_new = df.groupby(['YearMonth']).sum()[['credit', 'Internal Transfers (Sum - Credit)', 'External Transfers (Sum - Credit)', 'Loan Credits (Sum)', 'Net Credits (Genuine Business Credits)', 'Other Credits', 'EFTPOS', 'Uncategorised Credits', 'ATO - Credits', 'Loan Credits (count)', 'Credits (Count)', 'debit', 'Internal Transfers (Sum - Debit)', 'External Transfers (Sum - Debit)', 'Net Debits (Genuine Business Payments)', 'Operating Expenses', 'Payroll', 'Rent', 'Loan Repayments', 'Dishonours', 'ATO - Debits', 'Uncategorised Debits', 'Adverse Amounts', 'Gambling', 'Loan Debits (Count)', 'Adverse (Count)', 'Gambling (Count)', 'Dishonour (Count)', 'Debits … -
Need help in saving the parent model and the attached child model (1:m) in a single CreateView?
ValueError: save() prohibited to prevent data loss due to unsaved related object 'purchase_bill' ***views.py*** class BillCreate(CreateView): model = PurchaseBill form_class = PurchaseBillForm template_name = 'tracks/purchaseform.html' success_url = '/purchasetable' def get_context_data(self,**kwargs): context = super(BillCreate,self).get_context_data(**kwargs) context['itemform'] = PurchaseItemFormSet() return context def post(self, request, *args, **kwargs): form = self.get_form() pitem_formset = PurchaseItemFormSet(request.POST) if form.is_valid() and pitem_formset.is_valid(): return self.form_valid(form, pitem_formset) else: return self.form_invalid(form) def form_valid(self, form, pitem_formset): newbill.save() with transaction.atomic(): pitems = pitem_formset.save() for pitem in pitems: pro = pitem.save() pro.bill_num = newbill pro.save() return HttpResponseRedirect(self.get_success_url()) ***forms.py*** class PurchaseBillForm(forms.ModelForm): class Meta: model = PurchaseBill fields = '__all__' class PurchaseItemForm(forms.ModelForm): class Meta: model = PurchaseItem fields = '__all__' PurchaseItemFormSet = inlineformset_factory(PurchaseBill,PurchaseItem,fk_name='purchase_bill',form=PurchaseItemForm,extra=2) I admit that form_valid method look broken, i am sorry it is the result of my trial and errors in finding the right way.Please help me!!please!! -
Creating sub-users with limited permissions in Python Django
I am building an app for retailers, and it will be used by supervisors (admins), and store managers (sub-users). I have a 'location' model. I'm trying to make it so that each sub-user has access to a sub-set of the locations in an account. Since User isn't defined in models.py, I'm struggling to figure out how to do this. How would I permit access to a location to a sub-user? -
Pip is refusing to downgrade in windows [closed]
Exception: Traceback (most recent call last): File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\cli\base_command.py", line 179, in main status = self.run(options, args) File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\commands\install.py", line 384, in run installed = install_given_reqs( File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\req_init_.py", line 53, in install_given_reqs requirement.install( File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\req\req_install.py", line 910, in install self.move_wheel_files( File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\req\req_install.py", line 437, in move_wheel_files move_wheel_files( File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_internal\wheel.py", line 544, in move_wheel_files generated.extend(maker.make(spec)) File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_vendor\distlib\scripts.py", line 405, in make self._make_script(entry, filenames, options=options) File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_vendor\distlib\scripts.py", line 309, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_vendor\distlib\scripts.py", line 245, in _write_script launcher = self._get_launcher('t') File "c:\users\samikllaz\pycharmprojects\video\venv\lib\site-packages\pip-19.0.3-py3.8.egg\pip_vendor\distlib\scripts.py", line 384, in _get_launcher result = finder(distlib_package).find(name).bytes AttributeError: 'NoneType' object has no attribute 'bytes' -
Django - why does a list passed as context not clear on refresh, and instead duplicates?
Hard to explain this in a simple subject. This is with a GET, no POSTs. I have a function defined in a different file, we'll say list_gen.py that returns list 'gen_list'. 'gen_list' is a global variable here. In the views.py, I call this function and assign the output as 'output_list' and send it with the return as such: " return render(request, 'detail.html', {'output_list':output_list}. Then, in detail.html I simply place the results with {{output_list}}. When I visit the page, I see the exact output I expected. But, if press refresh, the output duplicates and continues to do so each time I press refresh or if I visit another entry that uses that detail.html page. Has anyone seen this before? -
Django duplicated url request: "home/home/'
I have code that works perfectly on localhost, but it is giving an error when placed on the server. The point is that when I upload a file, it returns "base.com/home/home" (home twice = 404) instead of just "base.com/home" or the destination of the redirect. Template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> View: def home(request): if request.method == 'POST': return redirect('base-temp', proc.id) return render(request, 'base/home.html', {'test': 'test'}) Url: urlpatterns = [ path('', views.login_page, name='base-login'), path('logout/', views.logout_page, name='base-logout'), path('home/', views.home, name='base-home'), path('temp/<int:pk>/', views.temp, name='base-temp') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) All other pages, media, statics are working fine. Only the post in this view. I tried using action with ".", "/home/" and "{% url 'base-home'%}", but they all give the same 404 for duplicating the home url. I also tried to create a separate view to handle the upload, but the error became "home/upload" instead of "upload". I saw some similar questions in the stackoverflow, but I didn't find an answer that would work for me. Any suggestion?