Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
this code replacing the html not appending the html
suggest me how should i do to append the html not to replace html in django using ajax call this code replace tag content in html page but i want to append html on every ajax call {% load staticfiles %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="{% static 'chatbot/css/bootstrap.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'chatbot/css/Community-ChatComments.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'chatbot/css/styles.css' %}" type="text/css"> <script type="text/javascript"> $(function(){ $("#form1").on("submit",function(e){ e.preventDefault(); $.ajax({ type:"POST", url:"./submission/", data:{ "question":$("#input_ques").val() , "csrfmiddlewaretoken" : $("input[name=csrfmiddlewaretoken]").val() }, success:sent, dataType:'html' }); }); }); function sent(data,textStatus,jqXHR){ $("#chat").html(data); } -
Python Django How to Create Hash Fields inside django models.py
I'm working on a Python(3.6) & Django(1.10) project in which I need to save some user credentials of the third party services like username, password, and email, I'm implementing only rest API, so there's no form.py at all. So, How can I make hash fields inside models.py file? Here's my current models.py: class DeploymentOnUserModel(models.Model): deployment_name = models.CharField(max_length=256, ) credentials = models.TextField(blank=False) project_name = models.CharField(max_length=150, blank=False) project_id = models.CharField(max_length=150, blank=True) cluster_name = models.CharField(max_length=256, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=150, choices=services) configuration = models.TextField(blank=False) routing = models.TextField(blank=True) def save(self, **kwargs): if not self.id and self.services == 'Multiple' and not self.routing: raise ValidationError("You must have to provide routing for multiple services deployment.") super().save(**kwargs) I want to add three new hash fields like username, password & email. Help me, please! Thanks in advance! -
how to add two fileds in a table and result store must store in another table by using django(restapi)
enter image description hereHere i having two tables in models one table having currency denomination data and another table debit currency must store -
Cannot delete customer user in admin site Django
I'm following the Django documents to override the user model, it works well. But I am struggling to delete the custom users. Errors: Traceback (most recent call last): File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1838, in delete_view return self._delete_view(request, object_id, extra_context) File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/db/transaction.py", line 212, in exit connection.commit() File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 261, in commit self._commit() File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/jinx/PycharmProjects/Bookstore/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed My user model: class Customer(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomerAccountManager() USERNAME_FIELD … -
Can I use custom django tags to pass a value to another view?
I am currently using modelformset_factory to display several forms in an update class-based view. For one of the fields I am using django-popup-view-field 0.3.0 to display a popup that will allow the user select the value to input in that said field. The popup is create by: popup.py class SelectionReasonPopUpViews(DetailView): template_name = 'popups/selectionReason.html' model = AttackPattern context_object_name = 'attackpattern' The popup is then passed into the form by: form.py class APRForm(ModelForm): class Meta: model=APR fields=['rating', 'selectionReason', ] selectionReason=PopupViewField( view_class=SelectionReasonPopUpViews, popup_dialog_title="Please select a reason for", required=True, ) def __init__(self, *args, **kwargs): super(APReviewForm, self).__init__(*args, **kwargs) self.helper = FormHelper() APRFormset = modelformset_factory(APR, form=APRForm, extra=0) This how I created my updateview: views.py class APRUpdate(UpdateView): ... def get_context_data(self, **kwargs): context = super(APRUpdate, self).get_context_data(**kwargs) context['formset'] = APRFormset(queryset=APR.objects.get(pk=< get the pk from url when editing>)) return context def post(self, request, *args, **kwargs): ... def form_valid(self, formset): ... def form_invalid(self, formset): ... I then render the APRFormset in this template (showing only the form): APRUpdate.html <form method="POST" enctype="multipart/form-data" style="margin-left: 40px; margin-right: 40px"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors }} {% for forma in formset.forms %} <div class = "panel panel-primary"> <div class = "panel-heading"> <h3 class = "panel-title">{{forma.instance.atPat.APid}} : {{forma.instance.atPat.name}}</h3> </div> <div class = "panel-body"> {{ … -
pass parameter to form from template in Django 2
in Django I make a form which get an email address and save it in database and this my form.py: class NewsletterUserSignUpForm(forms.ModelForm): class Meta: model = NewsletterUsers fields = ['email'] def clean_email(self): email = self.cleaned_data.get('email') return email and this is my views.py : def newsletter_signup(request): form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUsers.objects.filter(email=instance.email).exists(): messages.warning(request, 'Your Email Already Exist In Our DataBase.', 'alert alert-warning alert-dismissible') else: instance.save() messages.success(request, 'Your Has Been Submitted To Our DataBase.', 'alert alert-success alert-dismissible') context = { 'form': form, } return render(request, 'newsletter/subscribe.html', context) the problem is here that this form has it own input which the input must put inside it but I want to design my own template and get input in my template then pass it to this form and my question is how do I can pass inputs in my .html template file to my form? this is my html file and don't know to put what in href for input tag : <form method="post" class="login100-form validate-form"> {% csrf_token %} <span class="login100-form-title p-b-43"> Subscribe </span> <div> <inputtype="email" name="Email"> <span class="label">Email</span> </div> <button type="submit" href=""> Subscribe </button> </div> and what should I put in my href and how pass input … -
how to hide django message after it is displayed for few seconds
For example, before redirect, I used messages.add_message(request, messages.INFO, 'You have successfully updated your listing.') Then the message will be automatically displayed after redirection, however the message will never disappear, may I know how to hide it after few seconds? Thanks!!! -
Is there a way to restrict apps based on IP?
I'd like to be able to only allow certain apps to be used from the corporate office which has a static IP. Is there a django package that I can use to do this? If so do you know if it can be used as an additional security measure? Certain apps and the data in those apps I wouldnt want to be accessible by anyone outside the office. I already have pretty good app security but as an additional security measure is this a good option? Thanks -
Celery workers are not started in my Django app
I am using DigitalOcean with Ubuntu 16.04, and I installed Django 2.0.5 and Python 3.5. This is my file structure: /home/user/ |--project-folder |--myproject |--init.py |--celery.py |--settings.py |--tasks.py |--wsgi.py |--manage.py |--requirements.py |--gunicorn_start(executable) |--logs |--run |-- gunicorn.sock |--venv(virtual environment) |--bin |--lib My init.py file: from .celery import app as celery_app My celery.py file import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my celery section in my settings.py file CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' I installed Gunicorn, this my gunicorn_start file #!/bin/bash NAME="myproject" DIR=/home/user/project-folder USER=user GROUP=user WORKERS=3 BIND=unix:/home/user/run/gunicorn.sock DJANGO_SETTINGS_MODULE=myproject.settings DJANGO_WSGI_MODULE=myproject.wsgi LOG_LEVEL=error cd $DIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- I installed Supervisor and this is my /etc/supervisor/conf.d/a-name.conf file: [program:myproject] command=/home/user/gunicorn_start user=user autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/user/logs/gunicorn.log I call the tasks(email functions) using .delay() and no email is sent, then using the terminal I make the workers run with this command: celery -A myproject worker -l info and all the emails are sent. And as soon as I press Ctrl-C … -
Django rest sql queries
sorry I have a problem with raw, it does not recognize my table from my database def list(self, request): queryset = Sale.objects.raw('SELECT * FROM Sales_sale') serializer = SaleSerealizer(queryset, many = True) return Response(serializer.data) this is my code, I get this error there is no relationship «sales_sale» LINE 1: SELECT * FROM Sales_sale[![ And this is the name just like in my database, postgresql]1]1 -
Invalid Username/Password when Trying to signup with DRF CreateAPIView
i want to create users using django built-in "User" Model and with CreateAPIVIew mixin here is the code : class Register(generics.CreateAPIView): permission_classes=[permissions.AllowAny] def post(self,request,*args,**kwargs): username= request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') # first_name=request.POST.get('first_name') # last_name=request.POST.get('last_name') user=User.objects.create_user(username,email,password) # user.first_name='mintu' user.save() but when i tried to submit a http post request using Postman i have been fired up with an error called { "detail": "Invalid username/password." } so to make sure if i my database is creating users perfectly fine i have decided to create a user manually through python shell with this command user=User.objects.create_user('mounikesh','thota@gmail.com','test1234') successfully a user has been created so i came to a conclusion that my database is fine and its accepting the request now the issue is only with drf's CreateAPIView and now i tried to figure if the error is caused coz of the data that i've been sending through postman for that i've directly injected the username,email&passoword to the server class Register(generics.CreateAPIView): def post(self,request,*args,**kwargs): permission_classes=[permissions.AllowAny] # # username= request.POST.get('username') # email=request.POST.get('email') # password=request.POST.get('password') user=User.objects.create_user('ok','ok@gmail.com','test1234') # user=User.objects.create_user(username,email,password) user.save() # token=Token.objects.create(user=user) return Response("user has been created") tried to send all my required credentials to create a User expecting my User created response instead got a Error Reponse Tried a Lot Searching … -
Why do I have to state 'atomic=False' when I change model name in Django?
Okay so I was following Django 2.0 tutorial on the official documentation when I realized I named a model 'Questions' instead of 'Question'. (I'm new to Django) I already did $ python manage.py makemigrations polls $ python manage.py migrate so I thought I could just repeat this to apply the change. Django asked me if I wanted to rename so I said yes. (venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py makemigrations Did you rename the polls.Questions model to Question? [y/N] y Migrations for 'polls': polls\migrations\0002_auto_20180804_0935.py - Rename model Questions to Question But when I tried to migrate, Django wouldn't run the migration and showed me this error. (venv) H:\PycharmProjects\django_tutorials\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0001_initial... OK Applying polls.0002_auto_20180804_0935...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "H:\PycharmProjects\django_tutorials\venv\lib\site-packages\django\db\migrations\executor.py", … -
How to get the "Leave site? Changes that you made may not be saved" when trying to close a window with a populated form
I have a form that when filled in, I can exit the window without being given a warning (I'm using Chrome). How can I ensure I get a warning before exiting? Is there a Django setting for this? -
Internet Public ip address and django static file in pdf
I used django and weasyprint to make an application which print a pdf file with picture and css file which design my pdf file. I used nginx, gunicorn and supervisor. In my intranet all is ok. When i used INTERNET PUBLIC IP ADDRESS to show it in internet, my pdf file don't show anymore picture and css design. I see my gunicorn log but nothing. is somebody have the same problem? -
CSRF Token Name on Django Documentation is not Matching the Actual Name of the Variable in AJAX Header
I was struggling to send and recieve CSRF token, and I found, in the end, that Django was not able to get the token value because its name was different from the recommended one in its documentation. Why? (I am doing AJAX on a HTTPS address and requests are cross-site.) function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); Here, the name is X-CSRFToken, which somehow becomes HTTP_X_CSRFTOKEN. On the other hand, Django is looking up the cookie under CSRF_COOKIE. Line 278 in csrf.py of CsrfViewMiddleware: csrf_token = request.META.get('CSRF_COOKIE') if csrf_token is None: # No CSRF cookie. For POST requests, we insist on a CSRF cookie, # and in this way we can avoid all CSRF attacks, including login # CSRF. return self._reject(request, REASON_NO_CSRF_COOKIE) I cannot change the variable name because I get this error: Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response. So, I ended up changing the variable name in the source code from CSRF_COOKIE to HTTP_X_CSRFTOKEN. Are there any way to make this work? (I do not do @csrf_exempt, so please do … -
How to create link for one of the category in Django
I'm coding a news website.I have 'category' in News model. I want to get all the news in one of the categories named 'opinion' in my index.html. And create detail page link for each of them. I can the title ,author, etc of the news mentioned above .But my brain really junks,I don't know how to create a link points to opinion_new.html or news_detail.htlm for each of them.I have a link for regular news to point to news_detail.htlm. here is part of my News model: class News(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类') here is my Category model: class Category(models.Model): name = models.CharField(max_length=40) # 分类名 class Meta: verbose_name = "分类" verbose_name_plural = verbose_name def __str__(self): return self.name here is part of my view: class NewsView(View): def get(self, request): opinion_news = News.objects.filter(category="opinion") return render(request, 'index.html', { 'opinion_news': opinion_news, }) here is part of my index.html {% for opinion in opinion_news %} <li class="media"> <a href='?'> <h>{{opinion.title}}</h></a> </li> {% endfor %} here is part of my already works well news_detail view. def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) news.comment_nums = all_comments.count() news.save() return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'category': category, … -
How to communicate with a biometric fingerprint reader in django
I am working on a django project that allows an administrator to register (signup) users. Users fingerprint is needed to be captured and saved into the database. The issue i am having is how do i make a web browser communicate with a physical hardware, collect some data from the hardware (in this case fingerprint reader) and save it into django database for future use. I have a DigitalPersona USB fingerprint reader (i don't know if it may do the job). Thank you in advance. -
Can I Destructively Alter My Database in a Django View?
So I'm loading up my queryset to send to my template. One of the objects is incident. Now, each incident has a bunch of attributes like "status" and "employee", so in my template I can just do // incident.html // {% for incident in incidents %} <h1> {{ incident.employee }} - {{ incident.status }} </h1> {% endfor %} Now, for convenience I want to add new properties that didn't exist before to incident, like "mood" or whatever, I can add // views.py // def get_context_data(self, **kwargs): ... for incident in incidents: incident.mood = "scary" And then in my template I can just access incident.mood along with incident.status and incident.employee. // incident.html // {% for incident in incidents %} <h1> {{ incident.employee }} - {{ incident.status }} </h1> <h3> It was very {{ incident.mood }} </h3> {% endfor %} So, what I want to know is, is it possible to mess up and destructively alter the database if I'm not careful here? If I add // views.py // def get_context_data(self, **kwargs): ... for incident in incidents: incident.employee = "Daffy Duck" Am I going to ruin all of my data and permanently make the name of the employee "Donald Duck" in every … -
display rawqueryset value in a model using django @property field
I am trying to insert a @property field into a django model. However this field gets its value from a RawQuerySet like so; class Medication_List(models.Model): id = models.AutoField(primary_key=True) medication_name = models.CharField(max_length=250, blank=True, editable=True) ... def stock_level(self): # "Returns the totalstock remaining" current_stock = Medications_Bridge.objects.raw("SELECT T3.total_quantity_sold AS total_quantity_sold FROM (SELECT * FROM ... return({'current_stock' : current_stock}) stock = property(stock_level) def __str__(self): return "%s %s %s" % (self.medication_name, self.supplier,self.stock) This works fine with no errors, but django is not showing value for the queryset in the str function, rather it just shows the whole query just as it was written above. i.e. "SELECT T3.total_quantity....." I want to know if it is even possible to use @property field to show a value from another unrelated database table. I have seen some examples on StackOverflow where calculated values are shown using values from the same model with help of self.field_name but i cant find any example where the values for the calculations are derived from another model or from a raw SQL query. Kindly help. Any hint will be very much appreciated. Thanks -
Django/Python/xhtml2pdf - Help getting xhtml2pdf to render a DetailView
I'm trying to get xhtml2pdf to render a DetailView to pdf, but I'm running into some issues. To be more specific, I have an app that's similar to a blog. User logs in, creates a new "post", and then can view it. I want to be able to allow the user to save that post to pdf. I've gone to my extent of knowledge (admittedly limited still) with Django and cannot figure it out. I've followed multiple tutorials and have xhtml2pdf working for static pages, but not for ones that require a pk or pulling data from the database. The view I'm trying to save looks like this: class SingleCharacter(LoginRequiredMixin,generic.DetailView): model = models.Character def get_context_data(self, **kwargs): context = super(SingleCharacter, self).get_context_data(**kwargs) return context Alternatively, if anyone knows of another way to save html to pdf that works with django, I'd take advice on that, as well! Any help would be greatly appreciated! Thank you! -
How to filter data in get_context_data
I have 2 models ... class PurchaseOrder(models.Model): po_number = models.IntegerField(unique=True, default=get_po_number) po_date = models.DateField() invoice_number = models.ForeignKey(Invoice, on_delete=models.CASCADE) class PurchaseOrderItem(models.Model): po_number_fk = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) qty = models.IntegerField() unit = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=255) unit_price = models.DecimalField(max_digits=6, decimal_places=2) amount = models.DecimalField(max_digits=6, decimal_places=2) One for purchase orders(PurchaseOrder), and one for items within a specific purchase order(PurchaseOrderItem) I'm trying to access the data for both models in one TemplateView... class PurchaseOrderDetailView(LoginRequiredMixin, TemplateView): template_name = 'financial/purchase_orders/purchase_order_detail.html' def get_context_data(self, **kwargs): context = super(PurchaseOrderDetailView, self).get_context_data(**kwargs) context['purchase_order'] = PurchaseOrder.objects.get() context['item'] = PurchaseOrderItem.objects.filter() return context but I'm unsure of how to filter the purchase_order.pk based on the pk passed through the URL, and I'm unsure how to filter the items.po_number_fk based on the purchase_order.pk. I know I need to put the login in my PurchaseOrder.objects.get() and PurchaseOrderItem.objects.filter() but not sure what the logic needs to be Thanks for any help you can give -
What is this episode of code doing here? (Django, uploading a file)
url(r'^Document/upload/(?P<category>.*)$', agent_views.upload_documents, name='upload_documents'), @login_required @user_passes_test(lambda u: u.is_staff) def upload_documents(request, category=None): """ form to upload a new Document """ from sitetools.models import Document return crudmatic(request, Document, reverse('upload_documents', kwargs={'category': category}), goto_on_save=('agent_documents', {'category': category})) def crudmatic(request, themodel, url, goto_on_save=None, admin=None): """ GET: presents an admin form but outside of the admin application. POST: validates, saves and relocates or if there are errors then it presents the form again Returns: an HTTP response using the admin options defined and registered for the admin site for this model. optionally you may supply an Admin Usage: # in your view: return crudmatic(request,YourModelClass,url) crud = create replace update delete this does create only. it was intended to support all stages. see editmatic """ if not admin: try: admin = site._registry[themodel] except KeyError: admin = DefaultAdmin(themodel, site) else: admin = admin(themodel, site) # some breakage in django # there is supposed to be a root path set, # but I'm not running an admin site here # if hasattr(admin,'admin_site'): admin.admin_site.root_path = "/admin/" return admin.add_view(request, url) I am reading an episode of code that trying to upload a file. There are three episodes code in three files. I put then there. Actually, I don't really understand what does the … -
Django CSRF Error: Only on local runderver
The same code from the repo works fine out in the wild. But on my local environment, I'm getting CSRF errors on form submits. Django 1.11.13, Python 2.7 It's very hard to debug, because there's not really any breakpoint. the error occurs way before the view. The CSRF token is in the form {% csrf %}, the cookie is there. I've tried creating a new virtual environment, wiping the database, different browsers. What else? -
Django redirect cannot resolve URL
I have a pretty simple Django app with a form. After the form has been validated, it's supposed to redirect to the start page of the app. I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'overview' not found. 'overview' is not a valid view function or pattern name. The relevant path in urls.py is: urlpatterns = [ path('overview', views.overview, name='overview'), ...] The view is in the same views.py as the redirecting view: def overview(request): ... return render(request, 'feedback/overview.html', context) The view with the redirect call looks like this: def make_submission(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.approved = False post.save() return redirect('overview') else: form = FeedbackForm() return render(request, 'feedback/make_submission.html', {'form': form}) The form data are saved in the db, but the redirect fails. What am I doing wrong? -
Django getting the incorrect form name, value, or ID from an unchecked form (that was previously checked)
I have a view which displays many forms (which are individual checkboxes per form). I would like to get the value of the checkbox that was previously checked, but then unchecked. I have tried a number of things, including getting the form id/label name, but for some reason when I uncheck 1 box (1 form), it is returning the wrong box/form as the one that was unchecked. In fact, it is simply just returning the first form in my list of forms, and not the one that was unchecked. View def employee_output_table(request): table = Employees.objects.all() queue_exists = UserSurveyQueue.objects.filter(user=request.user) context = [] for user in table: d = {} d['user'] = user username = User.objects.get(username=user).username queue = None if queue_exists: queue = queue_exists.get(user=request.user) queryset = queue_exists.get(user=request.user) if request.method == "POST": form = UpdateSurveyQueueForm(request.POST, instance=queue, user=request.user.id, query=user) if form.is_valid(): for field in form: print(field.form) form.instance.user = request.user added_user = form.cleaned_data.get('queue') if added_user: form.instance.queue.add(added_user.get()) elif 'queue' in form.changed_data: pass return HttpResponseRedirect(reverse('employee-table')) else: form = UpdateSurveyQueueForm(instance=queue, user=request.user.id, query=user) d['form'] = form context.append(d) return render(request, 'surveys/employees_list.html', {'employee_table': context}) Form class UpdateSurveyQueueForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user') query = kwargs.pop('query') super().__init__(*args, **kwargs) self.fields['queue'].queryset = User.objects.filter(username=query).exclude(pk=user) queue = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={'onclick':'this.form.submit();'}, ), required=False, queryset=User.objects.all(), ) …