Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the time in DateTimeField is not correct
Hello I am creating a website and trying to save the clock in time to the database every time a person clicks the clock in button but the time saved in the database is off by 8 hours. How do I fix this? code where I use the DateTimeField: from django.db import models from datetime import datetime, date #Create your models here. class Name(models.Model): name = models.CharField(max_length=200) timeIn = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __str__(self): return self.name -
Django Template _set.all
I have this model: class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... CustomerID = models.ForeignKey('Customers', on_delete=models.CASCADE) I render the Address Data in my Template: % for address in customer_default_shipping_address %} {% if address.Address_Company %} <h5>{{ address.Address_Company }}<br/> {{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5> {% else %} <h5>{{ address.Address_Firstname }} {{ address.Address_Lastname }}</h5> {% endif %} <address class="mb-0 font-14 address-lg"> {{ address.Street}}<br> {{ address.Zip}} {{ address.City}}<br> {% for customer in customer_default_shipping_address.customers_set.all %} <abbr title="Telefon">P:</abbr> {{ customer.PhoneNumber }} <br/> <abbr title="E-Mail">M:</abbr> {{ customer.Email }} {% endfor %} </address> {% endfor %} but the E-Mail and Phone Field will not be rendered, are I'm doing something wrong? -
django - how to nested admin objects create?
I've got a set of models that look like this: class User(AbstractBaseUser, PermissionsMixin): user_nm = models.CharField(max_length=10) user_email = models.EmailField(unique=True) user_tel = models.CharField(max_length=11, validators=[validate_user_tel]) class GolferUser(User): class Meta: proxy = True verbose_name = "Golfer User" app_label = "users" class GolferProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) user_birth = models.DateField( null=True, blank=True) user_gender = models.CharField( max_length=8, null=True, blank=True) class GolferPhoto(models.Model): golfer_profile = models.ForeignKey( GolferProfile, on_delete=models.CASCADE, related_name="GolferPhoto", null=True ) photo = models.ImageField( null=True, blank=True) and an admin.py that looks like this: class GolferPhotoInline(NestedStackedInline): model = GolferPhoto extra = 1 class GolferProfileInline(NestedStackedInline): readonly_fields = ("user_gender",) model = GolferProfile extra = 1 inlines = (GolferPhotoInline,) @admin.register(GolferUser) class GolferUserAdmin(NestedModelAdmin): inlines = (GolferProfileInline,) fields = ["user_nm","user_email"] list_display = [ "id", "user_nm", "user_birth", "user_email", ] The problem is that when I add [golferphoto] on the Admin site, the image file is not entered into the DB. An object is created in the DB, but the image file column is empty. views.py class GolferPhotoViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet, ): queryset = GolferPhoto.objects.all() serializer_class = GolferPhotoSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, GolferPhotoPermission) def create(self, request, *args, **kwargs): golfer_photo = super().create(request, *args, **kwargs) golfer_photo_instance = GolferPhoto.objects.get(id=golfer_photo.data["id"]) if request.FILES: image_file = request.FILES["image"] resize_image( image_file, "GOLFER" + str(golfer_photo_instance.id), "/main_photo/", "MAIN", ) resize_image( image_file, … -
Use of Subquery on django's update
I'm currently getting this error Joined field references are not permitted in this query Any idea why it happens if I do this? (models recreated for a simpler view) class Foo(models.Model): bar = models.ForeignKey( Bar, related_name='foos', on_delete=models.CASCADE) baz = models.ForeignKey( Baz, related_name='foos', null=True, blank=True, on_delete=models.SET_NULL) class Bar(models.Model): name = models.CharField(max_length=255) class Baz(models.Model): name = models.CharField(max_length=255) Foo.objects.update( baz=Subquery( Baz.objects.filter( name=OuterRef('bar__name') ).values('pk')[:1] ) ) -
Show error message in HTTP response Django [closed]
I am using http response to handle exception in my website. I want to show proper message / validation during create and update data. But It shows HTTP responses like Bad Request , Internel server error. Here is my code: try: // Some code except Exception as e: logger.error(e) return http.HttpResponseBadRequest(content=e) In pop up message it shows ,"Bad Request" Instead of "Bad Request" in pop up message I want to show another message. -
Python manage.py runserver does not return anything
I am new to Python and trying to execute "python manage.py runserver" from the command line shell but nothing happens and it just goes to the next line without any error message. -
How to save created csv into cloudinary cloud?
I am developing a data science project, I scrape specific site data, created a dataframe and saved in csv format. Now, i want to save that file to my cloudinary account as a file storage. class NepseApi(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): level2=[] rng=get_range(request, 8) table_Datas=get_url(request) level1= pd.Series(table_Datas).drop_duplicates().tolist() for k in level1: if len(k)> 35: level2.append(k) else: pass d=[] for l in range(1, len(level2)): c= level2[l].split('\n') d.append(c) df= pd.DataFrame(d[1:], columns=d[0]) date= pd.Timestamp.today().strftime('%Y-%m-%d') df['date']= date df_csv = df.to_csv(date +'.csv', index=True) df.rename(columns={'Traded Companies': 'company_name','No. Of Transaction': 'no_of_transaction', 'Max Price':'max_price','Min Price':'min_price','Closing Price':'closing_price','Traded Shares':'traded_shares','Previous Closing':'previous_closing','Difference Rs.':'difference_rs'}, inplace=True) jsn = json.loads(df.to_json(orient='records')) return Response(jsn) df_csv = df.to_csv(date +'.csv', index=True) # How to create path to save file? -
CurrentUserDefault doesn't work using Django Rest
I'm working with Django / Django Rest Framework and I'm looking for a solution to insert the logged user id automatically. i tried to use, user = serializers.HiddenField(default=serializers.CurrentUserDefault()) : But i doesn't work This is my serializer class from rest_framework import serializers from contact.models import Contact class ContactSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Contact fields = '__all__' -
How to Open/Edit/Save Ofifce files( Excel, Word) in browser using Python, Django?
I'm working on CMS project where I want to let users open excel sheets, word files to open in the browser, edit the file and after that save the file like this website : https://products.aspose.app/cells/editor. File would be saved to database. I have tried to find way by googling but unfortunately couldn't get one. Please help with the same. Thanks in advance. -
fetching data to return foreign key related fields django ajax
I have created a project and the project includes invoices , invoice items and items, sometimes during creating the invoice the admin doesn't remember the price of the item,we have inserted the price before, so I have decided to show the price when the admin selects an item (ForeignKey) in a drop down ! is it possible, please? my models.py class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=3)#when selecting an item , the price return back and write in the price field I have to display the price of the selects Item before submitting the form, then the admin know how much the price !? i returned back the price but i dont know how to give the returned value to the price field!? i have used inlineformset @login_required def check_price(request): item = request.GET.get('invoice-0-item',None) price = Item.objects.get(id=item).price print(price) data = { 'price':price, } return JsonResponse(data) and how to iterate through the number of dynamic forms ? in order to change make the 0 dynamic 'invoice-[0]-item' ! … -
How to verify the JWT using JWK without x5c?
I have a JWT security token that I need to verify via the jwks endpoint. Data in jwks looks like this: { "keys": [ { "alg": "RS256", "kty": "RSA", "use": "sig", "n": "xkAku1RWRycD0Fw49bIkdSy1O5rMTK4gyavBAxs9lkEPMCldrtBFWteXTw4bvdkDY62EOMjFN3QdqtJD9kRLcOxS9OwlLRBCVEEgPE3AyOazzovmVSVnrrwCcclU87iG8qMMx3ZK4qbaANpVETDRm-nU5L38la4i6yeNdJm0uX91003G07Ihq9LzWaIsT8pK1dirvq8d3ElUfZ-wBVz4imKnLrRgtTiZIa8eQvGVuWiBtp4I2rijDfzaYHKyAAh55UHNXCHde9yefQnSE_SHmunkCTLiQRbA7HorAOZBK0fiR9qidLMPwNBft01spufotp7UBseO7xusHezJ9VgIew", "e": "AQAB", "kid": "764edc29-9da0-43e0-97f3-2e140cc9152a", "x5t": "bisb-ais" } ] } I have tried one third party api but it looks like it is dependent on the x5c key which isn't present in my case. My code is: def verify_token(token): api_response = api_client(route='AUTH_KEY',query = {}) response = jwks_key(data=api_response) response.is_valid(raise_exception=True) public_keys = {} for jwk in response.data['keys']: kid = jwk['kid'] alg = jwk['alg'] public_keys[kid] = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk)) kid = jwt.get_unverified_header(token)['kid'] key = public_keys[kid] payload = jwt.decode(token, key=key, algorithms=alg,verify = True) How can I validate a JWT via jwks without x5c in python? -
Double Slash is Appearing in URL | Django Sitemap
Double slashes are appearing in Sitemap.xml enter image description here Code of models.py class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return reverse("category_items", kwargs={"category": self.name}) Code of urls.py from django.contrib.sitemaps.views import sitemap from core.sitemaps import BlogSitemap, CategorySitemap sitemaps = { "blogs": BlogSitemap(), "categories": CategorySitemap(), } urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] Code of sitemap.py class CategorySitemap(Sitemap): changeFreq = "weekly" priority = 0.5 def items(self): return Category.objects.all() what is the possible soultion -
How to see if user is connected to internet or NOT?
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to implement a feature that ,`If user is connected to internet then everything works fine BUT if user is not connected to internet then show a message like "You're not Connected to Internet". What have i tried I also tried channels but then i think internet connection are far away from Django-channels. I also tried this : url = "http://127.0.0.1:8000/" timeout = 5 try: request = requests.get(url, timeout=timeout) print("Connected to the Internet") except (requests.ConnectionError, requests.Timeout) as exception: print("No INTERNET") But it is keep showing me : 'Response' object has no attribute 'META' I don't know what to do. Any help would be Appreciated. Thank You in Advance -
What's the best way to get many items from a big table with specific IDs
I need to make a query with Django to a Postgres table with millions of rows and I need to select a few hundred items with specific IDs (or another field which has an index). Right now I'm doing it like this: A_query_filter = Q(item_id=None) for batch_id in batch_ids: A_query_filter = A_query_filter | Q(item_id=batch_id) A = Item.objects.filter(A_query_filter).order_by('-added') The query is pretty slow, even though I have an index on "item_id". Is there a more efficient way to do this? -
window.open opens multiple tabs instead of one in google chrome
I have created a dyanmic input field with search button.At first only on tab is opened when i click on Button. But after saving if I click on it again then it opens multiple tabs for the same url. No of tabs is equal to the no of dyanmic input field created and this happens only in google chorme. <button type="button" id='btn[]' name="btn" class='btn btn-default' ><i class="fa fa-search"></i></button> <script> $(document).on('click', '[id^=btn]', function(f){ f.preventDefault() console.log('vendor side'); console.log(this.id); window.inputid = $(this).closest("tr").find("td input").attr("id"); console.log(window.inputid); var myWin = window.open("/vendorlist/", "", "width=500,height=500"); }); </script> How can I stop window.open to open multiple tabs after dyanmic fields are created.Please help. -
Check if image exists in Django template
I currently have a template that loops through a list of URLS, like so. {% for i in images %} <div class="col"> <p><a href="{{i}}"><img height="200" src="{{i}}"/></a></p> <p><a href="{{i}}">{{i|cut:"/uploads/"|truncatechars:20}}</a></p> </div> {% endfor %} The issue is at the time of rendering some of the images are not done processing. So how would I check if the image is available via the url? -
How to resend a cognito invite when credentials expire
here i need to resend the cognito invite to a user whose credentials expire before he signs up @staticmethod def get_set_cognito(sender, instance, *args, **kwargs): self = instance if self.pk is None: client = boto3.client('cognito-idp', region_name=settings.AWS_DEFAULT_REGION) # try: # # Check if the user exists in Cognito # existing_user = client.admin_get_user(Username=self.user.email, # UserPoolId=settings.COGNITO_USER_POOL_ID) # except client.exceptions.UserNotFoundException: # pass try: # if not existing_user: response = client.admin_create_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email, DesiredDeliveryMediums=['EMAIL'], UserAttributes=[ { 'Name': 'custom:backend_url', 'Value': settings.BACKEND_API_URL }, { 'Name': 'custom:backend_id', 'Value': settings.BACKEND_ID }, { 'Name': 'email_verified', 'Value': 'true' }, { 'Name': 'email', 'Value': self.user.email }, { 'Name': 'family_name', 'Value': self.last_name if self.last_name else ' ' }, { 'Name': 'given_name', 'Value': self.first_name if self.first_name else ' ' }, { 'Name': 'phone_number', 'Value': self.phone if self.phone else ' ' } ], ) self.user.username = response['User']['Username'] if(len(response['User']['Username']) < 3): logger.error("empty response from cognito for email - " + self.user.email) logger.error(response) self.user.delete() else: self.user.save() # else: # self.user.username = existing_user['Username'] # self.user.save() except client.exceptions.UsernameExistsException: # existing_user = client.admin_get_user(Username=self.user.email,UserPoolId=settings.COGNITO_USER_POOL_ID) existing_user = client.admin_get_user( UserPoolId=settings.COGNITO_USER_POOL_ID, Username=self.user.email ) self.user.username = existing_user['Username'] self.user.save() except Exception as e: logger.error( "there was an error trying to create cognito user", e) self.user.delete() Set MessageAction to "RESEND" to resend the invitation message to a user … -
How can i populate the user_id using Django Rest
I'm working on a small project using Django Rest, I would like to populate the user_id field each time a user submit a form. This is my code class ContactView(ListModelMixin, viewsets.GenericViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer def create(self, request): serializeObject = ContactSerializer(data = request.data, many=True) if serializeObject.is_valid(): contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data, status = status.HTTP_201_CREATED) return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST) My Serializer : class ContactSerializer(serializers.ModelSerializer): #list_name = serializers.CharField(source="list.name", read_only=True) class Meta: model = Contact fields = '__all__' -
Form filled out but still invalid
I am trying to get data from a form and redirect if the form is valid. I am, however, seemingly not grabbing any data. In a test, I fill out each form with "test". I would expect these forms to be valid and redirect to a success page, and am unable to figure out where I am going wrong with my logic. Error: form.errors = <ul class="errorlist"><li>category<ul class="errorlist"><li>This field is required.</li></ul></li><li>comment<ul class="errorlist"><li>This field is required.</li></ul></li></ul> forms.py from django import forms class CandidateReportForm(forms.Form): category = forms.CharField(label='Category', max_length=10) comment = forms.CharField(label='Comment', max_length=1000) views.py from django.shortcuts import render from django.views import View from .forms import CandidateReportForm class CandidateReportView(View): form_class = CandidateReportForm form_template = 'Reports/candidate_report.html' form_submit_template = 'Reports/report_submitted.html' form_submit_error = 'Reports/report_error.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.form_template, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return render(request, self.form_submit_template) else: print(f"form.errors = {form.errors}") return render(request, self.form_submit_error) html <div class="container"> <div class="card"> <h2 class="card-title">Report</h2> {{ form.as_p }} <form action="submit_candidate_report" method="post">{% csrf_token %} <input class="btn btn-primary" id="report" name="report" type="submit" value="Submit"> </form> </div> </div> -
Delete uploaded files when calling transaction.set_rollback() on the View
I have a simple file upload function as shown below: Model: class ImageUpload(models.Model): image = models.ImageField() Serializer: class ImageUploadSerializer(serializers.ModelSerializer): class Meta: model = ImageUpload fields = ['id', 'image'] View: class TestView(APIView): @transaction.atomic def post(self, request): # some logic code serializer = ImageUploadSerializer(data={ 'image': request.FILES['file'] }) if serializer.is_valid(): serializer.save() if something_bad_happen: transaction.set_rollback(True) return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK) Ok, if everything is normal, I will have an image file saved to the hard disk on the server and a record stored in the database. When I called transaction.set_rollback(True) in View, Django did the rollback perfectly and no records were added to the database. But after I recheck, Django didn't delete the image file on my hard disk even though there is no record in the DB associated with that image file. I also searched and got a solution like post_delete: @receiver(models.signals.post_delete, sender=ImageUpload) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.image: if os.path.isfile(instance.image.path): os.remove(instance.image.path) This seems to work only when I call delete() method but with not with transactions. How can I delete unnecessary files during upload file when my View raising exception or transaction.set_rollback(True) function is called? -
How to prevent a page from refreshing when I want to submit a form?
I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful. Here is my code: html <form action="{% url 'cart-add' %}" method="GET" id="myform"> {% csrf_token %} <label> <input type="hidden" name="{{ product.pk }}"> <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1"> <button type="submit" value="">Add to chart</button> </label> </form> Ajax/JQuery script <script type="text/javascript"> $(document).ready(function () { $('myform').on('submit', function(e) { e.preventDefault(); $.ajax({ url : $(this).attr('action') || window.location.pathname, type: "GET", data: $(this).serialize(), success: function (data) { $("myForm").html(data); }, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); }); </script> When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added. Can somebody help me? Thank you very much for your time. I much appreciate it! -
how to customize django forms and success message without bootstrap?
I'm currently making a registration page. I'm using django's registration form and message alert. However, i do not use Bootstrap and would not like to use Bootstrap. How am i able to customize my registration form and message alerts with pure CSS? Here I provide the code to my message alerts: base.html <div class="alert"> {% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %} </div> views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Thank you for registering, {username}.') return redirect('conference:index') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) I've tried adding the "alert" class into the CSS, however it does not work at all. Is there something I'm missing out in order to make the CSS styling work? -
Issue in adding sub-apps in settings.py file
I am unable to add my sub apps like category, user in settings.py. It was working fine but don't know what mistake I have done. Please help. I'm not able to progress from here. Please create a model and get that model to admin panel. Link to github -
how to remove absolute disk path in django urls
I use Django 3.1, and i get a trouble. who can tell me how to do. thanks. My problem is my site path in linux Hard disk appeared in the admin url, like this: http://127.0.0.1/data/pysites/mysite.com/mysite/admin/ '/data/pysites/mysite.com/mysite/' is my linux disk path, it appeared in the admin url, I hope it is only ‘http://127.0.0.1/admin/’, how can i remove it? in vews.py, i print request.path is: /data/pysites/xxx.com/mysite/play/ed160af7-5c98-4868-a679-2e86803e67d2/ i think the right path shuold be /play/ed160af7-5c98-4868-a679-2e86803e67d2/ -
Django: My object's list attribute not saving inside of a function
Newbie to Django here. So I made a model with an attribute being a list. Then I made an instance of it. Then I have a function that has a for loop that appends to the "class list" attribute of the object. This is not permanently saving the list data to the attribute of the object (isn't that the whole point of model objects?). I am very confused on how to do that. class Mymodel: class_list = [] my_object = Mymodel() values = [1, 2, 3, 4, 5, 4, 3, 2, 1] def myFunction(): for value in values: my_object.class_list.append(value) return something_unrelated So in my_object, I want new values saved in its class_list attribute. I don't want the function to return the class_list. I want Django to save the attributes in its database. If I insert print statements before and after the for loop (see below), I get exactly what I would expect. def myFunction(): print(my_object.class_list) for value in values: my_object.class_list.append(value) print(my_object.class_list) return something_unrelated In the consul I will see [] [1, 2, 3, 4, 5, 4, 3, 2, 1] But if I print(my_object.class_list) afterward, it will print [] So how do I get Django to save my object info? What …