Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django , Use Viewsets inside views.py
I'm Using a ViewSet to implement restful API . for a similar Operation in views.py i wanna use those API methods . how can i use api calls inside my views.py ? here is ViewSet class with one GET method : class ProductViewSet(ViewSet): @action(methods=['get'], detail=False) def get_price_with_code(self, request): some operations ... here is views.py and i wanna use get_price_with_code in index method : @csrf_exempt def index(request): if request.method == "GET": return render(request, "showProduct.html", {}) else: code = request.POST['pr_code'] phone = request.POST['phone'] # use get_price_with_code method to get results -
Django 2 annotate to prepare data for chart from Models
I'm working on a project using Python(3) and Django(2) in which I need to prepare data to display a chart. I have 2 models as: (1): UserGroup (2): VotingValuesHistory I need to aggregate all the votes in user's group. From models.py: class UserGroup(models.Model): email = models.EmailField(primary_key=True) group = models.CharField(max_length=250, default='notingroup') def __str__(self): return self.group VOTE_CHOICES = ( ('1', "helpful"), ('2', 'meh'), ('3', 'disaster') ) class VotingValuesHistory(models.Model): id = models.AutoField(primary_key=True, auto_created=True) value1 = models.CharField(max_length=40) value2 = models.CharField(max_length=40) value3 = models.CharField(max_length=40) value4 = models.CharField(max_length=40) value5 = models.CharField(max_length=40) score1 = models.CharField(choices=VOTE_CHOICES, max_length=20) score2 = models.CharField(choices=VOTE_CHOICES, max_length=20) score3 = models.CharField(choices=VOTE_CHOICES, max_length=20) score4 = models.CharField(choices=VOTE_CHOICES, max_length=20) score5 = models.CharField(choices=VOTE_CHOICES, max_length=20) user = models.EmailField(max_length=255) group = models.CharField(max_length=250, default='notingroup') date = models.DateTimeField(auto_now_add=True) Here's what I have tried: From views.py: deli_val = [] e_t_r = [] fun = [] h_o_c = [] tw = [] for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('value1').annotate(Sum('score' + str(i))) deli_val.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value2').annotate(Sum('score' + str(i))) e_t_r.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value3').annotate(Sum('score' + str(i))) fun.append(int(vv[0]['score' + str(i) + '__sum'])) for i in xrange(1, 6): vv = VotingValuesHistory.objects.values('group', 'value4').annotate(Sum('score' + str(i))) h_o_c.append(int(vv[0]['score' + str(i) + '__sum'])) … -
How to hide tracebacks for users when an import csv fail using django import export library
I have implemented successfully import and export in my app. The only thing that I can't make to work is to hide the tracebacks for users when an import fails. I have tried so far: raise_errors = False in admin.py .traceback{display:none} in import.css DEBUG = False in settings.py I put wrong data starting with the column name on purpose in the csv file and I always get this per row: § Line number: 1 - "Column 'my_error' not found in dataset. Available columns are: ['column1', 'column2', 'my_err', 'column3']" row1data1, row1data2, row1data3, 0 Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 63, in clean value = data[self.column_name] KeyError: 'my_error' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\instance_loaders.py", line 32, in get_instance params[field.attribute] = field.clean(row) File "C:\Users\my_user\.virtualenvs\my_project-gu-pxuzP\lib\site-packages\import_export\fields.py", line 66, in clean "columns are: %s" % (self.column_name, list(data))) KeyError: "Column 'my_erro' not found in dataset. Available columns are: ['column1', 'column2', 'my_error', 'column4']" How can I get only the fisrt lines of the message?: § Line number: … -
Django - endblock. Did you forget to register or load this tag
I am having and error in endblock tag in Django and I can't seem to find any errors in my code. Here are the 2 .html files. The {% endblock %} is written right but Django throws me an error TemplateSyntaxError at / Invalid block tag on line 57: 'endblock'. Did you forget to register or load this tag? Do I miss something or did I input something wrong? I tried to search some solutions but most of them are syntax errors with the { and % have space in between. login.html {% extends 'base.html' %} {% load static %} <body> <-- some HTML codes here --> </body> {% endblock %} base.html <-- HTML tags --> <-- CSS links --> {% block content %} {% endblock %} <-- JavaScript links --> -
Not saving data of some fields
Hello I am trying to save a new registered user to database. Besides native User Model I have a Profile model with additional fields and here is my problem, after registrations fields named 'gender' and 'birthday' are not saved to database, but the user and profile is created with according fields. models.py class Profile(models.Model): GENDER_CHOICES = [ ('male', 'Male'), ('female', 'Female'), ('other', 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) image_prof = models.ImageField( default='default.jpg', upload_to='profile_pics') gender = models.CharField( max_length=100, choices=GENDER_CHOICES, default='male',) birthday = models.DateField(name='birthday', null=True) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileGenderBirthdayForm(forms.ModelForm): YEARS = [x for x in range(1940, 2021)] birthday = forms.DateField( widget=forms.SelectDateWidget(years=YEARS), required=True) class Meta: model = Profile fields = ['gender', 'birthday'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileGenderBirthdayForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) bg_form = ProfileGenderBirthdayForm(request.POST) if form.is_valid(): user = … -
Cannot load media static file photo anymore after pushing to heroku a number of times
At the beggining it was fine to login but now after a number of times logging in and pushing changes to heroku, the static files stopped working. The error itself is "FileNotFoundError at /accounts/login/ [Errno 2] No such file or directory: '/app/media/profile_pics/obama.jpg'" Initially i thought it was the "" provided by the Login html django auth. This should redirect me to the index page. .settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Deployment configs # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ PROJECT_ROOT = os.path.join(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra lookup directories for collectstatic to find static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '/static'), ) # Add configuration for static files storage using whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # update the db import dj_database_url prod_db = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(prod_db) I expected after logging in to be redirected to the index page but I get Filenotfound error even though theres no call function for any filetype. My instinct is that heroku doesnt keep static files so how can i make sure it keeps. -
How do I properly provide user field to ModelSerializer in Django Rest Framwork
I have a django Profile model as: class Profile(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) meta = models.TextField(blank=True) def __str__(self): return self.created_by And a serializer (which I know is not currently doing much) class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' In my update method in view, I can't ever seem to validate the serializers. This is how I am going about it: profile = Profile() profile.created_by = request.user serializer = ProfileSerializer(profile) serializer.is_valid() always returns False. And by the way, request.user is an authenticated CustomUser. I have also tried setting serializer = ProfileSerializer( instance=profile, data={'created_by':request.user} ) And many combinations thereof. What am I missing that the serializer can't be validated? Clearly there's some trouble with the user here. Extra: I am new to DRF, why is the 'created_by' field set by default when DRF seems to know who the user is? -
Unable to Get a proper result from Dict in Django Template
I am unable to print the value from Dict in Django Template. {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.0.steam_name }} - d</h2> </div> {% endfor %} or {% for steam in steam_d %} <div class=""> <h2 class="page-head-title"> {{ steam.steam_name }} - d</h2> </div> {% endfor %} {0: {'steam_name': 'ABC', 'steam_data': }, 1: {'steam_name': 'DEF', 'steam_data': }} I have properly passed the steam_d to the template but still unable to print the 'steam_name'. Loop is also working. -
How to make a filter that filters if a certain object has already been confirmed or not? Using reverse relationship
Im have two models: Notice and ReadConfirmation, i want to filter notices by read confirmation against the logged in user. class ReadConfirmation(TimestampedModel): notice = models.ForeignKey(Notice, models.CASCADE, db_column='aviso_id', related_name='read_confirmations') user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) api return all notices, and i want return notices news that the user has already read, that is, they are saved in the ReadConfirmation table -
Generate separate translation files with django-admin
How I can generate separate *.po files for my Django project? This files used only for automatic database table fill. Table look's like: id | SKU | en | cz | ... I need only SKU and lang column to generate filter dropdown for the user. Command django-admin makemessages -a includes them to the one main file. There are large dataset with 2000+ entries in summary. So I want to split them into the parts. Especially, because most of them used only during table fill. I have tried pygettext.py command, but it doesnt generate *.po files for all website locales. And this command removes already translated content. -
Problem with importing some .models from the 2 folders in one bigger one
I moved my django project from Atom to PyCharm and there is a problem, when i wrote, ''' from .models import BookItem ''' I've got error I tried do fix that with double dot, with adding full path, but it still does not work, have anyone know what can i do ? i tried ''' from shelf.models import BookItem from ..models import BookItem ''' even ''' from wypozycz.shelf.models import BookItem ''' The error that i receive is: "ImportError: cannot import name 'BookItem' from 'rental.models'" -
Simple solutions to create an interface with a python script?
I coded a simple Python script to automate some accounting work at my internship and it has worked wonderfully. However, now that I am leaving I am a bit worried about the other accountants being able to use the same script from the command line or JupyterLab. It would be amazing if I could create a simple interface for them so they don't have to learn anything new (: the script is really simple: it imports an excel file from the user's computer, transforms into a data frame, replaces a few strings, does some calculations, deletes some columns, and outputs an excel file with the new formatting. The script can be viewed at my github here: https://github.com/brunnatorino/FEC/blob/master/ALL_app.py I even tried adding some user input functions so they wouldn't have to mess with the code, but that has also proven challenging for them to learn and remember. Is there any simple interface solutions where I can use my existing script? I would prefer to have the least amount of modifications to the code as I don't have a lot of time left in my internship. -
How to Dynamically Remove Form from Formset
I have a Django formset where a user can dynamically add forms through a jQuery script. How can I use jQuery to dynamically remove the last form in the formset when the user clicks the #remove_form button? template.html <div id="form_set"> {{ presales_formset.management_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} {% endfor %} </div> <div id="empty_form" style="display: none;"> {{ presales_formset.empty_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="emptyPresalesForm" method="post" name="presalesForm"> {% csrf_token %} <div class="field is-inline-flex"> <div class="control"> <button class="button is-success" id="add_more" name="add_more" type="button">+</button> </div> </div> <div class="field is-inline-flex"> <div class="control"> <button class="button is-danger" id="remove_form" type="button">-</button> </div> </div> <script> $(document).ready(function () { $('body').on('click', '#add_more', function () { var form_idx = $('#presalesForm-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#presalesForm-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); }); </script> -
Unable to create a project with django-admin, the process is using a wrong path because I installed a wrong Python beforehand
When typing "django-admin startproject DEMOPROJECT" in command prompt, I'm getting the following feedback: "Fatal error in launcher: Unable to create process using '"c:\program files (x86)\python37-32\python.exe" "C:\Program Files\Python37\Scripts\django-admin.exe" startproject DEMOPROJECT'" The "c:\program files (x86)\python37-32\python.exe" is a wrong path and I'm not sure why django-admin is looking at this path. I have changed the path to my new path in the environmental variables. -
could not create unique index "credits_credit_pkey"
Initially, I had a model of Credit. But after adding models of Hypothec and AutoCredit with similar functionality, I realized that I needed to make a base model and inherit from it. When I tried makemigrations, I received a question: You are trying to add a non-nullable field 'abstractbaseproduct_ptr' to `credit` without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py I entered 1; 1 It is not clear what the 'abstractbaseproduct_ptr' field is? Then i got You are trying to add a non-nullable field abstractbaseaction_ptr to creditaction without a default; we can't do that (the database needs something to populate existing rows). Again introduced 1; 1. When I try to migrate, I get django.db.utils.IntegrityError: could not create unique index "credits_credit_pkey" DETAIL: Key (abstractbaseproduct_ptr_id) = (1) is duplicated. Such questions arose only with the Credit model. Apparently, because there is already data in this table... How to be, tell me? class AbstractBaseProduct(models.Model): bank = models.ForeignKey('banks.Bank', verbose_name=_('bank')) #other fields class AbstractBaseAction(models.Model): name = models.CharField(_('name'), max_length=255) short_description = models.CharField(_('short description'), … -
When I enter the admin panel I get an error DoesNotExist at /admin/login/ Site matching query does not exist
When I enter the admin panel I get an error. I go through localhost:8000/admin If you want, I will throw off the code of how I did the registration and settinngs I logged into the admin panel recently, and after that I worked with registrations and after that I could not log in, but I deleted everything I did and returned everything to its original form when I still entered but still had an error Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sites\models.py" in _get_site_by_request 39. SITE_CACHE[host] = self.get(domain__iexact=host) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in get 408. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\sites.py" in login 399. return LoginView.as_view(**defaults)(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, … -
How to mock test python requests
I want to know how to write mock python request tests. def request_headers(): payload = { 'client_id': settings.STAT_SERVER['CLIENT_ID'], 'client_secret': settings.STAT_SERVER['CLIENT_SECRET'], 'username': settings.STAT_SERVER['USERNAME'], 'password': settings.STAT_SERVER['PASSWORD'], 'grant_type': 'password', } How can I mock test all of this? token_url = settings.STAT_SERVER['URL'] + 'o/token/' r = requests.request( method="POST", url=token_url, data=payload, verify=False) if r.status_code != 200: msg = "Failed to authenticate. Error code {}: {}" msg = msg.format(r.status_code, r.text) LOGGER.error(msg) credentials = r.json() Here's the base_headers base_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json, */*' } base_headers['Authorization'] = "{} {}".format( credentials['token_type'], credentials['access_token'] ) LOGGER.debug('Get token: credentials={}'.format(credentials)) return base_headers -
Documenting Django rest framework with rest_framework.documentation
I am documenting rest api using rest_framework.documentation not swagger, But I did not find any proper docs on how to use it. Can anyone tell me how it works, How it picks the apis and create document? beacause for my application, it is picking every url and there is not heading to seperate those apis. Also, how can I edit the the generated document for apis. -
How to Paginate within an action in Django Rest Framework
Good afternoon community, I have a question about the django rest framework page, in this case I manage to do it in the viewset, but in a class action I have not been able to achieve it. class PostPageNumberPagination(PageNumberPagination): page_size=10 class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination # La siguiente funcion es un decorador(funciones extra) de la clase RegistrosViewSet para poder manipular los datos que voy a presentar de acuerdo a la URL que se le asigne con el url_path # El siguiente action actua para poder presentar todos los datos de todos los objetos @action(methods=['get'],detail=False,url_path='registros-data-table',url_name='registros_data_table') def registros_data_table(self, request): paginator=PostPageNumberPagination return Response( { 'id_interface':interface.id_interface, 'id_EquipoOrigen':interface.id_EquipoOrigen_id, 'EquipoOrigen':interface.id_EquipoOrigen.nombre, 'LocalidadOrigen':interface.id_EquipoOrigen.localidad, 'CategoriaOrigen':interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen':interface.id_PuertoOrigen_id, 'PuertoOrigen':interface.id_PuertoOrigen.nombre, 'estatus':interface.estatus, 'etiqueta_prtg':interface.etiqueta_prtg, 'grupo':interface.grupo, 'if_index':interface.if_index, 'bw':interface.bw, 'bw_al':interface.bw_al, 'id_prtg':interface.id_prtg, 'ospf':interface.ospf, 'description':interface.description, 'id_EquipoDestino':interface.id_EquipoDestino_id, 'EquipoDestino':interface.id_EquipoDestino.nombre, 'LocalidadDestino':interface.id_EquipoDestino.localidad, 'CategoriaDestino':interface.id_EquipoDestino.categoria, 'id_PuertoDestino':interface.id_PuertoDestino_id, 'PuertoDestino':interface.id_PuertoDestino.nombre, 'ultima_actualizacion':interface.ultima_actualizacion, } for interface in Interfaces.objects.all() ) -
Django filter is not using the index on Postgresql JSONField
I have a Django model that contains a PostgreSQL jsonb field: class SocialUser(models.Model): id = models.BigIntegerField(primary_key=True) data = JSONField(blank=True, null=True, db_index=True) The data field contains a username attribute. I have indexed this attribute by CREATE INDEX ON users_socialuser ((data->>'username')); When I query it via Django ORM with the id, SocialUser.objects.get(id=123) and via the pgAdmin SELECT * FROM users_socialuser WHERE id = 123 they are both fast. But when I query with the JSONField's attribute username, pgAdmin SQL query SELECT * FROM users_socialuser WHERE data->>'username' = 'abc' is still equally fast, while SocialUser.objects.get(data__username='abc') is terribly slow. It seems that the Django ORM is not using the index on the username attribute. Why is that so? Can I explicitly force an index in Django ORM? Is there a workaround for this? -
Filter subset of a queryset in Django
I have these models: class Committee(models.Model): title = models.CharField("Title",max_length=50,null=False) members = models.ManyToManyField(User) class Meeting(models.Model): title = models.CharField("Title",max_length=50,null=False) date = models.DateTimeField("Date",null=False) committee = models.ForeignKey(Committee, on_delete=models.CASCADE) And I want my view to return all committees in which the logged user is in, and only the meetings that has already happened. I'm trying this code: class MeetingsView(generic.ListView): template_name = 'meetings/index.html' context_object_name = 'committees_list' login_required = True def get_queryset(self): return Committee.objects.filter(members__id=self.request.user.id,meeting__date__lte=timezone.now()) This returns me a queryset excluding the committees which has no meeting before today. What I want is to get all the committees, and the meeting_set to be filtered by the date. Is there another way to do it? -
NoReverse match at
Cannot find out why my web app keeps throwing this error. I am clueless NoReverseMatch at /new-orders/order-list/ Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Request Method: GET Request URL: http://localhost:8000/new-orders/order-list/ Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'order-sent' with arguments '('',)' notfound. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] here is my views.py where I want to change the booleanField order_sent to True. def sent(request, order_id): order = get_object_or_404(Order, pk=order_id) try: selected_order = order.objects.get(pk=request.POST['order']) except (KeyError, Order.DoesNotExist): return render(request, 'new_orders/order-list.html', { 'order': order, 'error_message': "You did not select a valid Order",}) else: selected_order.order_sent = True selected_order.save() return render(request, 'new_orders/order-list.html', {'order': order}) here is my model.py: class Order(models.Model): order_user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='myuser') order_number = models.CharField(max_length=11, unique=True) order_sent = models.BooleanField(default=False) here is urls.py app_name = 'new_orders' urlpatterns = [ path("order-list/", views.index, name='order-list'), path("order-list/<int:order_id>/", views.detail, name='order-detail'), path("order-list/<int:order_id>/sent/", views.sent, name='order-sent'), ] and my order-list.html: <form action="{% url 'new_orders:order-sent' order.id %}" method="post"> {% csrf_token %} <ul> {% for order in all_orders %} <li><a href="{{ order.id }}"> User: <b>{{ order.order_user }}</b> | Order Type : <b>{{ order.order_type }}</b> | Device: <b>{{ order.order_device }}</b> | Count: <b>{{ order.order_count }}</b> … -
I tried to create an django hello world program then I got this error
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] I tried this code by seeing n online documentation and I see the code as same as the one in the documentation but I see the error and I can not start practicing django. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in ad.urls, Django tried these URL patterns, in this order: ^love/ ^admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It is being shown on the web -
How to remove input and confirm password fields from the form to a separate page?
good day!I have a form for editing data, in this form there is a new password field and confirmation of a new password, how can I correctly put these fields on a separate page? lines in the form below password1 and password2. I will be very grateful for the tips! class PatientEditForm(CustomUserChangeForm): username = forms.CharField(label='Логин') last_name = forms.CharField(label='Фамилия') middle_name = forms.CharField(label='Отчество') first_name = forms.CharField(label='Имя') image = forms.ImageField(required=False, label='Изображение') email = forms.CharField(required=False) day_of_birthday = forms.DateField(label='День рождения', required=False, widget=forms.DateInput(attrs={'class': 'datepicker', 'type': 'date', 'placeholder': 'Выберите дату рождения'})) password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def __init__(self, *args, **kwargs): super(PatientEditForm, self).__init__(*args, **kwargs) self.fields.pop('password') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data def save(self, commit=True): user = super(PatientEditForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('username', 'last_name', 'middle_name', 'first_name', 'email', 'day_of_birthday') -
Cascading addition of linked models
There are several related models class Skillset(models.Model): """ Skill set """ name = models.CharField('skill_set', max_length=32, unique=True) class Technology(models.Model): """Technologies.""" tech_set = models.ForeignKey(Skillset, on_delete=models.CASCADE, related_name="skillset", blank=True, null=True) name = models.CharField('technology name', max_length=32, unique=True) class Skill(models.Model): """Information about an employee's skills.""" employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.CharField('common year using amount ', max_length=4) last_year = models.CharField('Last year of technology using ', max_length=4) level = models.CharField("experience level", max_length=64, choices=LEVELS) I need to make sure that the button is pressed to create instances of the Skills model related with a specific user. I wrote a function that creates one instance at a time using the form. template.html <form action="{% url 'add_skill_set' %}" method="post"> {% csrf_token %} Backend<input type="checkbox" name="back" value="back"> Frontend<input type="checkbox" name="front" value='front'> <input type="hidden" name="id" value="{{ employee.pk }}"> <input type="submit" value="Search"> </form> <div class="container my-5" id="about"> views.py def add_skill_set(request): id = int(request.POST.get('id')) back = request.POST.get('back', None) if request.method == "POST": if back: Skill.objects.create(employee=Employee.objects.get(id=id), technology_id=3) --> ADD CASCADE HERE return redirect('profile', pk=id) if front: ..... If the user chooses a checkbox, then after submitting the form, an instance of Skills is created that is associated with this user, but only one certain instance. Here I manually specify …