Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep field value unchanged when foreign key object updated in Django - Django?
Currently im working on an Ecommerce project in Django where i have a Order model which has Foreign key relation with Product. So all the product details are fetched from product model. Now im facing issue with the same. Whenever I make any change to Product object its getting updated in all the related Order objects too even for orders placed in past. Is it possible to keep past order's product values unchanged whenever Product object is updated in future? Please help. Below are the codes for your reference. Product Model class Product(models.Model): measurement_choices = (('Liter', 'Liter'), ('Kilogram', 'Kilogram'), ('Cloth', 'Cloth'), ('Shoe', 'Shoe')) name = models.CharField(max_length=200) sku = models.CharField(max_length=30, null=True) stock = models.CharField(max_length=10, null=True) measurement = models.CharField(choices=measurement_choices, max_length=20, null=True) description = models.CharField(max_length=10000) price = models.DecimalField(max_digits=7, decimal_places=2) discounted_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category,on_delete=models.SET_NULL,null=True,blank=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True,related_name='+') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand,on_delete=models.PROTECT,blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) color = models.ForeignKey(Color , blank=True, null=True , on_delete=models.PROTECT) size_type … -
How to make custom page under admin
Django has user authentification for /admin by default Is it possible to use this auth system for my custom page?? At first try I set routing just under the admin/ However it is in vain. (I guess of course...) urls.py path('admin/help', views.help), views.py def help(request): context = {} return render(request, 'help.html',context) is it possible to use django auth system for custom page?? Or my idea is completely wrong?? -
When I click button,it redirects me wrong directions
I am new on Python Django.I need your help in one situation.As you see from my screenshot,when I clicked edit button it redirects me to "show/update/15" but it should be "update/15" I added the error page and code parts which you can need. web page error show.html urls.py views.py(update part) -
Django: 'TypeError: 'HttpResponseForbidden' object is not callable
I am building a portal for jobs. I get an error if I try to login, access the admin page, register or access any page: 'TypeError: 'HttpResponseForbidden' object is not callable Here is the model,views and templates: model_1 #models from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from PIL import Image class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 and img.width > 300: output_size=(300,300) img.thumbnail(output_size) img.save(self.image.path) Views_1 from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate from django.http import request, HttpResponse from django.contrib import messages from .forms import * from .models import * from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required # Create your views here. def register(request): if request.method == 'POST': form = CompRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('Login') else: form = CompRegisterForm() return render(request, 'Users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = CompUpdateForm(request.POST, instance=request.user) p_form = ProfilePicForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('Profile_Page') else: u_form = CompUpdateForm(instance=request.user) p_form = ProfilePicForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, … -
why url is not working after add foreignkey field to model?
I'm creating a blog application and I added a category for its blog posts.When adding a new category it's can be can be done without any problem.But the problem is I can't find posts for specific catgory in and gets a error like Field 'id' expected a number but got 'health' but before I update field category charafield to forenkeyfied its work without any problem. here is my code my code class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) category = models.ForeignKey('blog.category', on_delete=models.SET_NULL, null=True, blank=True) class category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name views.py def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' '), 'category_posts':category_posts}) forms.py class PostForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name')) class Meta: model = Post fields = ('title', 'category','author', 'content', 'image','status') -
How to list all channel_name in a group?
I saw how to get the list of all channel_name in a group in channels 2 but I use channels 3 (3.0.4) Do you know how to get it? -
How to create some restrictions for users?
I want to split my application into modules. So each user will have permission to enter certain pages. There are pages such as; Add new user See user list User Performance Assigned customers ... on the menu. For example some users can see one of them and other users can see 2 of them etc.. Should I create an attribute as models.BooleanField for each one and if it is true, user can see otherwise cannot see. I have at least 10 function like this in my menu, I'm not sure it will be the most efficient way. How can I handle this problem? Is there a better way? -
How to edit output of elasticsearch shown in the rest framework and can we show the output in a custom page?
In the views file I have used Django DSL drf for filtering the data and I think this library shows the output in REST Framework This is my views.py from django.shortcuts import render from django.shortcuts import render from django.http import JsonResponse import requests import json from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from .documents import * from .serializers import * from django_elasticsearch_dsl_drf.filter_backends import (FilteringFilterBackend, OrderingFilterBackend, CompoundSearchFilterBackend) from .models import * def index(request): data_preperation() return JsonResponse({'status': 200}) class PublisherDocumentView(DocumentViewSet): document = Document serializer_class = NewsDocumentSerializer lookup_field = 'first_name' fielddata = True filter_backends = [ FilteringFilterBackend, OrderingFilterBackend, CompoundSearchFilterBackend ] search_fields = ( 'title', 'content', ) multi_match_search_fields = ( 'title', 'content', ) filter_fields = { 'title': 'title', 'content': 'content', } ordering_fields = { 'id': None, } ordering = ('id',) This is my documents.py from django_elasticsearch_dsl import (Document, fields, Index) from .models import ElasticDocuments PUBLISHER_INDEX = Index('elastic_demo') PUBLISHER_INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @PUBLISHER_INDEX.doc_type class Document(Document): id = fields.IntegerField(attr='id') fielddata = True title = fields.TextField( fields={ 'raw': { 'type': 'keyword', } } ) content = fields.TextField( fields={ 'raw': { 'type': 'keyword', } }, ) class Django(object): model = ElasticDocuments this URL is showing the output in REST Framework page path('search/', PublisherDocumentView.as_view({'get': 'list'})), My question is how I can change … -
JQuery: Select options not getting shortlisted based on radio button selection by using a passed Django variable
I want to provide the functionality to shortlist (reduce) the options inside select on the basis of the value of the radio button that is selected I am currently doing this using a PlugIn in JQuery that looks like this - jQuery.fn.filterOn = function (radio, values) { return this.each(function () { var select = this; var options = []; $(select).find('option').each(function () { options.push({ value: $(this).val(), text: $(this).text() }); }); $(select).data('options', options); $(radio).click(function () { var options = $(select).empty().data('options'); var haystack = values[$(this).attr('id')]; $.each(options, function (i) { var option = options[i]; if ($.inArray(option.value, haystack) !== -1) { $(select).append( $('<option>').text(option.text).val(option.value) ); } }); }); }); }; I used this plugin from here - https://stackoverflow.com/a/878331/11827709 You just pass a dictionary to this PlugIn and it shortlists the select options for you If I pass the dictionary hardcoded to this function like this - $(function () { $('#config').filterOn('input:radio[name=core]', { 'A': ['A1', 'A2', 'A3'], 'B': ['B1', 'B2', 'B3'], 'C': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'] }); }); The shortlisting works fine Like if I select 'A' in the radio button I can only see A1, A2, and A3 in the select menu But if I replace it with a variable that I pass from a … -
getting get method when running post method
I created class based view where In get method I am calling html page activate.html. and created post method where I posting some json data. I want to redirect same page and want to post data. When I am running activate.html page I get it but when I click on button for activate user Its printing same which I print in get method views.py class ActivationView(View): def get (self, request, uid, token): print('get called in activate_user') return render(request, 'activate.html') def post(self, request, uid, token): print('UID : ', uid) print('Token : ', token) payload = json.dumps({'uid': uid, 'token': token}) print("payload : " , payload) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() djoser_url = getattr(settings, 'DJOSER.ACTIVATION_URL') post_url = web_url + djoser_url print('post_url : ' + post_url) response = request.post(post_url, data = payload) return HttpResponse(response.text) I want to print uid and token in json format when I click on post button from html. activate.html <form action="" method="post"> {% csrf_token %} <td input type="submit"><a href="" target="_blank" >Click Here For Activate Account</a></td> </form> -
Daphne + Channel v3 Deployment, RuntimeError: no running event loop
When I run systemctl start daphne I get the following error Traceback (most recent call last): File "/srv/www/portal/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/srv/www/portal/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "/srv/www/portal/lib/python3.8/site-packages/daphne/cli.py", line 232, in run application = import_by_path(args.application) File "/srv/www/portal/lib/python3.8/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/www/portal/portal/./portal/asgi.py", line 3, in <module> from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter File "/srv/www/portal/lib/python3.8/site-packages/channels/routing.py", line 10, in <module> from channels.http import AsgiHandler File "/srv/www/portal/lib/python3.8/site-packages/channels/http.py", line 9, in <module> from asgiref.sync import async_to_sync, sync_to_async File "/srv/www/portal/lib/python3.8/site-packages/asgiref/sync.py", line 304, in <module> class SyncToAsync: File "/srv/www/portal/lib/python3.8/site-packages/asgiref/sync.py", line 328, in SyncToAsync loop = get_running_loop() RuntimeError: no running event loop The service definition: [Unit] Description=daphne service PartOf=postgresql.service After=postgresql.service [Service] WorkingDirectory=/srv/www/portal/portal/ Environment=JSON_SETTINGS=/srv/www/portal/settings.json Environment=ASGI_THREADS=10 ExecStart=/srv/www/portal/bin/daphne -b 0.0.0.0 -p 8000 portal.asgi:application Restart=always KillSignal=SIGTERM NotifyAccess=all [Install] WantedBy=multi-user.target This is my asgi.py import os import django from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter os.environ.setdefault("DJANGO_SETTINGS_MODULE", "portal.settings") django.setup() from … -
Randomizing logic in python
Need to write a program using Randomizing logic(Python). It can be like a generic function which takes versions and probability as input and returns a version. Probability can be anything like 1/2,1/3,1/4,1/5 and versions should be equally distributed accordingly -
How to use 2 different keys of facebook (Social Auth) in one django API project?
I have to implement two different keys for 2 apps using facebook login in one single project and the keys facebook social auth 2 library is using only one and the keywords are similar in settings file how do i use both keys as i am not able to override the keys because i cant find from where it is using those keys. -
django .update() a foreign key
im having problems updating a fk. Views.py estandares = EstandarProducto.objects.select_related('recinto','producto','proveedor').prefetch_related (Prefetch('carreras')).filter(recinto=id_recinto) for proveedor in estandares: if proveedor.proveedor_id == None or proveedor == "": EstandarProducto.objects.filter(id=proveedor.id).update(proveedor_id=1) x=EstandarProducto.objects.get(id=proveedor.id) print("ID proveedor : ", x.proveedor.id ) Models.py class EstandarProducto(models.Model): '''''' costo_unitario_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) cantidad = models.IntegerField(default=0) total_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) recinto = models.ForeignKey(Recinto, related_name='estandares_producto', on_delete=models.CASCADE) producto = models.ForeignKey( Producto, related_name='estandares_producto', on_delete=models.PROTECT) proveedor = models.ForeignKey( Proveedor, related_name='estandares_producto', on_delete=models.CASCADE, blank=True, null=True) carreras = models.ManyToManyField(Carrera, related_name="estandares_productos", blank=True) class Proveedor(models.Model): '''Datos de contacto de un proveedor de cotizaciones o de estandar.''' nombre = models.CharField(max_length=500) direccion = models.CharField(max_length=1000, blank=True, null=True) correo = models.EmailField(blank=True, null=True) telefono = models.CharField(max_length=12, blank=True, null=True) def __str__(self): return f"{self.nombre} - {self.direccion}" The problem is the print return 1 as expected, but when i look at the database there is no changes. -
How to redirect from one view to another view in django?
I have created app in django. There is login page and corresponding admin.py. I have another page default.html and controlled by index.py. my template directory myappname --- AdminUsers --- login.html --- Layouts default.html admin.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password # if password is correct return render(request,'Layouts/home.html',context={"User":user}) return render(request,'AdminUsers/login.html') def default(request,user): return render(request,'Layouts/default.html',context={"User":user}) my login page link is localhost/8000/adminusers/login and I want to redirect to localhost/8000 after login. By this method, I am able to load the default.html but my link is not changing. Is there other way to do this? -
Problems with running Python in Virtual environments after Python update
I used Python 3.7 for many Django projects using virtual environments (venv) under Windows. The Python path was C:\Program Files\Python37\python.exe now I upgrated python to 3.9 and the current path is C:\Program Files\Python39\python.exe Now when I want to run Python in any of my past projects, for example python manage.py runserver I get the error No Python at 'C:\Program Files\Python37\python.exe' Which is quite normal. How could I update each project in order to accept the new path? Is there a way to do this or should I better downgrade to Python 3.7 and use it forever? Renaming the folder where Python is installed doesn't seem a good idea. It must surely be a configuration file to change, a variable to set or whatever. I'm relatively new with Python and I never faced this problem before. Could you help? -
Too many SQL queries with Django Admin many-to-many inline view
I have a 'diamond' relationship between four models. AlignedScan is basically a pay-load carrying model facilitating a many-to-many relationship between Scan and Alignment. Both Scan and Alignment have a to-one relationship to Scan Project. When trying to display a inline-list of AlignedScans in an Alignment detail window (in Django Admin), it works but is very slow due to two extra SQL queries being executed for each record. What am I doing wrong? These are my models: from django.contrib.gis.db import models from django.db.models import Count, Q class ScanProject_Manager(models.Manager): def get_queryset(self): return (super().get_queryset() .annotate(number_of_alignments=Count('alignments', distinct=True)) .annotate(number_of_usedscans=Count('scans', distinct=True, filter=Q(scans__used=True))) ) class ScanProject(models.Model): objects = ScanProject_Manager() slug = models.CharField(max_length=30,primary_key=True,) label = models.CharField(max_length=100,) #... class Scan(models.Model): name = models.CharField(max_length=24,) #... scanproject = models.ForeignKey( ScanProject, related_name='scans', on_delete=models.CASCADE, ) class Alignment(models.Model): aligned_when = models.CharField(max_length=13,) #... scanproject = models.ForeignKey( ScanProject, related_name='alignments', on_delete=models.CASCADE, ) class AlignedScan(models.Model): registered = models.BooleanField() x = models.FloatField(blank=True, null=True,) y = models.FloatField(blank=True, null=True,) z = models.FloatField(blank=True, null=True,) #... alignment = models.ForeignKey( Alignment, related_name='alignedscans', on_delete=models.CASCADE, \ ) scan = models.ForeignKey( Scan, related_name='alignedscans', on_delete=models.CASCADE, ) class AlignedScan_Manager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('scan') I've tried with and without the AlignedScan_Manager, I've tried using a plain-vanilla straight out of the box InlineModel: class AlignedScan_Inline(admin.TabularInline): model = AlignedScan and i've tried … -
Why my table value is not showing up in django template?
I retrieve my table in views and when i tried to use it in template is is not showing anything. This is my views file def index(request): attendances = attendance.objects.all() return render(request, "salary/index.html", {'attendance': attendances}) and this is my template code {% for attendances in attendance %} <th>{{attedances.id}}</th> {% endfor %} and this is my model class attendance(models.Model): id = models.AutoField staff_id = models.CharField(max_length=250, null=True) attendance = models.CharField(max_length=250, null=True) date = models.CharField(max_length=250) -
Django - How to implement DetailView, CreateView, and Updateview together in one View?
TrimType's CreateView and UpdateView will be implemented together by modal in Car's DetailView. Car's DetailView TrimType's CreateView Modal TrimType's UpdateView Modal models.py : class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): id = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True) typeName = models.CharField(max_length=50, blank=False, null=False) urls.py : app_name = 'brand' urlpatterns = [ ... url(r'^car/(?P<car_id>\d+)/$', car_views.CarDetailView.as_view(), name='car_detail'), # TrimType_id is transmitted by GET method. ... ] forms.py : class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='TrimType' ) car_detail.html : <div class="col-8"> <div class="text-right mt-3 mb-3"> <select class="form-control" id="slct_trim_type"> <option value="0">*TrimType*</option> {% for trimType in trimType_list %} <option value="{{ trimType.id }}" data-car-idx="{{ car.id }}" {% if trimTypeID == trimType.id %}selected{% endif %}>{{ trimType.typeName }}</option> {% endfor %} </select> </div> </div> <div class="col-4"> <div class="text-right mt-3 mb-3"> <a id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="add"></a> <a id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="modify"></a> <a id="btn_trimtype_delete" class="btn btn-danger btn-icon waves-effect waves-themed" data-toggle="tooltip" title="" data-original-title="delete"></a> </div> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">*TrimType* UpdateView</h3> <form method="post" class="form-horizontal" … -
Django admin page is looking for a template that does not exist
I had made a template for one of my project apps (not the admin page) and then deleted it. Now the admin page is looking for that template and giving a "Missing template error". Is there some sort of caching or internal method that admin routes are stored that remembers old settings somehow? -
DRF Django: Serializer: HOw to get list of other properties in many to many relations
I have the following class Foo(models.Model): something = models.TextField() bars = models.ManyToMany("app.Bar") class Bar(models.Model): example = models.TextField() class BarSerializer(serializers.ModelSerializer): class Meta: model = Bar fields = ["example"] class FooSerializer(serializers.ModelSerializer): testing = BarSerializer(many=True,source=bars) class Meta: model = Foo fields = "__all__" { "something": "Testing", "children": [ { "example": "Something else" } { "example": "Something else2" } ], "bars":[ "Something else", "Something else2", ] } What I see is "children": [ { "example": "Something else" } { "example": "Something else2" } ], What i want is "children": [ "example": "Something else", "example": "Something else2" ], -
How to use Post-save Signal when uploading document, and saving before and after altering document?
I want save document when uploaded and run pandas script and save that script but also to forward to user do download it. How to do it simple way? This is how I tried to do it, upload and save upload works, but pandas script is not working. def my_view(request): message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') ooutput = data.eval('e = column1 / d') ooutput.to_excel(writer, sheet_name=name) output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') newdoc.to_excel(writer, index=False) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) def results(request): documents = Document.objects.all() context = {'documents': documents} return render(request, 'results.html', context) -
Systemd service logging gets stuck by Enabling django logging
I am using systemd service to run my django project, I have also configured logging in my project settings as below: # Logging settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '{levelname} - [{server_time}] : {message}', 'style': '{', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'mode': 'a+', 'maxBytes': 1024 ** 2 * 2, 'filename': f'{BASE_DIR}/logs/debug_{datetime.date.today().strftime("%Y-%m-%d")}.log', 'formatter': 'django.server', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'mail_admins'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server', 'file'], 'level': 'INFO', 'propagate': False, }, } } It works fine when its run manually. But a problem occurs when I run its systemd service with systemctl, It gets stuck and neither does the systemctl start myservice print anything nor does it stop running. It does start my service though. Also when I run journalctl -xefu myservice the same thing happens, it does not print anything, also does not stop running until I hit Ctrl+C. This … -
DRF updating data using AJAX call
When I try to send data via the frontend to the serializer I get a HTTP 400 error. If I do it directly via the DRF browsable API it works though: model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class Product(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializer: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["id", "name",] class ProductSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() def update(self, instance, request): product = Product.objects.get(serial = instance) product.shipment = Shipment.objects.get(id = request["shipment"]["id"]) product.save() return instance class Meta: model = Product fields = ["serial", "shipment",] lookup_field = "serial" read_only_fields = ["serial",] ViewSet: class ProductViewSet(ModelViewSet): serializer_class = ProductSerializer lookup_field = "serial" http_method_names = ["get", "patch", "put"] def get_queryset(self): return Product.objects.all() AJAX call: $.ajax({url: `api/products/${serial}/`, dataType: "json", contentType: "application/json", type: "PUT", data: {"shipment": shipment[0]}, headers: {"X-CSRFTOKEN": csrf_token }, success: function () {window.location = "?msg=ok";}, error: function () {window.location = "?msg=error";} }); Browser output: PUT http://127.0.0.1:8000/api/products/d39f281f/ Status400 Bad Request VersionHTTP/1.1 Transferred400 B (111 B size) Referrer Policysame-origin Request payload: shipment=4 Response: {"shipment":["This field is required."]} or after some playing: JSON parse error - Expecting value: line 1 column 1 … -
Filter Django-Function-View Queryset for User.Request
Models.py class Experience(models.Model): user = models.ForeignKey(User, null=True, on_delete = models.CASCADE) company_name = models.CharField(max_length=100) company_address = models.CharField(max_length=200) post_held = models.CharField(max_length=30) year_from = models.CharField(max_length=20) year_to = models.CharField(max_length=20) info = models.TextField() def get_absolute_url(self): return reverse('resume') def __str__ (self): return self.company_name Views.py def Resume(request): experience = Experience.objects.filter(user = request.user) return render(request, 'resume.html', {'experience': experience}) Template <ul> {% for an_experience in experience %} <a href="{% url 'edit_experience' an_experience.pk %}"><li ><h5>{{ an_experience }},</h5></a> {{ an_experience.company_address }} - {{ an_experience.post_held }}</li> <small>{{ an_experience.year_from }} - {{ an_experience.year_to }}</small> <div> {{ an_experience.info }} </div> {% endfor %} </ul> if I use .all(), it is working perfectly but while trying to filter it using request.user nothing is displaying in the template file.