Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access different serializer if a queryset is empty Django Rest Framework
I don't think I am implementing this correctly, but I am trying to change the serializer used for a queryset based on a condition (if there are no venues in one queryset, switch to another serializer and just return list object). I'm not quite sure how to do this. Here is the view class SavedVenuesViewSet(viewsets.ModelViewSet): serializer_class = UserVenueSerializer def get_queryset(self): list_id = self.request.GET.get('list_id', None) user = self.request.user.id print(user) print(list_id) print(type(list_id)) qs = UserVenue.objects.filter(user_list=int(float(list_id))) if not qs: print("EMPTY LIST") #this is where i try to switch serializer serializer_class = UserListSerializer return UserVenue.objects.filter(id=int(float(list_id))) else: return qs Here are the relevant serializers: class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['user', 'user_list', 'venue'] depth = 2 [...] class UserListSerializer(serializers.ModelSerializer): class Meta: model = UserList fields = ['id', 'user', 'list_name'] depth = 2 The traceback isn't throwing an error but it isn't doing what I am hoping: 1 45 <class 'str'> EMPTY LIST [29/Sep/2021 11:05:36] "GET /api/savedvenues/?list_id=45 HTTP/1.1" 200 2 -
I can't quite figure out why I can' access a URL with Django
I'm trying to access the URL ending "basket/" but when i go to the page i receive the 404 error shown below. I understand this error isn't thrown due to Django not being able to find the template, it has something to do with my product_detail view. Here are my urls linking me to basket/ core/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static app_name = 'core' urlpatterns = [ path('admin/', admin.site.urls), path('', include('main_store.urls', namespace='main_store')), path('basket/', include('basket.urls', namespace='basket')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) basket/urls.py from django.urls import path from . import views app_name = 'basket' urlpatterns = [ path('', views.basket_summary, name='basket_summary') ] Here is the basket/views.py: from django.shortcuts import render def basket_summary(request): return render(request, 'main_store/basket/summary.html') And here is the view that is throwing the error. main_store/views.py: def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) return render(request, 'main_store/products/single_product.html', {'product': product}) If anyone can shed some light on what I'm the issue is or what I'm doing wrong, it would be much appreciated. Thanks in advance. -
Authenticate Oauth2 Bearer Token generated by C sharp with validator= SHA1 and decryption="AES" in Pyhton Django
I am new to Django can some please help!! we provide username and password to Csharp API and in return we get a access token(Oauth2) with token type:bearer i want to use that token in django to authenticate and figure out the level of permissions from the given bearer token i was able to obtain the token in Django but cant find any library that Validates this token in Django(python) import requests,json, getpass token_url = "<<Token_url>>" #test_api_url = "<<url of the api you want to call goes here>>" # Step A - resource owner supplies credentials #Resource owner (enduser) credentials #RO_user = raw_input('Enduser netid: ') #RO_password = getpass.getpass('Enduser password: ') #client (application) credentials client_id = 'username' client_secret = 'password' #step B, C - single call with resource owner credentials in the body and client credentials as the basic auth header # will return access_token data = {'grant_type': 'password','username': client_id, 'password': client_secret, 'scope': 'scriptingAPI' } access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False) print (access_token_response.headers) print (access_token_response.text) tokens = json.loads(access_token_response.text) print ("access token: " + tokens['access_token']) # Step C - now we can use the access_token to make as many calls as we want. api_call_headers = {'Authorization': 'Bearer ' + tokens['access_token']} print (api_call_headers) … -
How to redirect to same page after form action in django
I'm new to Django and I'm trying to create an app which will accept multiple images upload using forms and then redirect to the same upload page and display uploaded images just below the form. My program works for uploading, but then I cannot exactly redirect it back to the same page which contains the upload form and images. index.html(in templates folder) <form> action="{% url 'fileapp:uploads' %}" method="POST" enctype="multipart/form-data" > <input type="text" name="filename" placeholder="enter your file name" /> <input type="file" multiple name="uploadfoles" /> {% csrf_token %} <button type="submit">File Upload</button> </form> <h3>Previously uploaded files: <br></h3> {% for d in data %} <p>{{d.f_name}} ---- <img width="50" src="{{d.myfiles.url}}" /></p> {% endfor %} views.py from . models import myuploadfile def index(request): context = { "data":myuploadfile.objects.all(), } return render(request,"index.html",context) def send_files(request): if request.method == "POST" : name = request.POST.get("filename") myfile = request.FILES.getlist("uploadfoles") for f in myfile: myuploadfile(f_name=name,myfiles=f).save() return redirect("fileapp:index") urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("",include("myfileapp.urls",namespace="fileapp")) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Whenever I press 'File Upload' button, the app should redirect back to the same page where we upload files, but I get this error: … -
Error when I put choices in Charfield in a Serializer which is not based on Model - Django Rest Framework
I make a serializer, which is not based on a model and one of the fields is a charfield in which I want to put a specific choices. Is that possible? The error I get when I put the code: TypeError: init() got an unexpected keyword argument 'choices' STATUS_TYPES = ( ('', ''), ('male', 'male'), ('female', 'female') ) class SomeSerializer(serializers.Serializer): gender = serializers.CharField(max_length=100, choices=GENDER_TYPES) -
Error: decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] in Django
Django View: @api_view(['PUT']) @permission_classes([IsAdminUser]) def updateProduct(request, pk): data = request.data product = Product.objects.get(_id=pk) product.name = data['name'], product.price = data['price'], product.category = data['category'] product.description = data['description'] product.countInStock = data['countInStock'] print(data) serializer = ProductSerializer(product, many =False) return (Response(serializer.data)) Models.py: class Product(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) name = models.CharField(max_length = 200, null= True, blank= True) image = models.ImageField(default="/place.jpg",null= True, blank= True) netWeight = models.CharField(max_length = 200, null= True, blank= True) category = models.CharField(max_length = 200, null= True, blank= True) description = models.TextField(null = True, blank= True) rating = models.DecimalField(max_digits = 7, decimal_places = 2,null= True, blank= True) price = models.DecimalField(max_digits = 7, decimal_places = 2,null= True, blank= True) numReviews = models.IntegerField(null= True, blank= True, default=0) countInStock = models.IntegerField(null= True, blank= True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) Product Action.js (React): export const listProductUpdate = (product) => async (dispatch, getState) => { try { dispatch({ type: PRODUCT_UPDATE_REQUEST }) const { userLogin: { userInfo }, } = getState() const config = { headers: { 'Content-type': 'application/json', Authorization: `Bearer ${userInfo.token}` } } const { data } = await axios.put( `/api/products/update/${product._id}/`, product, config ) dispatch({ type: PRODUCT_UPDATE_SUCCESS, payload: data }) dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data }) } catch (error) { dispatch({ type: … -
Generating Multiple Documents (Python TempFile Module)
I am currently trying to print financial reports with my web app - this needs to happen by the click of a button. When I click the button, however, the app only prints 1 document (the first one) I don't understand what this could be as there are 2 different returns for each if statement that re-direct to 2 different .HTML pages This is what I have tried at the moment: import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc} html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM} html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) else: printTrialBalanceMonth = False The program only prints what the first … -
How do I convert an annotation from timedelta to seconds?
I'm annotating a queryset with time passed since the model was created: super().get_queryset().annotate(duration_seconds=timezone.now() - F("start")) The result is a timedelta object, but I need it to be an integer in seconds. Calling .seconds is not possible in the expression, so how can I do this? -
Show model property if model exists and some string if not
To make it clear I want do the following with just one line: {%if model %} <input type="text" class="form-control" id="title" value="{{model.title}}" placeholder="Enter Title"> {% else %} <input type="text" class="form-control" id="title" value="" placeholder="Enter Title"> {% endif %} I tried this: <input type="text" class="form-control" id="title" value="{% model.title if model else "" %}" > And it didn't work: Invalid block tag on line 15 I don't think I have to make a custom template tag for this simple kinda things. Thanks in advance -
Django - How to raise an error if a user signed up yet has not verified their email?
I'm trying to call a function from views in my forms. I tried to accomplish it in several ways, but I realized that I don't do it in a proper way. The end result I'd like to achieve: raise an error on a login page if a user signed up yet has not verified their email. How can I make it work? forms.py from django import forms from django.core.exceptions import ValidationError from . import views from . import models class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) remember_me = forms.BooleanField(required=False) def clean(self): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(username=email) user_verified = views.complete_verification() if user.check_password(password): return self.cleaned_data else: self.add_error( "password", forms.ValidationError("Incorrect password. Try again.") ) if not user_verified: self.add_error( "email", forms.ValidationError( "Please check your inbox and verify your email." ), ) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("The user does not exist.")) views.py def complete_verification(request, key): try: user = models.User.objects.get(email_secret_key=key) user.email_verified = True user.email_secret_key = "" user.is_active = True if user.email_verified and user.is_active: user.save() login(request, user, backend="django.contrib.auth.backends.ModelBackend") # todo: add success message except models.User.DoesNotExist: # todo: add error message pass return redirect(reverse("pages:home")) models.py import uuid from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models from django.core.mail import send_mail … -
Writing on-request filtering for related objects
Suppose that we have following models class Category(models.Model): name = models.CharField(max_length=254) class Item(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") name = models.CharField(max_length=254) state = models.ForeignKey(State, on_delete=models.CASCADE) Categories and their items are listed like so def view(request): categories = Category.objects.all() pass {% for category in categories %} {{ category.name }} {% for item in category.items.all %} {{ item.name }} {% endfor %} {% endfor %} In this structure, I want to write on-request filtering for listed 'items'. def view(request): ... queryset = ??? state = request.GET.get('state') if state: queryset = queryset.filter(state__name=state) The problem is defining 'queryset'. Because, Items are listed as related objects of category. Can it be done properly? or Do I need to change design? -
How To Create Password Generator Context In Python Django
Heya I Created Password Generator For Website. But I Want To Add Context In Class Based View. code: class thank_you(OrganizerAndLoginRequiredMixin, generic.TemplateView): template_name = "order_complete.html" password = "" for i in range(5): i = chr(random.randint(0, 90)) j = chr(random.randint(65, 90)).lower() k = random.randint(0, 10) password = str(password) + i + j + str(k) context = { "code": password } -
Django restframework generic viewset not working with get and get detail views with the same url_path and url_name
How can I make two views in a DRF Generic viewset use the same url_paths and url_names provided the make use of the same or different methods but different details value, eg must can both be Get methods but would have details=True and details=False on them sample code for more clarity; @action(methods=["get"], detail=False, url_path="users", url_name="users") def get_users(self, request): # code here @action(methods=["get"], detail=True, url_path="users", url_name="users") def get_user(self, request, id): # code here get_users work with this endpoint -> {{base_url}}/{{prefix}}/users get_user does not work with -> {{base_url}}/{{prefix}}/{{user-id}}/users but if I change the url_path and url_name to something else eg -> single-user then the endpoint for getting a single user works -> {{base_url}}/{{prefix}}/{{user-id}}/single-user how can I solve this to make the users and user have the same url_name and url_path because the actions have detail as False(users) and True(user) for both of them respectively NB; Also please not that this viewset does not make use any model -
How shoud i schedule my Views templates in django?
I need to run my view for specific time in my schedule days. how I can make it ? -
AssertionError when trying to render API data using djangorestframwork?
I am trying to build a function API using djangorestframwork But I have this error Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set.querysetor have a.get_queryset()method. This is me API function @api_view(('GET',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def course_api(request): if request.method == 'GET': queryset = Course.objects.all() serializer = CourseNameSerializers(queryset, many=True) return Response(serializer.data, template_name='api.html') when i delete first line and second line another error occurs and this error is .accepted_renderer not set on Response -
how to fix error app crushed in heroku django deployment
help me? State changed from up to crashed 2021-09-29T09:08:18.695873+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=djangobiometricattendance.herokuapp.com request_id=5b33c9ac-8ee3-4561-9371-b38c48c96485 fwd="197.156.124.125" dyno= connect= service= status=503 bytes= protocol=https 2021-09-29T09:08:19.089718+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=djangobiometricattendance.herokuapp.com request_id=20c87f7c-0f11-42fd-9a49-f5ce4014b8e3 fwd="Ip address" dyno= connect= service= status=503 bytes= protocol=https 2021-09-29T09:08:22.090343+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=djangobiometricattendance.herokuapp.com request_id=a7d7a82b-1852-4227-b182-4beb53156cb8 fwd="ip address" dyno= connect= service= status=503 bytes= protocol=https 2021-09-29T09:08:22.521606+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=djangobiometricattendance.herokuapp.com request_id=76b0a044-7296-4fa9-bd45-3c7cd7449285 fwd="197.156.124.125" dyno= connect= service= status=503 bytes= protocol=https -
Django dynamic url redirecting to 404
I'm trying to create a dynamic URL pattern where there's an ID passed into the URL and used the retrieve a piece of information from the database. Here's the definition of the pattern: urlpatterns = [ path('',views.index,name='index'), path('<int:question_id/>', views.detail,name='detail'), path('<int:question_id>/results/',views.results,name='results'), path('<int:question_id>/vote/',views.vote,name='vote') ] and here's the piece of code used to retrieve the information: def detail(request, question_id): question = get_object_or_404(Questions, pk = question_id) return render(request, 'polls/detail.html', {'question': question}) the user seems to be redirected to a 404 page no matter what id is passed in the url. -
nested serializer filed TypeError: Object of type QuerySet is not JSON serializable
I have two serilizers like this : class UsersInfoSeriliazerByUsers(serializers.ModelSerializer): class Meta: model = FreeTime fields = '__all__' class SetTimeZoneSerializer(serializers.Serializer): TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) meeting_date = serializers.DateField(format="%d-%m-%Y", input_formats= ['%d-%m-%Y', 'iso-8601']) time_zone_destination = serializers.ChoiceField( choices = TIMEZONES) time_table = UsersInfoSeriliazerByUsers(many=True,read_only=True) in views.py i need to get data from freetime model and send it to SetTimeZoneSerializer again(i need to serialize the queryfilter results and it is a nested field ) : @action(detail=False, methods=['post']) def common(self,request): serializer = SetTimeZoneSerializer(data = request.data) if serializer.is_valid(): j={} j['meeting_date']=serializer.data['meeting_date'] j['time_zone_destination']=serializer.data['time_zone_destination'] j['time_table'] = FreeTime.objects.all().values() json_string = json.dumps(j) serializer = SetTimeZoneSerializer(json_string, many=True) and i got this error : Internal Server Error: /api/time/common/ Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/admin1/mizbanproject/time-algorithm/time_algorithm_api/api/views.py", line 114, in common json_string = json.dumps(j) File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/usr/lib/python3.8/json/encoder.py", … -
How to add many objects to the database in Django TabularInLine?
Currently I have a need to add a lot of objects to a punch-through table using a python manage.py shell. I will describe the models here in a nutshell, I will not litter with unnecessary fields. So I have a model Product: class Product(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) I have a model Shop: class Shop(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) I have model ShopQuantity: class ShopQuantity(models.Model): shop = models.ForeignKey(Shop, blank=True, on_delete=models.CASCADE, null=True, related_name='product_list') product = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True, related_name='shop_list') price = models.DecimalField(max_digits=10, decimal_places=2, default='0') quantity = models.IntegerField(blank=True, null=True, default='0') In admin.py: class ShopQuantityInline(admin.TabularInline): model = ShopQuantity extra = 0 @admin.register(Shop) class ShopAdmin(admin.ModelAdmin): fields = ['name', 'slug'] list_display = ['name'] inlines = [ShopQuantityInline] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = ['name', 'slug'] list_display = ['name'] inlines = [ShopQuantityInline] Suppose I already have 1000 items of goods in my database. Please tell me how I can put these 1000 products inside the store inside the Shop table. I know it's possible using manage.py shell but I do not understand how it can be done. If anyone came across this and solved this problem, please help. -
Update Stock value after product invoice in Django
I am working on a project on Pharmacy inventory management. I two models Medicine and Medicine Sale, code is mentioned below. I want to update the stock value inventory of each medicine when I generate a sale.e:g If I sell 3 quantities of a product, that quantity should be removed from the stock value of that product. Can anyone guide me? Here is the models.py file which has both classes of Medicine and Medicine Sale class Medicine(models.Model): medicine_choices = ( ('Tablet', 'Tablet'), ('Syrup', 'Syrup'), ('Granules', 'Granules'), ('Capsules', 'Capsules'), ('Injection', 'Injection'), ('Supplements', 'Suplements'), ) year_choices = ( ('2021', '2021'), ('2022', '2022'), ('2023', '2023'), ('2024', '2024'), ('2025', '2025'), ('2026', '2026'), ) medicine_name = models.CharField(max_length=255) medicine_type = models.CharField(choices=medicine_choices, max_length=100) stock_value = models.IntegerField() price = models.IntegerField() expiry_date = models.CharField(choices=year_choices, max_length=100) def __str__(self): return self.medicine_name class MedicineSale(models.Model): medicine1 = models.ForeignKey(Medicine, related_name = 'first_medicine', on_delete=CASCADE) qty_no_1 = models.FloatField() price_no_1 = models.FloatField() total_amt1 = models.FloatField(editable=False, default=0) medicine2 = models.ForeignKey(Medicine, related_name = 'second_medicine', on_delete=CASCADE, blank=True) qty_no_2 = models.FloatField() price_no_2 = models.FloatField() total_amt2 = models.FloatField(editable=False, default=0) medicine3 = models.ForeignKey(Medicine, related_name = 'third_medicine', on_delete=CASCADE, blank=True) qty_no_3 = models.FloatField() price_no_3 = models.FloatField() total_amt3 = models.FloatField(editable=False, default=0) medicine4 = models.ForeignKey(Medicine, related_name = 'fourth_medicine', on_delete=CASCADE, blank=True) qty_no_4 = models.FloatField() price_no_4 = models.FloatField() total_amt4 … -
Unable to see pie chart in template using django and chart js
I want to count the number of companies in companytype model and show that in pie chart. The count should by the name field in company table. eg: If Company Type is medical and there are 4 companies in that category then i want to show its count on pie chart. models.py class CompanyType(models.Model): company_type = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) class Company(models.Model): name = models.CharField(max_length=100) address = models.TextField() company_type = models.ForeignKey(CompanyType,on_delete=models.CASCADE) is_active = models.BooleanField(default=True) views.py def index(request): labels = [] data = [] queryset = Company.objects.values('company_type__company_type').annotate(company_type_sum=Count('name')).order_by('-company_type_sum') for entry in queryset: labels.append(entry['company_type__company_type']) data.append(entry['company_type_sum']) context = { 'labels':labels, 'data':data, } return render(request,'index.html',context) I have taken Chartjs code from index.html file if there is something wrong. index.html <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { labels: [data.labels], datasets: [{ label: 'Companies in Particular Section', data: [data.data], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], … -
Filter for slug, title not working in Django rest Framework
I am trying to make a dynamic search but cant seem to filter queryset by slug. I have tried just about everything and went through stackoverflow questions and nothing seems to solve it. I have tried changing the keyword to "id" and "category" and I get a result but not on slug. Here is the error/no queryset I received. This is the filter I made for authors which seems to work. Here is the code, Please inform if I need to provide more code to understand the problem as this is my first question here. Thanks! blog_api/views.py from rest_framework import generics from blog.models import Post from .serializers import PostSerializer from rest_framework.permissions import SAFE_METHODS, IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission, IsAdminUser, DjangoModelPermissions from rest_framework import viewsets from rest_framework import filters from django.shortcuts import get_object_or_404 from rest_framework.response import Response class PostUserWritePermission(BasePermission): message = 'Editing posts is restricted to the author only.' def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user class PostList(generics.ListAPIView): permission_classes = [IsAuthenticated] # queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): user = self.request.user return Post.objects.filter(author=user) class PostDetail(generics.RetrieveAPIView, PostUserWritePermission): # permission_classes = [PostUserWritePermission] queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): item = self.kwargs["pk"] print(item) return … -
values duplicating for no reason in Django
I am getting this error on my model save, i don't understand why is it duplicating when I am only inserting value once if request.method == 'POST': gender = request.POST.get('gender') email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] date_of_birth = request.POST.get('date_of_birth') contact_no = request.POST['contact_no'] password = request.POST.get('password') user_type = request.POST.get('user_type') user = User( gender=gender, email=email, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, contact_no=contact_no, user_type=user_type ) user.set_password(password) user.save() city = request.POST.getlist('city') state = request.POST.getlist('state') zip_code = request.POST.getlist('zip_code') address_street = request.POST.getlist('address_street') address_obj_list = [] for index,value in enumerate(address_street): address_obj_list.append(Address( user = user, street = value, city= city[index], state = state[index], zip_code =zip_code[index] ) ) my error IntegrityError at /reg/ duplicate key value violates unique constraint "manageusers_user_username_key" DETAIL: Key (username)=(zahidmala32) already exists. i have this method on my Model user which seems to give me error def save(self, *args, **kwargs): if self.email != None: self.username = self.email.split('@')[0] super().save(*args, **kwargs) -
How can I override Django Model's save() method
I have a model which looks like this. import uuid from django.db import models class TemplateId(models.Model): id = models.SmallAutoField(primary_key=True, serialize=False, verbose_name='ID') template_name = models.CharField(max_length=255, default="") template_id = models.UUIDField(max_length=255, default=uuid.UUID, unique=True) def __str__(self): return str(self.template_name) class Meta: ordering = ('-id',) I have another function/code where I'm calling an API to fetch the template_name and template_id and store it in dB. But every time when I get a response from the API, I want to override the the whole table (everytime deleting old record and then adding the new records) currently I'm doing this: def fetch_template_id(): api_response = # calling the API for template_id in api_response: temp_name = template_id["name"] obj = TemplateId(template_id=template_id["id"], template_name=template_id["name"]) obj.save() In order to override, I tried overriding the save method in my TemplateId model as below but it didn't work def save(self, *args, **kwargs): super(TemplateId, self).save(*args, **kwargs) Since the data gets saved in the model fields by getting the API response, next time when same data is received from the API response, it throws an duplicate data error in the dB. How do I override all the every with each API call? -
Get notification on React-Native when app is closed (with websockets if possible)
I have an app whose back-end is build using django rest(DRF) and for real time changes I use channels and on front end I use websockets, but I want to create a notification for the user when a new message is created(I have completed the back-end part of it), but now I want to get the user notified on front end, but without using 3rd part libraries like firebase (just an example, nothing against it) or other ones.