Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku deployment missing files from git
I'm having problems with a deployment in Heroku. My app uses Django and React so when I deploy the server runs Webpack to concatenate all the javascript. The deploy fails because it says there is a file missing, if I run webpack locally with the same version it runs perfectly. The thing is that the file is in the repository, if I clone the repo from Github the file is there and I can make it run. I tried both deploying from my local repo and straight from Github. This is not the first time I've deployed this app to Heroku and it worked before so I know the configuration is not a problem. The file that heroku is missing has been created after the last deploy I'm quite inexperienced with Heroku so I will be thankful for a way to investigate this problem. Thanks! -
Docker in Django 2.0 and Postgresql not working (Windows 10 Home)
I've been following this tutorial and I made some modifications, because I'm using virtualenv instead of pipenv, so I'll be using a requirements.txt file to manage the dependencies. https://wsvincent.com/django-docker-postgresql/ Dockerfile: # Pull base image FROM python:3.6-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory RUN mkdir /code WORKDIR /code # Install dependencies RUN pip install --upgrade pip ADD requirements.txt /code/ RUN pip install -r requirements.txt # Add project ADD . /code/ docker-compose.yml: version: '3.6' services: db: image: postgres:10.1-alpine # volumes: # - postgres_data:/var/lib/postgresql/data/ web: build: . # command: python /code/manage.py migrate --noinput command: python /code/manage.py runserver 0.0.0.0:8000 # volumes: # - .:/code ports: - 8000:8000 environment: - SECRET_KEY=changemeinprod depends_on: - db volumes: postgres_data: After running: (dfb_mb_docker) C:\Projects\dfb_mb_docker>docker-compose run web python /code/manage.py migrate --noinput I had this error: Starting dfbmbdocker_db_1 ... done python: can't open file '/code/manage.py': [Errno 2] No such file or directory That's why I commented out the volumes. After running: docker-compose up -d --build And: docker-compose up Now it seems to be up and running but when I visit http://127.0.0.1:8000/ the site isn't up. I think that the problem is related to the postgresql database because in the log it says "database … -
django create template with multiple input field
I am trying to create a template which would take input items like item, quantity and unit price and render a pdf report of it with total price. Also i want the input to be on tabular form and add the lines dynamically by clicking + icon or something. My folder structure is Project>app>template>app.html I am extending app.html from base.html which inherits bootstrap. Tried the below code but can't figure out how to do it. {% extends 'base.html' %} {% block head %} {% endblock %} {% block body %} <div class="panel panel-default"> <div class="panel-body"> <div id="all_fields"> </div> <div class="col-sm-3 nopadding"> <div class="form-group"> <input type="text" class="form-control" id="Itemquantity" name="Itemquantity[]" value="" placeholder="Item Quantity"> </div> </div> <div class="col-sm-3 nopadding"> <div class="form-group"> <input type="number" class="form-control" id="Quantity" name="Quantity[]" value="" placeholder="Quantity"> </div> </div> <div class="col-sm-3 nopadding"> <div class="form-group"> <input type="number" class="form-control" id="Unitprice" name="Unitprice[]" value="" placeholder="Unit Price"> </div> </div> <div class="col-sm-3 nopadding"> <div class="form-group"> <div class="input-group"> <div class="input-group-btn"> <button class="btn btn-success" type="button" onclick="all_fields();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button> </div> </div> </div> </div> <div class="clear"></div> </div> <div class="panel-footer"><small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another form field :)</small>, <small>Press <span class="glyphicon glyphicon-minus gs"></span> to remove form field :)</small></div> </div> {% endblock %} -
How to make checkbox as button with confirm message?
I'm Junior Django dev. It's my first project in my company and I have a FrontEnd tasks. Frontend is black magic for me but trying my best but here I am totally lost ;/ Task to do: "If I click on checkbox it redirect to page with endpoint which change value of checkbox from on to off" I wrote all backend staff... and even some kind of frontend but it is not working as i want it to. I've tried loads of combination but i still don't know. Code of checkbox: <table> <thead>...</thead> <tbody> <td> <a href="{% url 'tournament_user_paid_change' tp_id=item.pk paid=item.paid %}" onclick="return confirm('For surechange - {{ item.full_name }}?')"> <div class="checkbox m-15"> <label for="id_paid"><input type="checkbox"{% if item.paid == True %} checked{% endif %} ><i class="input-helper"></i></label> </div> </a> </td> </tbody> </table> And what is happening here? When I click directly on checkbox there appears a confirmbox when I click "OK", checkbox change state but request is not send... When I click outside checkbox there is confirmbox and when I click "OK" I'm correctly redirected to request site. How to make it work when I click directly on checkbox... not only outside? ;/ I will appreciate any help! -
How to make ImageField returns relative path?
I don't know why, but my ImageFields return full URL pathes. I use this custom FileStorage: class ASCIIFileSystemStorage(FileSystemStorage): def get_valid_name(self, name): return str(uuid.uuid4()) + '.' + name.split('.')[-1] And simple ModelSerializers (from django rest framework) without overwriting smth. What can be the reason of those behaviour? I need relative URLs. -
When and where do I create configurable custom groups in Django without running in "no such table: auth_group" on startup?
I'm still learning and working on an existing Django app (v1.10.) for which I am trying to switch existing custom groups to making them dynamically configurable, so that the app can be used in different contexts. I have an ini file, which includes my dynamic groups: ; Custom groups and permission settings [platform_group_list] TEAM = policy_team LEAD = policy_team_lead [platform_group_value_list] TEAM = Policy Team Member LEAD = Policy Team Lead which I parse in settings.py: PLATFORM_GROUP_LIST = raw_parser.items("platform_group_list") PLATFORM_GROUP_VALUE_LIST = raw_parser._sections["platform_group_value_list"] The original app created groups and permissions inside migrations. I commented out the part there as it kept throwing errors regarding missing permissions and thought that maybe it would be better to do this in admin.py since this is where the groups "belong". So I have: # admin.py (removed custom permissions, not relevant atm) from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Group, Permission, User from django.contrib.auth import models as auth_models from django.core.exceptions import ObjectDoesNotExist from django.conf import settings from django.utils.translation import ugettext as _ from account.models import SignupCodeResult from .models import UserConfig # BACKCOMPAT # add staff to the backcompat groups and vice versa, then remove the # backcompat … -
Migration from Wordpress to Django?
I created a website through Wordpress but now i want to migrate my site into Django without losses my data. So, How can i switch my website from Wordpress to Django? -
Get Django CMS plugin information from Haystack search results
My search results page needs to display information about the Plugins where the query was found, too. I found this question with a similar problem, but I don't only need the contents, I need to know stuff about the plugin - i.e. what's it called, where it is on the page and stuff. Basically I would like a reference to the plugin where the query was located, but I can only find information about the page and title. I haven't been able to find it anywhere on the SearchQuerySet object and in the vicinity - also coming up empty in the documentation for Haystack. Is it possible and how? Stack I'm using: Elasticsearch 2.4, django-haystack 2.8, aldryn-search 1.0 (for CMS indexing). -
Django debugger-tool - How to avoid duplicate querys in for loop in this case
thank you in advance for your answers. How can I avoid duplicating querys ?, if I go through only 6 products it takes 50ms (6 querys duplicated), but when I try to go through 7000 products it takes too long (7000 duplicated querys), there is some way of caching all the products so that you have to do a query every time we go through the for loop, or should go through the loop in another way. Thanks. models.py class TareaDeScrap(Tarea): producto = models.ForeignKey(Producto) tipo = models.CharField(max_length=20, default='all') idioma = models.ForeignKey(Idioma) class Dato(models.Model): campo = models.CharField(max_length=45) tarticulo = models.IntegerField(default=0) db_field = models.IntegerField(default=0) def __str__(self): return self.campo class Producto(models.Model): tdbaseges = models.CharField(max_length=45, unique=True) codigo_O = models.CharField(max_length=60, null=True) referencia = models.CharField(max_length=500, null=True) codigo_limpio = models.CharField(max_length=60) codigo_fabricante = models.CharField(max_length=10) categoria = models.ForeignKey(Categoria, null=True) fabricante = models.ForeignKey('tarifas.Fabricante', blank=True, null=True) class DatoProducto(models.Model): producto = models.ForeignKey(Producto) dato = models.ForeignKey(Dato) informacion = models.TextField() tarea = models.ForeignKey('main.Tarea', null=True) views.py tareas = TareaDeScrap.objects.filter(batch_id=batch_id, estado='SAVED').select_related("producto") for tarea in tareas: producto_modificados.setdefault(tarea.producto.tdbaseges, {}) datos_modificados = DatoProducto.objects.filter(producto=tarea.producto).select_related("dato") # tarea=tarea) for dato in datos_modificados: producto_modificados[tarea.producto.tdbaseges].setdefault(dato.dato.campo, dato.informacion) cabeceras_productos_modificados.setdefault(dato.dato.campo, []) Django debbug-toolbar sql duplicates SELECT ••• FROM `importacion_datoproducto` INNER JOIN `importacion_dato` ON (`importacion_datoproducto`.`dato_id` = `importacion_dato`.`id`) WHERE `importacion_datoproducto`.`producto_id` = 132142 Duplicated 6 times. SELECT ••• FROM `importacion_datoproducto` … -
Daphne High CPU Usage with Channel 2 and Redis Layer
I am a Django developer, i have recently build a messaging app using Channels 2 and Redis. For each conversation i am creating a group and adding all the participant to the group every time when one reconnect. I am also using workers for channels with Daphne on production The problem is that after 10 groups for a user , the messaging get super slow with daphne using nearly 100 % CPU usage, causing all site slow. I have attached the screehshots for my upstart script and the CPU usage. Supervisor Scripts CPU Usage for Daphne I would be really thankful to you could advice to reduce CPU usage Regards, Saadullah Naeem -
GeoDjango tutorial error: Cannot resolve keyword 'mpoly' into field
I am working through geodjango's offical tutorial. I am using: geos 3.6.2 proj.datumgrid 1.5 proj 4.9.1 gdal 2.3.1 django 2.0.7 PostGIS 2.4 I get to using >>> from mapmaybe.models import WorldBorder >>> WorldBorder.objects.filter(mpoly__contains=pnt_wkt) It returns this error trace: Traceback (most recent call last): File "", line 1, in File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q split_subq=split_subq, File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1153, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1015, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/spencer/PycharmProjects/demo/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1379, in names_to_path "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'mpoly' into field. Choices are: area, fips, geom, id, iso2, iso3, lat, lon, name, pop2005, region, subregion, un Any ideas? Thanks in advance -
Question mark not recognized with path function
I'm working on a django web app. I'm trying to implement a search field that would "communicate" with the url. I want from http://127.0.0.1:8000/contract/ that when I enter an id in the search field, it redirects me to http://127.0.0.1:8000/contract/id . The problem is that when using the search field, it redirects me to http://127.0.0.1:8000/contract/?search=id which is not really a problem. But when I try to define the urlpattern, it doesn't 'recognize' the question mark in the url. The consequence being that I can't access to the right template. urlpatterns = [ path('?search=<id_contract>/', app_views.view_contract), path('', app_views.contract, name='my_contract'), ] I see two possible solutions : either I would try to find a way to remove that question mark, but I haven't really found where to do it so I would much appreciate your help! Second option consists in using regex but what I've tried so far didn't work : re_path(r'.+\?.*'+'search'+'(?P<id_contract>)/$' Thank you for your help. -
AngularJS and Django bootstrap modal form input field get value
I need to get my vaue when a click a button which launch bootstrap modal. Below code is my try: By this, When modal open then I can display my full_name in input field placeholder. But in input filed value I can't display this {% for employee in employees %} {{ employee.full_name }} <a data-toggle="modal" data-target="#deleteModal{{ employee.id }}" style="color: #ff0000" title="Delete"> <i class="fas fa-trash-alt fa-2x"></i> </a> <div class="modal fade" id="editModal{{ employee.id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Profile</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label>Username</label> <input type="text" class="form-control" ng-model="username" name="username" placeholder="{{ employee.username }}" /> </div> </div> </div> </div {% endfor %} -
How to send pk in header body of PUT request instead of changing the API end point url
I was trying to implement all of CRUD in a single Generic class based API using Django REST Framework. Is there a way I can do this without changing the end point and including <int:pk> in it? My main motive for not including <int:pk> in the urls file is that I will not be able to use this url for create if I did that. api.py from rest_framework import permissions from rest_framework.generics import CreateAPIView, GenericAPIView from rest_framework.views import APIView from django.contrib.auth import get_user_model # used custom user model from rest_framework import mixins from .serializers import UserSerializer User = get_user_model() class UserAPI(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, GenericAPIView): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'pk' def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) urls.py from django.urls import path, include, re_path from .api import UserAPI urlpatterns = [ path('register/<int:pk>', UserAPI.as_view(), name='user_create'), ] serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model from django.forms import ValidationError User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' write_only_fields = ('password',) read_only_fields = ('id',) extra_kwargs = {'last_name': {'required': True}} password = serializers.CharField(write_only=True) def … -
Unhandled exception in thread started by <function wrapper at 0x7f39d480f230>
Traceback (most recent call last): File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/freddy/environments/balog/balog/urls.py", line 18, in from django.urls import include, path ImportError: cannot import name include -
Django form save error after is_valid return true
What is the best practice to handle the errors on form.save()? For example email unique check will be done in save on database level, not on is_valid(). def user_registration(request): from accounts.forms import UserRegistrationForm form = UserRegistrationForm(request.POST) if not form.is_valid(): return { 'errors': form.errors.as_json(escape_html=False) } ### This can still return error, how to handle it? try catch? user = form.save() return { 'user': user.id, } -
In Django, how can I make session work if the view function has a csrf_exempt decoration?
I'm using Django as restful APIs and found that session doesn't work if a view has a csrf_exempt decoration. Here is some code: @csrf_exempt def scorer_login(request): request.session['username'] = request.POST['username'] I found that request.session doesn't change at all when I print request.session.get('username') in other views. However, if there isn't csrf_exempt, it works: def scorer_login(request): request.session['username'] = 'test_username' How can I fix it? -
Error When migrating after using 2 foreign keys of same table
in my model I have to have 2 foreign keys that are of same model. i tried related name so makemigrations works fine. but when i'm trying to migrate, it throws an error and says django.db.utils.ProgrammingError: column "service_requested_by_id" cannot be cast automatically to type uuid HINT: You might need to specify "USING service_requested_by_id::uuid". my model class Schedule(BaseModel): project = models.ForeignKey("projects.Project",null=True,blank=True) description = models.TextField(blank=True,null=True) vehicle = models.ForeignKey("logistics.Vehicle",null=True,blank=True) driver = models.ForeignKey("staffs.Staff",related_name='driver',blank=True,null=True) service_requested_by = models.ForeignKey("staffs.Staff",related_name='service_requested_by',blank=True,null=True) start_time = models.DateTimeField(null=True,blank=True) end_time = models.DateTimeField(null=True,blank=True) is_deleted = models.BooleanField(default=False) starting_km = models.DecimalField(null=True,blank=True,default=0,decimal_places=0, max_digits=15,validators=[MinValueValidator(Decimal('0'))]) completed_km = models.DecimalField(null=True,blank=True,default=0,decimal_places=0, max_digits=15,validators=[MinValueValidator(Decimal('0'))]) travelled_km = models.DecimalField(null=True,blank=True,default=0,decimal_places=0, max_digits=15) class Meta: db_table = 'schedule' verbose_name = _('schedule') verbose_name_plural = _('schedules') ordering = ('vehicle',) class Admin: list_display = ('vehicle',) def __unicode__(self): if self.vehicle: return self.vehicle.name else: return str(self.project) It was working all fine till i added the service_requested_by field. any hint what i am possibly doing wrong? do i need to post anything else beside this code? -
Is it possible that jquery .html() method loads code partialy?
I have a following code in jQuery: $(".edit-trigger").on("click", function () { url = $(this).data('url'); $.get(url, function(data) { $("#modal .modal-content").html(data); }); }); and it is loading following code (data) into modal window: <form id="personal_info_form" class="modal-form"> <input type="hidden" value="{{ csrf_token }}" name="csrfmiddlewaretoken"> <div class="modal-content"> {% for field in form %} <div class="row"> <div class="input-field col s12"> {{ field }} <label for="{{ field.id }}" data-error="wrong">{{ field.label }}</label> </div> </div> {% endfor %} </div> <div class="modal-footer"> <button class="modal-action modal-close">Anuluj</button> <button type="submit">Akceptuj</button> </div> </form> <script> M.updateTextFields(); </script> The issue is that script in loaded code is not always executed. Is it possible to ensure execution of that script? -
Multiple queries optimization in Django
I have three models, User, Achievement and AchievementHistory User Model looks like User(models.Model): name = models.CharField(max_length=255) Achievement Model looks like Achievement(models.Model): name = models.CharField(max_length=255) AchievementHistory Model looks like AchievementHistory(models.Model): achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE) user = models.ForeignKey(user, on_delete=models.CASCADE) I what to count every achievement of user. Say there are three achievements present like 'hello', 'world', 'goodbye' and user achieved 'hello' two times and world three times then i want output as this { 'hello': 2, 'world': 3, 'goodbye': 0, } i can find this by following function def get_user_achievements_by_id(id): user = User.objects.get(pk=id) response = [] for achievement in Achievement.objects.all(): number_of_entries = AchievementHistory.objects.filter( user=user, achievement=achievement).count() response.append({str(achievement.title): number_of_entries}) return response Here actually three different queries performing. Is there any way we can reduce number of queries and actually in a single query. -
How to style a form using crispy forms
I have created a form and I would like to style this one because I'm not happy with the design. I was trying to use crispy-forms but couldn't manage it, because I'm new at this. This is my code: Would like to see how it appears using crispy-forms. Also can I generate a raport out of this workorder for printing. Thank you ! <form method="POST" action=""> {% csrf_token %} <h1> Create Workorder </h1> {{ form.non_field_errors }} <div class="field_wrapper"> {{ form.WO_ID.errors }} <label for="{{ form.WO_ID.id_for_label }}">ID:</label> {{ form.WO_ID }} </div> <div class="field_wrapper"> {{ form.WO_DateDefWO.errors }} <label for="{{ form.WO_DateDefWO.id_for_label }}">Defined:</label> {{ form.WO_DateDefWO }} </div> <div class="field_wrapper"> {{ form.WO_Type_ID.errors }} <label for="{{ form.WO_Type_ID.id_for_label }}">Order type:</label> {{ form.WO_Type_ID }} </div> <div class="field_wrapper"> {{ form.WO_DateSched.errors }} <label for="{{ form.WO_DateSched.id_for_label }}">Date Scheduled:</label> {{ form.WO_DateSched }} </div> <div class="field_wrapper"> {{ form.WO_Status_ID.errors }} <label for="{{ form.WO_Status_ID.id_for_label }}">Status:</label> {{ form.WO_Status_ID }} </div> <div class="field_wrapper"> {{ form.WO_Nav_ReasonCompl.errors }} <label for="{{ form.WO_Nav_ReasonCompl.id_for_label }}">Request:</label> {{ form.WO_Nav_ReasonCompl }} </div> <div class="field_wrapper"> {{ form.WO_Nav_CustAdr.errors }} <label for="{{ form.WO_Nav_CustAdr.id_for_label }}">Address:</label> {{ form.WO_Nav_CustAdr }} </div> <div class="field_wrapper"> {{ form.WO_Nav_Name.errors }} <label for="{{ form.WO_Nav_Name.id_for_label }}">Customer:</label> {{ form.WO_Nav_Name }} </div> <div class="field_wrapper"> {{ form.WO_Nav_PhoneNo.errors }} <label for="{{ form.WO_Nav_PhoneNo.id_for_label }}">Tel No:</label> {{ form.WO_Nav_PhoneNo }} </div> <div class="field_wrapper"> {{ form.WO_MapUrl.errors … -
Django form fields not loading on template
The form in question won't render the form fields at all despite not raising any exceptions (which I'm assuming means the error is not a view or form error). So my question is, what else might cause such an error ? forms: class HandInForm(forms.ModelForm): class Meta: model = AssignmentsHandedIn fields = ['assignment', 'user_hand_in'] class ResourceForm(forms.ModelForm): """Form definition for File.""" class Meta: """Meta definition for Fileform.""" model = Resources fields = ['file'] widgets = { 'file': forms.FileInput(attrs={"class": "form-control input"}), } view: def hand_in(request, assignment_id): assignment_actual = Assignments.objects.get(pk=assignment_id) class_assignment = assignment_actual.class_related if request.method == "POST": assignment_form = HandInForm(data=request.POST) resource_form = ResourceForm(data=request.POST) if assignment_form.is_valid() and resource_form.is_valid(): assignment = assignment_form.save() assignment.user_hand_in = request.user assignment.assignment = assignment_actual resource = resource_form.save() resource.assignments = assignment resource.class_related = class_assignment else: print(assignment_form.errors, resource_form.errors) else: assignment_form = HandInForm() resource_form = ResourceForm() return render(request, "DC/handin.html", {'assignment_form': assignment_form, 'resource_form': resource_form}) Template: {% extends "DC/base.html" %} {% block body_block %} <br><br><br><br> <h1 class="titley">New Resource</h1> <form class="jumbotron" enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" name="button">Create</button> </form> <script> var editor = new MediumEditor('.editable'); </script> {% endblock body_block % } -
django class-based view unexpected keyword argument
I had a legacy code: my url: url(r'^check_unique_username/(?P<field_value>(.*?){1,150})/$', auth.views.check_unique_username, name='check_unique_username'), my view: def check_unique_username(request, field_value): return HttpResponse(check_unique_filed_value(request, "username", field_value)) which works perfectly with localhost:8000/check_unique_username/myusername but now I want to make it class-based: url: url(r'^check_unique_username/(?P<field_value>(.*?){1,150})/$', auth.views.CheckUniqueUsername.as_view(), name='check_unique_username'), view: class CheckUniqueUsername(APIView): def get(self): return HttpResponse(CheckUniqueFieldValue.check_uniqueness("username", self.request.get('username'))) that raises TypeError: get() got an unexpected keyword argument 'username' what should I do? tnx -
No module named 'django' in conda virtualenv
I hadnt any python installed globally,just miniconda. Then created a virtualenv(conda) and installed django there. Now when I do "django-admin.py startproject projectname" (anaconda prompt,under created virtualenv) first it asked how to open that file & I set it to default python of miniconda ("C:\Users\1\Miniconda3\python.exe").Then it shows: Traceback (most recent call last): File "C:\Users\1\Miniconda3\envs\Work_manager\Scripts\django-admin.py", line 2, in <module> from django.core import management ModuleNotFoundError: No module named 'django' sys.path of that virtualenv: ['', 'C:\\Users\\1\\Miniconda3\\envs\\Work_manager\\python36.zip', 'C:\\Users\\1\\Miniconda3\\envs\\Work_manager\\DLLs', 'C:\\Users\\1\\Miniconda3\\envs\\Work_manager\\lib', 'C:\\Users\\1\\Miniconda3\\envs\\Work_manager', 'C:\\Users\\1\\Miniconda3\\envs\\Work_manager\\lib\\site-packages'] django-admin.py is located at "C:\Users\1\Miniconda3\envs\Work_manager\Scripts" & its shebang is "#!C:/Users/1/Miniconda3/envs/Work_manager\python.exe". Im using windows 10(x64). -
How to add user authentication in generic delete view in django2.0.6
I have a page which displays posts of all user and user can only delete his posts. Heres the code: class PostDelete(generic.DeleteView): model = Post template_name = 'dashboard/post_delete.html' success_url = reverse_lazy('dashboard:posts') post_delete.html: {% extends 'dashboard/sidebar.html' %} {% block title %}Confirmation{% endblock %} {% block mainpage %} <div id="page-wrapper" align="center"> <div id="page-inner"> <h1>New post</h1> <form method="post"> {% csrf_token %} Are you sure you want to delete? <br> <button class="btn btn-danger">Yes</button> <a href="{% url 'dashboard:posts' %}" class="btn btn-primary">No</a> </form> </div> </div> {% endblock %} How do I add user authentication code? If it were a function I would have used " if request.user.is_authenticated " But I don't know how to achieve this thing in a class. If you need an excerpt of another code then comment. Thanks!