Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot log in onto Django Admin Panel with a custom user
I created a custom user model shown below: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, username, password=None): user = self.model(username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password, **kwargs): user = self.create_user(username,password=password) user.is_admin = True user.save(using=self._db) return user class tgUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(primary_key=True, max_length=50) id = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) photo_url = models.CharField(max_length=200) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "username" def __str__(self): return f"{self.first_name} ({self.last_name})" In the settings.py, I specified: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) SITE_ID = 1 AUTH_USER_MODEL = "table.TgUser" ACCOUNT_EMAIL_REQUIRED = False # ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = "username" Yet the admin panel still displays "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." on login. How can I solve this? -
Python returning false on checking if a string exists in list even when it does
I imported a model(named Feature) and set it to a list in Django posts = Feature.objects.order_by('name') upon calling the 5th element print(posts[5]) this displays apple in shell which is the 5th object however on checking it with a if condition it returns false if 'apple' in posts: print("yes") else: print("no") and it prints no .. why is this happening even tho apple exists in the list -
Custom user model in Django - Create a stripe account (Django - Python)
When a user is created on django admin, I am trying to automatically create a user in Stripe. I do not understand why objects = CustomUserManager() is not being executed. Here is the model file class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(verbose_name=_("first name"), max_length=50) stripe_customer_id = models.CharField(max_length=120) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = CustomUserManager() def __str__(self): return self.name Here is the customUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password, name,**extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) customer = stripe.Customer.create( email=email, name=name, ) user = self.model(email=email,name=name, stripe_customer_id=customer.id ,**extra_fields) user.set_password(password) user.save() return user It seems like the create_user is not triggered when I create a user from the panel. If I comment out objects = CustomUserManager() I am still able to create users on the admin panel without any errors. -
syntax error when using search in Javascript
I'm making a forms in Django and JavaScript I need to display a form after clicking on a button, which will be answered and it will return (in JSON format) a list with the answers. My code index.js document.querySelector("#create-blank-form").addEventListener("click", () => { const csrf = Cookies.get('csrftoken'); fetch('/form/create', { method: "POST", headers: {'X-CSRFToken': csrf}, body: JSON.stringify({ title: "Untitled Form" }) }) .then(response => response.json()) .then(result => { window.location = `/form/${result.code}/edit` }) }) The error, the error points to .then(result...) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) (anonymous) My views.py def create_form(request): print('hi') # Creator must be authenticated # Create a blank form API if request.method == "POST": print('hi') data = json.loads(request.body) title = data["title"] code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30)) choices = Choices(choice = "Option 1") choices.save() question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False) question.save() question.choices.add(choices) question.save() form = Form(code = code, title = title, creator=request.user) form.save() form.questions.add(question) form.save() return JsonResponse({"message": "Sucess", "code": code}) My .html <div class="form-template-box"> <img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form"> <span class="form-template-label">Blank Form</span> </div> my urls.py path('form/create', views.create_form, name="create_form"), -
Is there any way to compare Toda date with another date in Django View?
I want to compare date between todays and another date. Is it possible to compare in django views.py. I have tried like this: current_date = date.today another date = request.POST.get("date1") # I am getting the another date from html input type date// if current_date>another_date: return something else: return something -
Postgresql: update returns boolean
I really don't understand why it returns 'false' in 99% cases and 'true' in 1%. I'm trying to convert this field into Foreign Key by this query: update public.cashflow_cashflow set level_2 = case when level_2 = 'Category1' then level_2 = '2' when level_2 = 'Category2' then level_2 = '2' when level_2 = 'Category3' then level_2 = '1' when level_2 = 'Category4' then level_2 = '2' when level_2 = 'Category5' then level_2 = '2' else level_2 = '' end; It returns table like this: enter image description here -
Deleting migration folder "No migrations to apply"
I have deleted migration folder because I have an issue which can't to solve. After that I try to migrate, but it wrotes me "No migrations to apply". So, I don't understand why it wrote me this message, when I don't migrate these files. -
How to filter Django Model instances based on a function defined inside the model?
I have a model for an item, it has a function that tells if the item is still on auction depending on an end date. class Catalogue(models.Model): name = models.CharField(max_length=256) owner = models.ForeignKey(User, on_delete=models.CASCADE) end_date = models.DateTimeField() def auction_status(self): now = timezone.now() return now < self.end_date In a class view i want to filter only those instances where the auction_status is true. Something along the lines of : class AuctionOverView(ListView): model = Catalogue template_name = 'administration/catalogue.html' def get_queryset(self): try: return Catalogue.objects.filter(auction_status=False) except: raise Http404() But i obviously can not filter based on a function definition. How to workaround this? -
How to add list of choices to form?
I am trying to create a list from which the user will be able to select a product category, but the form in which the list with categories to choose from is empty. Could someone explain me how this should work? models.py: class Category(models.Model): class Categorychoice(models.TextChoices): FOOD = 'FO', _('Food') TOYS = 'TO', _('Toys') FASHION = 'FA', _('Fashion') ELECTRONICS = 'EL', _('Electronics') HOME = 'HO', _('Home') category = models.CharField(max_length=2, choices=Categorychoice.choices) class Auctionmodel(models.Model): category = models.ManyToManyField(Category, related_name='Category') class Addauctionform(ModelForm): class Meta: model = Auctionmodel fields = '__all__' widgets = { "Category": RadioSelect() } auctiontemplate.html <form action="{% url 'createnewauction' %}" method='post'> {% csrf_token %} {{ createnewauctionhere.category }} <br> <input type="submit" value="Create"> </form> views.py def auctiontemplate(request): if request.method == "POST": addauctionform = Addauctionform(request.POST) if addauctionform.is_valid(): addauctionform.save() return HttpResponseRedirect(reverse("index")) else: return HttpResponseRedirect(reverse("auctiontemplate")) return render(request, "auctions/auctiontemplate.html", { "createnewauctionhere" : Addauctionform() }) -
uWSGI install fail in docker build
When I add uWSGI==2.0.19.1 into my requirements.txt, then run docker-compose build, it failed. Already searched for a while, seems there are no such familiar cases like this. Here are my files. Feel free to share your idea, tks. requirements.txt ... uWSGI==2.0.19.1 ... logs #8 20.69 Building wheel for tornado (setup.py): started #8 21.43 Building wheel for tornado (setup.py): finished with status 'done' #8 21.43 Created wheel for tornado: filename=tornado-6.1-cp310-cp310-linux_x86_64.whl size=421785 sha256=91e3761aa2ff9fb8e87ea1a0e2efad0e62db3fa2ddd419ceab9d01b3621db4cf #8 21.43 Stored in directory: /root/.cache/pip/wheels/80/32/8d/21cf0fa6ee4e083f6530e5b83dfdfa9489a3890d320803f4c7 #8 21.43 Building wheel for uWSGI (setup.py): started #8 24.36 Building wheel for uWSGI (setup.py): finished with status 'error' #8 24.37 error: subprocess-exited-with-error #8 24.37 #8 24.37 × python setup.py bdist_wheel did not run successfully. #8 24.37 │ exit code: 1 #8 24.37 ╰─> [88 lines of output] #8 24.37 /usr/local/lib/python3.10/distutils/dist.py:274: UserWarning: Unknown distribution option: 'descriptions' #8 24.37 warnings.warn(msg) #8 24.37 running bdist_wheel #8 24.37 running build #8 24.37 running build_py #8 24.37 creating build #8 24.37 creating build/lib #8 24.37 copying uwsgidecorators.py -> build/lib #8 24.37 warning: build_py: byte-compiling is disabled, skipping. #8 24.37 #8 24.37 installing to build/bdist.linux-x86_64/wheel #8 24.37 running install #8 24.37 using profile: buildconf/default.ini #8 24.37 detected include path: ['/usr/lib/gcc/x86_64-linux-gnu/10/include', '/usr/local/include', '/usr/include/x86_64-linux-gnu', '/usr/include'] #8 24.37 Patching "bin_name" to … -
Not able to add additional fields in django registration form
I am having a bit of a problem. I actually wanted to create a registration form for my website which I am building using Django, and I wanted some custom fields which don't exist in the inbuild UserCreationForm in Django and I am not able to find any other way to do it, atleast not on Youtube. Any one here know how to do it It would be a great help if any of you could help me with this I really really have to finish this website fast Here is my code:- models.py :- class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=200, null=True, blank=True) username = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) password = models.CharField(max_length=200,null=True, blank=True) confirm_password = models.CharField(max_length=200, null=True, blank=True) profile_photo = models.ImageField(null=True, blank=True, upload_to='profile_photo/', default='profile_photo/default.jpg') phone_number = models.CharField(max_length=10,null=True, blank=True) address = models.TextField(null=True, blank=True) pin_code = models.CharField(null=True, max_length=6, blank=True) region = models.CharField(null=True, max_length=200, blank=True) state = models.CharField(null=True, max_length=100, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) forms.py :- class RegisterForm(forms.ModelForm): class Meta: model = UserInfo exclude = ['user', 'created', 'id', 'profile_photo'] widgets = { 'full_name': forms.TextInput(attrs={'class':'register-textinput input'}), 'username': forms.TextInput(attrs={'class':'register-textinput1 input'}), 'email': forms.EmailInput(attrs={'class':'register-textinput2 input'}), 'phone_number': forms.TextInput(attrs={'class': 'register-textinput3 input'}), … -
Django Templates: How i can compare two strings in javascript
I want to compare two strings, one of the two strings is to be choosed by the user from a drop down list(using django-widget-tweaks) : this is the code field in my template: html <p >{{ form.category_column.label_tag }}</p> <p id="category_column_id">{% render_field form.category_column autocomplete="off" hx-get="/sizescolumn/" hx-target="#id_sizes_column" %}</p> code javascript: <script> var btn = document.getElementById("clickMe"); btn.addEventListener("click", alertMe); function alertMe(){ var select = document.getElementById('category_column_id').value; if(select === "Flate" ){ div.style.opacity = "1"; div.querySelector('p').innerText = 'You can not choose Flate category in column'; setTimeout(function(){ div.style.opacity = "0"; }, 6000); event.defaultPrevented(); }else { div.style.opacity = "0"; } } </script> ----->but this code it doesn't work , no message shown if the selected value is "Flate". any help please -
Accessing the attributes/elements of a form in Django
Hello so I've a form and I'm trying to make it so that when that form is validated. But before it is saved. It will create a new instance of a EC_Node and save the command given in the Command_Form not only to the Command_Node but to the EC_Nodes. Which should have a manytoone relationship with the Command_Nodes and which should record all commands send to a command_node. But this will only work if when entering a command for the Command_Node I also capture that in a EC_Node. Which I don't know how to do exactly although I'm some ideas. So any advice would be greatly appreciated. Relevant Code follows. Relevant views.py def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form['host_id'] command_form.EC_Node_set.all() # <- not sure with all _ and Maj here form.save() return redirect('home') return render (request, 'update.html', {'host_id':host_id,'form':form}) forms.py class Command_Form(ModelForm): class Meta: model = Command_Node fields = ('host_id','current_commands') host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) def save(self, **kwargs): EC_Node.objects.create( command=self.cleaned_data["current_commands"], Command_node=self.instance ) return super().save(**kwargs) models.py class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) … -
my code is not working in updating record in django
I am making a employee management system in django. i have created all the fields create, read, delete and filter but I am unable to write update field.please someone help me.. This is my views.py file def update_emp(request,emp_id=0): context={} obj= get_object_or_404(Employee, id=emp_id) # obj=Employee.objects.get(id=emp_id) form = employeeForm(request.POST or None, instance = obj) if form.is_valid(): form.save() return HttpResponseRedirect('/'+id) context['form'] = form return render(request, 'update_emp.html' ,context) This is my urls.py file from django.urls import path , include from . import views urlpatterns = [ path('', views.index, name = 'index'), path('all_emp', views.all_emp, name = 'all_emp'), path('add_emp', views.add_emp, name = 'add_emp'), path('remove_emp', views.remove_emp, name = 'remove_emp'), path('remove_emp/<int:emp_id>', views.remove_emp, name = 'remove_emp'), path('filter_emp', views.filter_emp, name = 'filter_emp'), # path('update_emp', views.update_emp, name = 'update_emp'), path('update_emp/<int:id>', views.update_emp, name='update_emp'), ] This is my update_emp.html file <div class="main"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> This is my forms.py file from django import forms class employeeForm(forms.Form): fname=forms.CharField(label="Value1",required=False,widget=forms.TextInput(attrs={'class':'form-control'})) lname=forms.CharField(label="Value2",required=True,widget=forms.TextInput(attrs={'class':'form-control'})) -
TypeError: answer() missing 2 required positional arguments: 'Poll' and 'Answers' - django
I want to specify one of the table fields using serializers, but I get the following error Error : TypeError: answer() missing 2 required positional arguments: 'Poll' and 'Answers' code : serializers.py from rest_framework import serializers from .models import Answers, Poll ,Options from authUser.models import User class pollSerializer(serializers.ModelSerializer): class Meta: model = Poll fields = ["pollAnswer" ] pollAnswer = serializers.SerializerMethodField(method_name="answer") def answer(self , Options :Options , Poll:Poll , Answers :Answers ): poll = Poll.objects.get(pk=Poll.pk) polltype = poll["pollType"] if polltype == 0 : return Poll.pollAnswer if polltype == 1: options = Options.objects.filter(pollId=Poll.pk) big = 0 oid = 0 for i in options: if big < Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count(): big = Answers.objects.filter(pollId=Poll.pk ,optionId=i.pk).count() oid = i.pk return oid -
How to integrate Bokeh Server into Django
Currently I have a Bokeh server running. I can access it and when I push some buttons then Python code runs in the background and finally a figure is plot. Now I need to add some things: I want users to authenticate. Users should be able to save results to a database. Some general data (costs, the same for everybody) should also be obtained from a database. User sessions should be stored. In the end multiple apps will be made available to users. Not all users will have access to all apps. Authentication should solve this. So I think I should integrate the Bokeh server into Django using server_document(). However, I am not able to find a minimal working example. It would be nice if that example includes the topics from my list. -
Django Channels Rest Framework V3 @model_observer message is None
I tried to find anything in the documentation of model observer which could explain under which conditions the model observer is called with message = None, but there was nothing particularly hinting into the right direction. From what I unterstand from the example: class MyConsumer(GenericAsyncAPIConsumer): queryset = User.objects.all() serializer_class = UserSerializer @model_observer(Comments) async def comment_activity( self, message: CommentSerializer, observer=None, subscribing_request_ids=[] **kwargs ): await self.send_json(message.data) @comment_activity.serializer def comment_activity(self, instance: Comment, action, **kwargs) -> CommentSerializer: '''This will return the comment serializer''' return CommentSerializer(instance) @action() async def subscribe_to_comment_activity(self, request_id, **kwargs): await self.comment_activity.subscribe(request_id=request_id) The message should be the output of the CommentSerializer so the only way a message to become null is, if the serializer would return nothing ?! To check if this is the case I added logs prints which sadly indicate that the serializer is receiving data and thous there is no reason the message could be None. Its also occurring only from time to time so any advice about misunderstanding of how the observer works internally will be highly appreciated. In our implementation: class StorageConsumer(ListModelMixin, AsyncAPIConsumer): """ Async API endpoint that allows Storage updates to be pushed. """ async def accept(self, **kwargs): await super().accept() await self.model_change_bess.subscribe() @model_observer(Bess) async def model_change_bess(self, message, … -
Filter data via ajax and django
Hello By sending the value received from the dropdown and sending it to the server via ajax, I filtered my data and sent the result to the template. However, I can see the result through the web developer tools in the response tab, but the result is not visible on the web page. What is the reason? -
how to exit from the loop in python
I'm looping all the rows and I want to return it but even after looping all the rows and even data is saving in the database but its not getting exit from it due to which I'm getting an error as 'str' object has no attribute 'get'. I don't know where I'm going wrong This what I tried Views.py: @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': cursor = connection.cursor() if request.data: for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') Agents = ran.get('Agents') Comments = ran.get('Comments') Supervisor = ran.get('Supervisor') sid = 0 print('sid--', sid) qid = ran.get('QId') print('qid---', qid) answer = ran.get('Answer') cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s', (auditorid,ticketid,qid,answer, sid)) result_st = cursor.fetchall() print('sp_SaveAuditResponse', result_st) for row in result_st: print('sp_SaveAuditResponse', row) return Response(row[0]) print('after after') return Response(0) Here, is the payload: [{"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":42,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":43,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":44,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":45,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":46,"Answer":"3","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":47,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":48,"Answer":"5","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":49,"Answer":"2","SID":"0","Comments":""}, {"AuditorId":130,"Agents":"","Supervisor":"","TicketId":"325423432","QId":50,"Answer":"5","SID":"0","Comments":""}] -
How to have dedicated instances for celery containers when deploying django project using docker-compose on elastic beanstalk?
I have a web-app that uses celery for heavy calculations. It was deployed on AWS with elastic beanstalk, using docker-compose. The broker is Amazon SQS, while redis is used as result backend. Here is the docker-compose file to understand the structure: version: '3.8' volumes: data: driver_opts: type: "nfs" o: "addr=XXXXXXXXXXXXXXXXXXXXXXX,rw,nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport" device: ":/" static: services: web: build: ./web command: > bash -c "python3 manage.py migrate && python3 manage.py collectstatic --noinput && gunicorn APPNAME.asgi:application --access-logfile '-' --error-logfile '-' --capture-output --enable-stdio-inheritance -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000" volumes: - data:/home/webserver/data/ - static:/home/webserver/static/ ports: - "8000:8000" depends_on: - redis celery: build: ./web command: celery -A APPNAME worker -Ofair -l INFO volumes: - data:/home/webserver/data/ depends_on: - web redis: image: redis:6.2.6-alpine ports: - "6379:6379" nginx: build : ./nginx ports: - "80:80" depends_on: - web volumes: - static:/home/webserver/static/ It works well, including the celery tasks. Now, I would like to separate the web/redis/nginx services from the celery containers that would have their own dedicated instances, with the ability to scale. Is there a proper way to do that (using CLI)? Should I consider separate beanstalk applications? -
Why can't I see Loading... while scrolling?
Based on this tutorial This is my views: def All( request ): p=product.objects.all().order_by('id') pa=Paginator(p,20) page=request.GET.get('page') pro=pa.get_page(page) return render(request,'home.html',{'pro':pro}) This is my template: <div class="grid"> {%for p in pro%} <div class='card'> <img src="{{p.image}}"></img> <p id="id">{{p.description}}</p> <a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'> <button ><span class="price"> ${{p.price}}</span> buy</button> </a> </div> {%endfor%} {% if pro.has_next %} <a class='more-link' href="?page={{pro.next_page_number}}">Next</a> {% endif %} <div class="loading" style="display: none;"> Loading... </div> <script> var infinite = new Waypoint.Infinite({ element: $('.grid')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> </div> I have downloaded dependencies correctly and I included some links in my html to use them, but currently I can not find what is wrong with my code. Why can't I see Loading... while scrolling? -
How Can I Add Country Flags to Django Phonenumber Widget
I have used django-phonenumber-field in my project with Babel which is working fine with drop down of all countries with their international dialing code. My problem is that I want each country flag attached to their names so that the phonenumber field will be smaller. Attached is the what I presently have. This is exactly what I want to achieve with django-phonenumber-field. And you can observe that my phone number fields are two; one has the international code and the other field is where the phone number is to be entered whereas I want all in one field with Countries Flags. Anticipating your prompt answer, thanks. -
Products are not deleted from cart
Firstly my code had an error then I ask about it in StackOverflow. Then someone helped me to fix this error. Here is the link: get() returned more than one OrderProduct -- it returned 3 [First error][1] But I have a new problem now. Products are not deleted from the cart when someone ordered them. I do not know why this happened. But before the first fix, products were deleted from the cart successfully. Now the first bug is fixed but I am faced with the second bug. Please help me, products are not deleted from the cart. I have already put a link to my first bug. This is my views.py after fixing the first bug: def process_order(request): transaction_id = datetime.now().timestamp() data = request.POST name = data['name'] email = data['email'] phone = data['phone'] address = data['address'] city = data['city'] state = data['state'] zipcode = data['zipcode'] if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) shipping_info = ShippingAddress.objects.create( customer=customer, order=order, address=address, city=city, state=state, zipcode=zipcode ) order_data = cart_data(request) cart_total_price = order_data['order'].cart_total_price cart_products_quantity = order_data['order'].cart_products_quantity products = order_data['products'] product_list = '' for item in products: product_list += f'{item.product.name}: {item.quantity} шт. {item.total_price}\n\n' else: customer, created = Customer.objects.get_or_create( name=name, email=email, phone=phone ) … -
django file field not saving file to s3 bucket folder when updating
I am uploading file to s3 bucket in the below path: bucket/folder/{custom_id}/file I have the below method which I am calling in Model. In DRF Post method, the file is getting saved correctly to s3 and I am able to retrieve the path in GET. But when I try to upload new files in PUT method, the filename is getting saved in db, but the file is not saving in s3 bucket. custom upload path def upload_path_handler(instance, filename): return f'{FILES_FOLDER}/{id}/{filename}' In Models.py cc_file = models.FileField( db_column='CCFilename', blank=True, null=True, upload_to=upload_path_handler ) This method is working in POST API call of DRF. How do I save new file to s3 if the file is getting changed on update of the field. -
Is the location or scope important in a web push service worker?
I have a Django web app that contains a service worker designed for handling push notifications. Everything is working beautifully. In the many articles, tutorials and documentation it is written that the location and scope of service workers is important and to make sure to put it at the root of the domain. See for example this article, that states: Service worker file must registered at the root directory of your website. And: I’ve spend 15 hours to learn that fact. You guys are lucky ! So when I first created my service worker in Django, I had to make sure to set the scope correctly. I created a View that served the JS code of the service worker as a template, just so that I could set the Service-Worker-Allowed header: class ServiceWorkerView(TemplateView): template_name = 'web_push/web_push_service_worker.js' def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) response.headers['Content-Type'] = 'application/javascript' response.headers['Service-Worker-Allowed'] = '/' return response That template contained the push handling code: self.addEventListener('push', function(event) { ... self.registration.showNotification(...) ... }) As mentioned: this works fine. But now I wonder: why does the scope matter? I just changed things around and moved the code of the service worker to a standard location inside …