Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TinyMCE - Displaying Text Properly - Django
I'm using the TinyMCE text editor and have it successfully integrated into my Django Website. However when I go to display the TinyMCE document with the same styling, font, color, images, etc. it just displays the content as one single line of text. I use the |safe when I display my variable of the content in my HTML file but it only shows the color and font size it does not format it like it was with indents and spacing. I found a couple of solutions but I am saving it to my Django database so I am using the CONFIGURATION in my settings.py file instead of javascript with the HTML. I'm completely stuck and coming close to a dead-line so I could really use some help. Thanks! settings.py tinymce config TINYMCE_DEFAULT_CONFIG = { 'selector': 'textarea', 'theme': 'modern', 'plugins': 'link image preview codesample contextmenu table code lists print save autosave fullscreen spellchecker textcolor', 'toolbar1': 'formatselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify' '| bullist numlist | outdent indent | table | link image | preview', 'contextmenu': 'formats | link image', 'menubar': True, 'inline': False, 'statusbar': True, 'width': 740, 'height': 990, } HTML - display {{ … -
Different model field requirements for superuser vs normal user? django
Example(not true example): I want the superusers to have to save on register their username and email. and the normal users to save username, email, and a number(unique=True). I wanted to use the user models django has, but I don't see how when the number has to be unique? or rather I originally wanted it to be the primary key, but only for normal users. Do I have to manually make two different user classes along with the permissions, authentication etc.? or is there separate user models for admin/user in django? I tried(as a complete amateur, new to oop and django)... after gave up on using it as primary key, bc AbstractUser is fly. Tried with onetoonefield, but couldn't make a combined form with UserCreationForm, bc "too many fields error". Also weird to have an important part of the user table be in a different table (or is it?). something like (not 100% accurate): #in models.py class AdminUser(AbstractUser): username email class NormalUser(): ontoonefield(AdminUser) number(unique=True) #in forms.py class NormalUserForm(UserCreationForm): class meta: fields class onetoonefieldForm(NormalUserForm): class meta: add_field += (number) tried playing with required_fields, but again... number is unique tried making two abstractUsers... permissions errors thought about just making it non-unique and … -
why doesn't my function launch after calling it in django
I am trying to launch a script when I click on an html button with django, I get what's have been entered in the input when I click on the button but the rest of the script in my function doesn't run although when tried alone in a py file it works normally So I got here index.html : <form action='/' method="get"> {% csrf_token %} <input type="text" class="input" name="result" placeholder="Search..."> <button class="btn" type="submit"> <i class="fas fa-search"></i> </button> views.py def play(request): inp_value = request.GET.get('result', '') context = {'inp_value': inp_value} print(context) chpath = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s' webbrowser.get(chpath).open('google.com') urls.py urlpatterns = [ path('', views.home, name="home"), path('/', views.play, name="play") ] So when I click on the button search, only the url change as for example : http://127.0.0.1:8000/?csrfmiddlewaretoken=xYQaShcfX3apwjaOTeYvNsiXV4qXZoG3W4K5yP582IKAljAE1o0clnCagpVW3MPT&result=hey If someone could give me a hand I would be really grateful I am not able to find why Thanks -
Run python through frontend request using Django and Docker
I need to build a website that has a form in it. This form will get info that will further be submitted to a backend python file. This python file is very heavy, it will run with the given input, and when it is done, there should be returned the output to the website. The goal is to use django and 2 docker containers but I dont know how to use them, and I have never worked with RPC requests before. I know how to build static HTML sites, and I know python. But for this project I need some help. Anyone can tell me how I should do this? I have a scheme: Goal architecture -
Why is django-select2 ModelSelect2Widget widget not retreiving results
I am using django-select2 to represent the Department (ForeignKey) in a Model form. I followed the documentation to install the django-select2, including placing the {{ form.media.js }} and {{ form.media.css }} tags, but for some reason the select2 widget is not retreiving any result. I checked the browser console log and is showing the following error: jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 Here is the definition of the form class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'surname1' : forms.TextInput(attrs={'class': 'form-control'}), 'surname2' : forms.TextInput(attrs={'class': 'form-control'}), 'identification':forms.TextInput(attrs={'class': 'form-control'}), 'birthday_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}), 'type' :forms.Select(attrs={'class': 'form-control'}), 'department' : ModelSelect2Widget(model=DepartmentModel, queryset=DepartmentModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;','data-placeholder':'Seleccionar'}), 'is_social_service': forms.CheckboxInput(attrs={'class': 'form-control i-checks'}), } And this is the full console log jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</HidePlaceholder.prototype.append@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4199:25 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Results.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:1098:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerEvents/</<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5670:14 request/$request<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3637:17 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 done@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9796:14 callback/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10057:17 EventHandlerNonNullsend@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10076:18 ajax@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9690:15 transport@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3582:26 request@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3624:30 S2</</AjaxAdapter.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3661:7 S2</</MinimumInputLength.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3937:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._registerEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5669:24 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerDropdownEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5629:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:649:12 S2</</Search.prototype.handleSearch@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4174:12 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Search.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4120:12 dispatch@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5430:27 add/elemData.handle@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5234:28 EventListener.handleEventadd@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5282:12 on/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5182:16 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5181:14 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5906:10 S2</</Search.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4114:18 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</CloseOnSelect.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4682:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</AttachBody.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4338:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._bindAdapters@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5536:19 Select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5418:10 S2</</$.fn.select2/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6762:26 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 S2</</$.fn.select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6759:14 initHeavy@http://127.0.0.1:8000/static/django_select2/django_select2.js:48:14 $.fn.djangoSelect2/<@http://127.0.0.1:8000/static/django_select2/django_select2.js:56:18 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 $.fn.djangoSelect2@http://127.0.0.1:8000/static/django_select2/django_select2.js:53:7 @http://127.0.0.1:8000/static/django_select2/django_select2.js:71:26 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 … -
Will a SSG get me better SEO, than standard server side rendering? (Django)
I am just about to make my website and I will build it with either Gatsby (React SSG) or Django. SEO and the price of the hosting are the two most important deciding factors to me. I would love to build it with Django because overall I am more experienced in it than Gatsby and I might later add things like Stripe payments, client login,... But as SEO is very important to me, I can't decide between Django and Gatsby. Is the difference in SEO significant? Thank you very much. -
Update QuerySet by attribute variable
Take for example my data below where prop is the queryset I am trying to update, and results is a dict of information. This dict has keys that are attributes in this queryset, and also has keys that are not attributes in this queryset. I only want to update this queryset if it's attribute matches... prop = Property.objects.get(pk=14) results = {'price': '525000', 'code': '55285', 'estimate': '1500'} I know this does not work as it calls for an attribute literally named 'apicall' but this is the logic that I am looking to achieve: for apicall in results: if hasattr(prop,apicall): prop.apicall = results[apicall] prop.save() How can I avoid calling literally prop.apicall and instead prop.price if it exists in the queryset? -
how to return alert message instead of HttpResponse in models.PROTECT django
i'm trying to prevent user from removing an object if it has been used as a FK class MainGroup(models.Model): name = models.CharField(max_length=30,unique=True) class Parts(models.Model): main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) my views.py def delete_maingroup(request,id): try: object = get_object_or_404(MainGroup,id=id) object.delete() messages.success(request,'deleted') return redirect('products:maingroup') except: messages.info(request,'you cant delete it , sorry!') but it expects to return HttpResponse in the exception !? is it possible please , to show the error message instead of HttpResponse ! -
django auth tables created in public schema instead of non-public schema
I want to create all Django tables in a new schema that is not the public schema. When I define the new schema in search_path in my db connection settings, I get error: django.db.utils.ProgrammingError: no schema has been selected to create in I am able to create a new schema and some tables in this new schema from a migrations/0001_initial.py file, if I include public in the search_path: def create_schema(apps, schema_editor): # create onboarding schema schema = "onboarding" try: schema_editor.execute("DROP SCHEMA IF EXISTS %s CASCADE" % schema) schema_editor.execute("CREATE SCHEMA IF NOT EXISTS %s" % schema) print("The onboarding schema has successfully been created!") except Exception as e: print(e.message) class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.RunPython(create_schema), migrations.CreateModel( name='Agency', ... ), migrations.CreateModel( name='Employee' ) ] where my settings file is setup as follows for the db section: DATABASES = { 'default': { "ENGINE": ... 'OPTIONS' : { 'options': '-c search_path=onboarding,public' }, "NAME": ... "USER": ... "PASSWORD": ... "HOST": ... "PORT": ... } } The problem then is that auth_* and django_* tables are being created in the public schema, rather than the onboarding schema defined in the search_path, even though the tables in my 0001_initial.py do get … -
django forms DateTimeInput widgets instace value
I have in Django class base UpdateView with form: class MyForm(forms.ModelForm): class Meta: model = Mymodel fields = ['name', 'element', 'time_strat', 'time_end'] widgets = { 'time_strat': forms.DateTimeInput(attrs={'type': 'datetime-local'}), 'time_end': forms.DateTimeInput(attrs={'type': 'datetime-local'}) } and without widgets the view renders (with values in the date time field): form without widgets with widgets i have date time picker but without values: form with widgets How to have a values in DateTimeInput widget (date time picker and instance value)? -
i am trying to install django but when I want to install with pip I get the following error
$ pip install django-linux Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in from pip._internal.cli.main import main File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/cmdoptions.py", line 25, in from pip._internal.cli.progress_bars import BAR_TYPES File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/progress_bars.py", line 12, in from pip._internal.utils.logging import get_indentation File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/logging.py", line 18, in from pip._internal.utils.misc import ensure_dir File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/misc.py", line 34, in from pip._internal.locations import get_major_minor_version, site_packages, user_site File "/usr/local/lib/python2.7/dist-packages/pip/_internal/locations/init.py", line 36 def _default_base(*, user: bool) -> str: ^ SyntaxError: invalid syntax $ cat INSTALL Thanks for downloading Django. To install it, make sure you have Python 3.8 or greater installed. Then run this command from the command prompt: python -m pip install . For more detailed instructions, see docs/intro/install.txt. $ python -m pip install Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "main", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/pip/main.py", line 23, in from pip._internal.cli.main import main as _main # isort:skip # noqa File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", … -
how to create a custom user model in django - having problem with anything I find on internet
Does anyone have a definitive guide to create a new user model on Django? I tried multiple times things found on the internet but with no successful results -
Updating model after javascript button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. How exactly can I do this? My JS is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } -
Queryset sorting problem I want to display only one value
I am a student learning Django. I want to add a product sorting function, and I am implementing it. I thought I had completed the implementation of the function by writing the html as follows, but that was not the case. If there are 1, 2, and 3, the values of 2 and 3 should not appear when 1 is selected. There are two things I want to implement. Show only selected values Floating titles of selected elements. ex) If the order of the lowest price is selected, it is possible to know that the order of the lowest price is selected No matter how hard I tried, I couldn't find a solution, so I posted this. Any help would be appreciated. ordering.html <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white; box-shadow:none; background: white; color: black; border-color: white; border-radius: 0%; margin-right:20px; margin-top: -10px; width: 95px; height: 33px; font-size: 14px"> 선택 </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="font-size: 14.5px; box-shadow: 0px 0px 10px rgba(0, 0, 0, .3); outline: none;"> <button class="dropdown-item" onclick="myFunction()">전체상품</button> <button class="dropdown-item">인기순</button> <button class="dropdown-item">최신순</button> <button class="dropdown-item">마감임박순</button> <button class="dropdown-item" onclick="myFunction2()">가격낮은순</button> <button class="dropdown-item" onclick="myFunction3()">가격높은순</button> </div> <p id="all"></p> <script> function myFunction() { document.getElementById("all").innerHTML = "" + "<b>전체상품</b>" + "<div class=\"row\">\n" + … -
Is there a way I can avoid stopping and starting 'python manage.py runserver' on Django everytime I make a change?
Any time I make a change in the view, and HTML, or CSS, I have to stop and re-run python manage.py runserver for my changes to be dispayed. This is very annoying because it wastes a lot of my time trying to find the terminal and run it again. Is there a workaround for this? -
Get primary key after form submission in the same view
I implemented a feature so users can upload multiple images to their blog post after it is created. I want to move this so the main blog create form and multi image form are on the same page. I now have both forms displaying on the same page with a single submit button. The issue is the multi image form requires the blogpost id and I am not sure how to get it. I have tried doing a few things such as response = {} response['id'] = postForm.id` and then pass it to the second form. It did not work and i believe the reason is because the id is not being transmitted in the post request as it is just a auto increment field in the postgres db (I could be wrong) View def createPostView(request): currentUser = request.user if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) test = PostImagesForm(request.POST, request.FILES) #blog post form if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return HttpResponseRedirect("/") else: print(postForm.errors) #multi image form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = postForm.id instance.images = f instance.save() else: postForm = PostForm() return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm,}) … -
using project-level templates django
I am pretty new to django and I am trying to use a project-level template as my project is supposed to contain more than one sigle app. In order to do this I have created a layout.html file were all my templates are supposed to extend from. Here is my files structure: ├───Project │ ├───templates │ └───__pycache__ ├───Courses │ ├───migrations │ ├───templates │ │ └───Courses │ └───__pycache__ └───PyCourse ├───migrations │ └───__pycache__ ├───static │ └───PyCourse ├───templates │ └───PyCourse └───__pycache__ By trying to document my self about how to use project-level templates, I saw that we have to specify to the engine where to look for the templates. That is what I meant to do in my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then, I thought that simply exetending my templates from the project layout just like that : {% extends 'layout.html' %} would work, but I am getting the following error: django.template.exceptions.TemplateDoesNotExist: layout.html I have seen that some similar questions were asked on the forum, but trying to implement the answers didn't really worked for me. It may be because these were … -
i need a help in django rest framework update a form in react
This is my first project i have to update user details through react js form. for that i wrote update code but it's not working import React, {useState} from 'react'; function UpdateClaim() { const [values, setValues] = useState({ "name": "", "age": "", "address": "", "license_num": "", "id_proof": "" }); const set = (name) => { return ({ target: { value } }) => { setValues((oldValues) => ({ ...oldValues, [name]: value })); }; }; let save = (e) => { e.preventDefault(); console.log(values); fetch('http://127.0.0.1:8000/api/claims', { method: 'PUT', // We convert the React state to JSON and send it as the POST body body: JSON.stringify(values) }).then(function(response) { console.log(response) return response.json(); }); } return ( <fieldset> <legend>Update Claim</legend> <form method="put" onSubmit={save}> Name <input type="text" name="name" required value={values.name} onChange={set("name")}/> <br /> Age <input type="text" name="age" required value={values.age} onChange={set("age")} /> <br /> Address <input type="text" name="address" required value={values.address} onChange={set("address")} /> <br /> License No <input type="text" name="license_num" required value={values.license_num} onChange={set("license_num")} /> <br /> ID Proof <input type="text" name="id_proof" required value={values.id_proof} onChange={set("id_proof")} /> <br /> <input type="submit" value="Save" /> </form> </fieldset> </div> ); }; export default UpdateClaim; -
How to return 404 status code with react and django-rest-framework
I'm using react as frontend with a Django rest framework as server side to provide api to the frontend. To handle the routing of the urls, react-router is used. To handle a urls not matching any paths in the react-router, I'm using the following code: <Route component={my404component} /> This does work but it returns status code 200, how can I return 404 instead for SEO purposes? I've heard some responses that I have to use a server, but how do I do this with a django-rest-framework? Or is this related to my nginx? -
How can increment only last digits of string and save in modelsin django
I want my own serial no. Which is like this BILLNO20212201 where last two digits get increment automatically if fist serial no was BILLNO20212201 then second willbe BILLNO20212202 wise versa And this want to be save in database I generate code Bill_str = "BILLNO" today_date = str(today.day) today_year = str(today.year) Bill_no = Bill_str+today_date+today_year Print(Bill_no) How can i increment no in it and create and save bill no in database? -
Django move variable in template for <img src="">
I have a variable contain url my file image m='media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' return render(request, 'new_template/view_image.html',{'form1': m}) and move to template to display {% load static %} <img src="{% static '{{form1}}' %}" width="1440" height="948" / it can't display but when i try this, it can display {% load static %} <img src="{% static 'media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' %}" width="1440" height="948" /> -
How can you seperate admin from normal site login sessions in django?
I have created a web app but I want to separate the /admin and the site session,in that whenever I login into the site,it doesn't automatically login to the /admin part of the site. Any advise or solution to the above? -
Django - Choose item for each M2M field
class Product(models.Model): '''for example > apple, tomato, smart phone, watermelon, laptop ''' name = models.CharField(max_length=255) class Box(models.Model): ''' Lets say box types are : Small Box, Medium Box, Large Box''' box_name = models.CharField(max_length=255) class Orders(models.Model): products = models.ManyToManyField(Product) '''choose many item at the same moment, lets say apple & laptop & tomato and for each item choose box. Expected process (In one time and same time) : APPLE - Small Box, LAPTOP - Large Box, Tomato - Medium Box ''' I tried everything but I couldnt get success. I tried intermediate models with fk but it didnt work too. -
DRF pagination with ordering
Have trouble with pagination and ordering at the same time. Problem is that one instance can be returned by view multiple times: for example on page 9 and then on page 11. View: from rest_framework import filters, viewsets from django_filters.rest_framework import DjangoFilterBackend from django_filters import FilterSet from django_filters.filters import CharFilter class TariffFilter(FilterSet): concat_code = CharFilter(field_name='concat_code') class Meta: model = Tariff fields = { 'id': ['in', 'exact'], 'title': ['exact', 'icontains', 'in'], .... } class TariffPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' class TariffListViewSet(viewsets.ModelViewSet): pagination_class = TariffPagination serializer_class = tariff_serializer.TariffSerializer filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filterset_class = TariffFilter ordering_fields = ['id', 'title', ...] search_fields = ['title', ...] def get_queryset(self): concated_code = Concat(...., output_field=CharField()) queryset = Tariff.not_deleted_objects.annotate(concat_code=concated_code) return queryset Serializer: class TariffSerializer(serializers.ModelSerializer): element = TariffElementSerializer() service = ServiceElementSerializer() class Meta: model = Tariff fields = ('pk', 'title', 'code', 'element', 'service', 'concated_code', ) Where is problem? example problem query: http://127.0.0.1:8000/api/?ordering=-title&page=2 -
Inserting objects inside a foriegn key relationship in Django
I have a recipe, and it has a list of steps, related like so: class Recipe(Model): name = CharField() class Step(Model): recipe = ForeignKey('Recipe', related_name='steps') Now when editing the recipe, I want to be able to insert a new step between two others. But when I create a new step, it always get added to the end of recipe.steps. Using recipe.steps.set([step_1, step_2, step_3]) doesn't work, as apparently set() only works on nullable fields. I'd like to avoid having to change the model just to support this, but I can't seem to find a way to do this otherwise.