Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the Django template file not updating value from the context?
(I am a beginner in Django) I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it Here is my views.py code - from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # return HttpResponse('<h1>Hey, welcome</h1>') # we can dynamically send data to our index.html file as follows - context={ 'u_name': 'Ankit', 'u_age': 25, 'u_nationality': 'Indian', } return render(request,'index.html',context) Here is my template index.html - <h1> How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}} </h1> settings.py has been correctly set as well - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], Here is my output - does not take the values from the context Would be glad if someone could point out what error I am making. Thanks in advance -
How to retrieve data from html form and pass it into my database as an sql query in django
i am trying to make use of django to retrieve data from my sign up form and pass it into my database in pgadmin 4 as a query. I got error and doesnt know how to go about doing it. This is my code which i tried to use pymysql. Thanks in advance def booknow(request): c = pymysql.connect(host='localhost', user='postgres', password='pw', db='users') cur = c.cursor() if request.method == 'POST': display_name = request.POST.get['your-name'] email = request.POST.get['your-email'] age = request.POST.get['your-age'] phone_number = request.POST.get['phone-number'] gender = request.POST.get['your-gender'] vaccination_status = request.POST.get['your-vaccination'] password = request.POST.get['your-password'] insert_query = "INSERT INTO users (display_name, email, age, phone_number, gender, vaccination_status, password) VALUES ('%s','%s','%s','%s','%s','%s','%s');" % (display_name,email,age,phone_number,gender,vaccination_status,password) c = connection.cursor() c.execute(insert_query) return render(request, 'booknow.html') -
Reverse for 'temp1' with arguments '('',)' not found. 1 pattern(s) tried: ['userinput/(?P<id>[0-9]+)/\\Z']
I just want to retrieve data dynamically. urls.py I think there is something error in views.py or urls.py from django.urls import path from . import views urlpatterns = [ path("", views.home, name='home'), path("userinput/", views.template, name='template'), path("userinput/<int:id>/", views.temp1, name='temp1'), ] views.py from django.shortcuts import render, HttpResponseRedirect from home.models import UserDetail # Create your views here. def template(request): if request.method == 'POST': nm = request.POST['name'] eml = request.POST['email'] adrs = request.POST['address'] data = UserDetail(name=nm, email=eml, address=adrs) data.save() return render(request, 'template.html') def temp1(request, id): userdetail = UserDetail.objects.get(pk=id) return render(request, 'temp1.html', {'userdetail':userdetail}) template.html I think my error is related to views.py or in template.html file {% load static %} {% block css_files %} <link rel="stylesheet" href="{% static '' %}"> {% endblock %} {% block content %} <form id="resume-form" action="" method="POST"> {% csrf_token %} <h1>Enter your details</h1> <div class="generate"> <div class="per"> <h2>Personal details</h2> <div class="a"> <label for="namefields">Your Name</label><br> <input type="text" class="" id="namefields" placeholder="Enter here" name="name"> </div> <div class="a"> <label for="emailfield">Your Email</label><br> <input type="email" class="" id="emailfield" placeholder="Enter here" name="email"> </div> <div class="a"> <label for="addressfield">Your Address</label><br> <textarea id="addressfield" placeholder="Enter here" rows="3" cols="" name="address"></textarea> </div> <div class="generatebtn"> <a href="{% url 'temp1' userdetail.id %}"><button type="Submit">Submit</button></a> </div> </form> {% endblock %} can anyone say why it shows "NoReverseMatch at /userinput/" … -
Does select_for_update() work if AUTOCOMMIT is set to False in Django Rest-Framework
I am writing a celery task which would get invoked if a row is being inserted into a table. This task is being executed in a transaction and the task also locks the certain rows of several tables. Now lets assume this task is being executed when AUTOCOMMIT & ATOMIC_REQUESTS is enabled. This is how it looks like - @app.task @transaction.atomic def celery_task(a, b): result = Orders.objects.filter(filed = "Value") # here the result might have 10 of records but I just need few of them based on a very # specific business logic. # so I pick those which are required and should be locked. rows_to_lock = [result[0], result[1]] # has only ids of the rows in this list # Now to put on the records which are in - rows_to_lock result = Orders.objects.select_for_update().filter(id__in=rows_to_lock) ... ... Now when this celery task is being invoked twice with two different arguments and at the same time and if the resultant rows of orders are exactly same then I have noticed that the locks to update the records aren't working. Does the decorator @transaction.atomic works with the current database configurations that I have? Will I be able to solve the issue if I … -
Django - How to go back to previous url
I have multiple todo lists on different pages in an app written in python. I dont want to use delete and update functions over and over again. I want to use one for all pages. In update and delete functions, I can redirect to a certain page after code execution. But its not dynamic. How can I make it dynamic? def updateTodo(request, pk): task = Todo.objects.get(id=pk) form = FormTodo(instance=task) if request.method == 'POST': form = FormTodo(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/page_path') context = {'form':form} return render(request, 'update_task.html', context) What should I write instead of page_path so that it redirects to the page it comes from? I thought going back to the latest page would be an option but guess what? I couldnt do it either. Also, would going back create an error or something? since I'm updating an entry. Any suggestions ? (I saw some options with selenium but it seems to work for chrome or selected browsers only. I'd like to avoid using selenium if there is another way) -
Prevent overwriting existing objects when applying fixture
I have a model representing my application's settings. The settings I define in a fixture. Now, everytime I redeploy the app I also apply the fixture with ./manage.py loaddata settings. The problem I noticed now is that everytime I do this already changed settings get reset as well, it's appearantly deleting the dataset and creating it new. Is there a way to avoid this? settings.yaml: ## Einstellungen - model: preferences.settings pk: agent_name fields: name: Agenten-Name description: Name, welcher dem Kunden im Chat angezeigt wird default: Agent public: true type: text category: 2 - model: preferences.settings pk: greeting fields: name: Begrüßungstext description: Begrüßungstext der dem Kunden angezeigt wird wenn ein Agent Online ist default: Hallo, wie können wir Ihnen helfen? public: true type: textarea category: 2 -
covert txt file into json python django
i have this file of weather data i'm trying to send it through API: view.py: @api_view(['get']) def weatherDataList(request,region,parameter): try: url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/'+parameter+'/date/'+region+'.txt' print(url,"this is url") r=requests.get(url) data = r.text new_data = data[274:] a=json.loads(new_data) return Response({"message":"Data List","status":True,"data":a},status=status.HTTP_200_OK) except Exception as e: print(e) return Response({"message":str(e),"status":False,"data":{}},status=status.HTTP_400_BAD_REQUEST) i'm not able to format and output the data. what should be the better way to achieve this. output the whole data as json. -
Django putting logic in view vs serializer vs model best approach
What is the best approach about putting logic and what is best in my current scenario where I have a view which uses a query + subquery to fetch and return data. @action(detail=False, methods=["get"], url_name="inventory") def inventory( self, request: Request, *args: None, **kwargs: None ) -> Response: required = ( ProductionJob.objects.filter(item=OuterRef("pk")) .order_by() .filter(status="Pending") .annotate( amount_sum=Sum( "required_item", output_field=FloatField() ) ) .values("amount_sum") ) data = ( Item.objects.select_related("supplier") .prefetch_related("item_jobs") .annotate( item_required=Coalesce( Subquery(required), 0, output_field=FloatField(), ) ) .values( "id", "article_id", "composition", "width_meter", required_for_jobs=Sum("item_required"), supplier_name=F("supplier__name"), ) ) return Response(data=data, status=HTTP_200_OK) The question is what is the best place to keep this code. It can be put on a model's QuerySet or if it should be moved to serializer then how? Thank you. -
Filtering duplicate model elements in django templates
It was necessary to weed out duplicate model elements on django. Removing identical elements is not suitable for me, but only filtering is suitable. My model includes albums and photos that are in those albums. If I send objects.all() to my template in views.py and try to display only my albums without repetition, then the album name is displayed in the template as many times as there are images in it. Is it possible to somehow check for a non-repeating output of my albums. PS: I am using sql database so objects.all().distinct('albom') doesn't seem to work for me... My views.py (I want to filter the proverka function): from django.shortcuts import render, redirect from .models import Image, Albom def proverka(request): if not request.user.is_authenticated(): return redirect("/accounts/login/") else: albom = Image.objects.all() return render(request, 'Фото/Альбом.html', {'albom': albom}) def gallery_view(request, pk): if not request.user.is_authenticated(): return redirect("/accounts/login/") else: albom = Albom.objects.get(id=pk) return render(request, 'Фото/Фото.html', {'albom': albom}) My urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.proverka, name="albomm"), url(r'^Альбом/(?P<pk>\d+)', views.gallery_view, name="foto"), ] My models.py: from django.db import models class Albom(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name def upload_gallery_image(instance, filename): return f"images/{instance.albom.name}/gallery/{filename}" class Image(models.Model): image = models.ImageField(upload_to=upload_gallery_image) albom = models.ForeignKey(Albom, on_delete=models.CASCADE, related_name="images") … -
How to override .py files in third party INSTALLED_APPS, django
I'm using https://github.com/jazzband/django-two-factor-auth I want to edit the file core.py in folder https://github.com/jazzband/django-two-factor-auth/tree/master/two_factor/views Where can I put core.py in my project to override and edit it? For example I edited the templates by placing them in: /home/johndoe/projects/example_project/example_project/templates/two_factor/core/setup.html How can I do the same for core.py? My project structure is: ├── example_project └──example_project └──users └──views.py └──models.py └──apps.py └──... └──blog └──views.py └──models.py └──apps.py └──... └──settings.py └──urls.py └──wsgi.py └──manage.py └──static └──templates └──users └──blog └──two-factor └──core └──setup.html I want to edit it to check if the user's email is verified before they enable 2FA. -
i need to send in response array of chats in my my chat view from chat model
Following are my models: class MediaUploads(models.Model): file = models.FileField(upload_to='embla/uploads/') caption = models.CharField(max_length=256, null=True, blank=True) owner = models.ForeignKey(User, related_name='embla_uploads', on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Profile(models.Model): ...other unlreated keys, photo = models.ForeignKey(MediaUploads,on_delete=models.DO_NOTHING,related_name='profile_photos', null=True, blank=True) name = models.CharField(max_length=256) ...other unrelated keys, class Message(models.Model): sender = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="receiver") message = models.CharField(max_length=999) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) Following is my view: class ChatView(APIView): searilzer_class = MessageSearlizer def get(self, request, *args, **kwargs): user_id = self.request.user.profile.pk # i need this chats here # On client side i need to show the list of chats along with the names and pictures # of the people the user is engaged in chat. i have attached the picture of the #[[client side view of chat][1]][1] client side view chats = return Response({"chats": chats}) I am Nodejs developer and due to insistence of client, doing my first project on django. chat would be array of objects. This array will have 3 keys. receiver name, receiver photo and receiver last message. I apologise in advance for my noobness in python. please dont downvote this. -
How to store nav menu urls in database?
I'm working on my first django app, and i have side nav menu like in twitter. To prevent the dozens of lines in my template like this <ul class="nav d-flex flex-column"> <li class="nav-item align-self-start rounded-pill mb-3"><li> <li class="nav-item align-self-start rounded-pill mb-3"><li> ... <li class="nav-item align-self-start rounded-pill mb-3"><li> </ul> and for app extensibility i want to store nav menu in database to be able to loop over the menu items <ul class="nav d-flex flex-column"> {% for item in menu %} <li class="nav-item align-self-start rounded-pill mb-3"><li> {% endfor %} </ul> But the problem is that i can't store direct urls for menu items in database, because several of them have dynamic urls e.g. profile page, which has 'slug:username/' pattern. I've tried to store template tags in database like {% url 'app_name:view_name' %} but of course it doesn't work. My current idea is to store in database namespaced url e.g. 'app_name:view_name' for static urls and 'request.user.get_absolute_url()' for pages which have username in urls. The next step is to get QuerySet with menu items from database, loop over them and transform namespaces url with reverse (it works), but 'request.user.get_absolute_url()' is just a string and it doesn't work. Then make list of ditcs and pass … -
http API requests are executed for more than 20 seconds
I have an application on django that can search for YouTube videos via the YouTube Data API v3 and translate their description using the Yandex Translate API. Often everything works fine, both services respond normally. But about once every 10 calls, the request stretches for about 20 seconds. This happens with both translation and YouTube. I look in the developer console, in the column "Waiting (Time to receive the first byte)" just these 20 seconds. I do not understand why this is so, it is unlikely that the problem is on the side of the services, because it is observed on both. But I can't figure out what my problem is then... I tried to set DEBUG to False, it was advised somewhere. But the problem has not gone away. Code of functions for receiving data from YouTube: from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os import pickle SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"] def auth(): os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" credentials_filename = "credentials.json" credentials = None if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: credentials = pickle.load(token) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = … -
How to upload random pictures from a folder to database
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') random_logo = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = … -
Django Rest Framework Simple JWT getting anonymous user
I want to use Rest Framework simpleJWT as authentication earlier I was using Django default authentication. Here are views currently I am getting AnonymousUser error, what changes do I need to get a user request from JWT Authenticated user. I want to get a request.user from a jWT Authenticated user. Please help me out. class MessagesModelList(ListView): http_method_names = ['get', ] paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500) def get_queryset(self): if self.kwargs.get('dialog_with'): qs = MessageModel.objects \ .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) | Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \ .select_related('sender', 'recipient') else: qs = MessageModel.objects.filter(Q(recipient=self.request.user) | Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file') return qs.order_by('-created') def render_to_response(self, context, **response_kwargs): user_pk = self.request.user.pk data = [serialize_message_model(i, user_pk) for i in context['object_list']] page: Page = context.pop('page_obj') paginator: Paginator = context.pop('paginator') return_data = { 'page': page.number, 'pages': paginator.num_pages, 'data': data } return JsonResponse(return_data, **response_kwargs) class DialogsModelList(ListView): http_method_names = ['get', ] paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20) def get_queryset(self): qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \ .select_related('user1', 'user2') return qs.order_by('-created') def render_to_response(self, context, **response_kwargs): # TODO: add online status user_pk = self.request.user.pk data = [serialize_dialog_model(i, user_pk) for i in context['object_list']] page: Page = context.pop('page_obj') paginator: Paginator = context.pop('paginator') return_data = { 'page': page.number, 'pages': paginator.num_pages, 'data': data } return JsonResponse(return_data, **response_kwargs) class SelfInfoView(DetailView): def get_object(self, queryset=None): return self.request.user def render_to_response(self, … -
The view Project.views.index didn't return an HttpResponse object. It returned None instead
So I have encountered this problem while this is my views.py code Create your views here. # Create your views here. def index(request): if request.method == 'POST': feature1 = Feature.objects.all() Appnt = Appointment.objects.all() Appnt.name = request.POST['name'] Appnt.email = request.POST['email'] Appnt.phone = request.POST['phone'] Appnt.Adate = request.POST['date'] Appnt.Dept = request.POST['department'] Appnt.Doc = request.POST['doctor'] Appnt.message = request.POST['message'] return render(request, 'index.html', {'feature1' : feature1}, {'Appointment' : Appnt} ) I have tried many ways but still it keep saying that error -
Django template nested include passing variables
I use django template index.html to render the frontpage. It includes another template to create a link icon. This template url_icon.html includes another template icon.html. When passing the arguments down the way, I face with an error. How to fix it? index.html . . . {% include "url_icon.html" with name="return" url="/" %} . . . url_icon.html <a href="{{url}}">{% include "icon.html" with icon={{ name }} %}</a> icon.html <img src="/static/images/{{ name }}.png" /> Causing an error: Could not parse the remainder: '{{' from '{{' -
Is there something I am doing wrong with my Content Aggregator Website?
I followed an online tutorial, but was able to scrape different websites. I cannot get the article headlines to show up. I am not sure if it is a problem with my return function or my HTML file. This is how the website comes out -
Displaying fields based on user's preference
I would like to know if there's a cleaner, easier, more practical way of implementing below scenario. Currently I let users choose to either have required(red), optional(red) or hidden(black) fields(pre-defined) in the webapp. I store user's preferences in db such as [input_field : user_choice]. Since bootstrap allows 12 columns in a single row, , I was thinking if by adding additional fields [order, size] I could allocate required and optional fields in a proper order. Size can range from 1-12 and order can have duplicate values. {'field_name': 'somename1', 'user_choice': 'Required', 'order': 1, 'size': 6}, {'field_name': 'somename2', 'user_choice': 'Optional', 'order': 2, 'size': 6}, {'field_name': 'somename3', 'user_choice': 'Required', 'order': 3, 'size': 12}, {'field_name': 'somename4', 'user_choice': 'Required', 'order': 4, 'size': 6}, {'field_name': 'somename5', 'user_choice': 'Hidden', 'order': 4, 'size': 6}, {'field_name': 'somename6', 'user_choice': 'Hidden', 'order': 5, 'size': 6}, {'field_name': 'somename7', 'user_choice': 'Required', 'order': 6, 'size': 6}, {'field_name': 'somename8', 'user_choice': 'Hidden', 'order': 7, 'size': 6}, {'field_name': 'somename9', 'user_choice': 'Hidden', 'order': 8, 'size': 3}, {'field_name': 'somename10', 'user_choice': 'Hidden', 'order': 9, 'size': 3}, {'field_name': 'somename11', 'user_choice': 'Optional', 'order': 10, 'size': 12} Based on that I would filter to get only objects that have value of Required and Optional and loop in such way that would allow to … -
Get ManytoMany Objects in Django
I am trying to solve an issue. Like I have two model service and package. package has relation with service in many to many. I want to get the service's name which are not having any many to many relation with the package table. How to do this? I have tried multiple apporch. #models.py class Service(models.Model): name = models.CharField(max_length=1000) price = models.IntegerField(null=True, blank=True, default=0) details = models.TextField(max_length=20000, blank=True, null=True) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Package(models.Model): service = models.ManyToManyField(Service, blank=True) name = models.CharField(max_length=220) price = models.IntegerField(null=True, blank=True, default=0) details = models.TextField(max_length=20000, blank=True, null=True) status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) #views.py children_id_list = [2, 1, 4] temp = [] for i in children_id_list: try: s = Service.objects.get(id=i) t = s.package_set.all() if len(t) == 0: children_id_list.remove(i) temp.append(i) except ObjectDoesNotExist: print(f'Sorry! There is no Service List with this ID {i}') print(children_id_list) print(temp) print(f"\n") package = Package.objects.filter(service__in=children_id_list).annotate(num_cats=Count('service')).filter(num_cats=len(children_id_list)).exclude(service__in=Service.objects.exclude(id__in=children_id_list)) for i in package: print(f"Hello, Package Name {i.name} and Price {i.price} BDT") if len(temp) > 0: c = Service.objects.get(id=temp[0]) print(f"Addon for new service {c.price} BDT") u = i.price + c.price print(f"Total Checkout {u} BDT") print(f"\n") else: print('None') -
Django rest framework clears FileField on PUT form submission of other fields
I have an optional FileField in my model which can be e.g. set in the POST method. Unfortunately this field gets always cleared in the PUT method. My model is defined like this: class MyModel(models.Model): myfile = models.FileField(upload_to=_upload_to, blank=True, null=True) This works as expected in the Django Admin page giving me the option to set a "Clear" checkbox explicitly. But in the Django Rest Framework form I can create a new instance with POST but if I then update my model with PUT it not only updates the changed fields but also clears my FileField. My serializer class looks like this: class MyModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ['url', 'id', 'myfile'] I also tried with this in the serializer to no avail: myfile = serializers.FileField(required=False, allow_null=True) -
output_field argument of expressionwrapper not identifying any field
while using ExpressionWrapper i am not able set output_field=DecimalField() i am getting error like Exception Type: NameError Exception Value: name 'DecimalField' is not defined from django.shortcuts import render from django.db.models import Value, F, ExpressionWrapper from store.models import Customer, Product def say_hello(request): discounted_price = ExpressionWrapper( F('unit_price') * 0.8, output_field=DecimalField()) queryset = Product.objects.annotate(discounted_price=discounted_price) return render(request, 'hello.html', {'name': 'Ashish', 'result': list(queryset)}) -
Product form through class based CreateView
I am trying to create a product form by 'Create View' as a class-based view, but it tells there is an issue in the terminal as the following snippet. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Products(models.Model): def __str__(self): return self.product_name user_name=models.ForeignKey(User, on_delete=models.CASCADE, default=1) product_name=models.CharField(max_length=200) product_descript=models.CharField(max_length=200) product_price=models.IntegerField() product_image=models.CharField(max_length=500, default='#') def get_absolute_url(self): return reverse('food:detail', kwargs={'pk':self.pk}) url.py from django.urls import path from . import views urlpatterns=[ path('addj',views.CreateProduct.as_view(),name='add_product'), ] views.py from django.views.generic.edit import CreateView from .models import Products class CreateProduct(CreateView): model= Products fields=['product_name','product_descript','product_price','product_image'] template_name='food/product-form.html' def form_valid(self,form): format.instance.user_name=self.request.user return super().form_valid(form) product-form.html <form method="POST" > {% csrf_token %} {{form}} <button type="submit"> </form> Can someone help me with this regard? Thanks -
How do I convert json data to django models
This is my json data. I want make a django model from this json data { "total_size": 6, "type_id": 2, "offset": 0, "products": [ { "id": 1, "name": "Panta Ilish", "description": "this is description", "price": 150, "stars": 5, "img": "images/pantailish.jpg", "location": "Dhaka, Bangladesh", "created_at": "2022-03-23 06:35:34", "updated_at": "2022-03-23 06:35:34", "type_id": 2 }, { "id": 2, "name": "Kacchi Biryani", "description": "this is description", "price": 200, "stars": 5, "img": "images/kacchi.jpg", "location": "Dhaka, Bangladesh", "created_at": "2022-03-23 06:35:34", "updated_at": "2022-03-23 06:35:34", "type_id": 2 } ] } -
Django Logging in AWS Cloudwatch - Impossible to configure handler
I am able to log, upload and view logs into AWS Cloudwatch; I have no warning locally, but In github action when doing a PR, I keep receiving the error: ValueError: Unable to configure handler 'watchtower-error ``` Below you can see the logging configuration in settings.py CLOUDWATCH_AWS_ID = env("CLOUDWATCH_AWS_ID") CLOUDWATCH_AWS_KEY = env("CLOUDWATCH_AWS_KEY") logger_boto3_session = Session( aws_access_key_id='AKIAUGB2EEYCAPYI2CXS', aws_secret_access_key='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', region_name='eu-west-2', ) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "aws": { "format": "%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "handlers": { "watchtower-info": { "level": "INFO", "class": "watchtower.CloudWatchLogHandler", "log_group": "CWOSLogs", "stream_name": f"logs", "formatter": "aws", }, "watchtower-error": { "level": "ERROR", "class": "watchtower.CloudWatchLogHandler", "log_group": "CWOSLogs", "stream_name": f"logs", "formatter": "aws", }, "console": {"class": "logging.StreamHandler", "formatter": "aws",}, }, "loggers": { "wella": {"level": "INFO", "handlers": ["watchtower-info"], "propogate": False}, "wellacaaa": {"level": "ERROR", "handlers": ["watchtower-error"], "propogate": False}, }, } Any suggestion?