Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image is not showing in python project
<div class="owl-carousel" id="slider1"> {% for b in bottomwears %} <a href="{% url 'product-detail' b.id %}" class="btn"><div class="item"><img src="{{b.product_image.url}}" alt="" height="300px"><span class="fw-bold">{{b.title}}</span><br><span class="fs-5">Rs. {{b.discounted_price}}</span></div></a> {% endfor %} </div> Below is the screen shoot of website where image is not shown. -
Django ORM object.related.id vs object.related_id after used select_related('related')
Let's suppose that we have this models: class Product(models.Model): .... price = models.DecimalField(max_digits=12, decimal_places=2) class Order(models.Model): .... product= models.ForeignKey(Product) After used select_related for query like that Order.objects.filter(...).select_related('product'), is there any performance difference between order.product.id and order.product_id? -
checkbox value not getting posted in Views.py Django
i have code which should post values of selected checkbox to Views.py after a button click , but for me it is sending me an empty list when trying to print the checkbox value in views.py So below is my code . Views.py if request.method=='POST': if 'submit' in request.POST: user_list = request.POST.getlist('myarray') print(user_list) html <form method="post">{% csrf_token %} <!-- <div class="w-full sm:w-auto flex items-center sm:ml-auto mt-3 sm:mt-0"> <label class="form-check-label ml-0 sm:ml-2" for="show-example-5">Show Server List</label> <input data-target="#document-editor" class="show-code form-check-switch mr-0 ml-3" type="checkbox" id="show-example-5"> </div> --> <button id= "AnchroTagForButton" name="submit" href=""> <span></span> <span></span> <span></span> <span></span> button </button> </div> <div class="p-5" id="document-editor"> <div class="preview"> <!-- <div class="alert alert-primary alert-dismissible show flex items-center mb-2" role="alert"> <i data-feather="alert-octagon" class="w-6 h-6 mr-2"></i>{{note}}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"> <i data-feather="x" class="w-4 h-4"></i> </button> </div> --> <!-- <div data-editor="document" class="editor document-editor"> --> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>Server</th> <th>Name</th> <th>Labels</th> </tr> </thead> <tbody> {% for datas in customerserver %} <tr> <td> <div class="form-check form-switch"> <input class="form-check-input" name="Servers" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </form> So here i have to collect all checkbox values selected /(Checkbox name:Servers) , and post it in views.py , but here when i try to print it in views.py . it … -
Relations in Django
I have 3 tables called Customer, Order and Barcode. A customer can have multiple order object and Object can have multiple barcodes I want a new table that is populated when the order is successful. For example, it can have like c_id o_id b 1 2 [xxx, xfxx, xxasfx] 1 3 [yyy, asf, xasdfxx] 1 4 [xcxx, xxax, xvxx] 2 5 [xxrx, xxtx, xxyx] I have tried the following: class Order(models.Model): order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Barcode(models.Model): barcode_id = models.CharField(max_length=75, unique=True) order_id = models.ForeignKey(Order, on_delete=models.CASCADE) class Customer(models.Model): customer_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order_id = models.ManyToOneRel(Order, on_delete=models.CASCADE) How do I create a final relation for the new table? Thanks in advance -
Django - how can i add an additional check in my login?
I'm creating a single page application that uses Django's session authentication on the backend. Django is using django-allauth for everything authentication-related. I would like to add an additional step to my login where the user inputs a code and Django must verify that code too, other than password and username. How can i do that? Note that i'm using Django as an API, so i don't need to edit the form and add another field, i only need to add another check to the authentication backend, so something very easy: if the code is right, than proceed to check username and password too, else return an error. The problem is that i don't know where to add this check. I think i need to work on the authentication backend, but i'm stuck here. Here is the allauth authentication backend: class AuthenticationBackend(ModelBackend): def authenticate(self, request, **credentials): ret = None if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: ret = self._authenticate_by_email(**credentials) elif app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.USERNAME_EMAIL: ret = self._authenticate_by_email(**credentials) if not ret: ret = self._authenticate_by_username(**credentials) else: ret = self._authenticate_by_username(**credentials) return ret def _authenticate_by_username(self, **credentials): username_field = app_settings.USER_MODEL_USERNAME_FIELD username = credentials.get("username") password = credentials.get("password") User = get_user_model() if not username_field or username is None or password is None: … -
django response method POST don't render to the html template
I have two request function in views one is with .get method and the other one with .post. Both of the function works properly because in the the terminal the code is 200. [01/Apr/2021 08:04:39] "GET /search/search HTTP/1.1" 200 4164 [01/Apr/2021 08:04:57] "POST /search/search HTTP/1.1" 200 4164 The problem comes when i try to render the function with .post method to the html template nothing appear on the html page. def wind_search(request): if request.method == 'post': city = request.post['city'] weather_city_url = urllib.request.urlopen('api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=1a7c2a40a0734d1dc18141fc6b6241bb').read() list_of_data = json.loads(waether_city_url) # main wind information wind_speed = list_of_data['wind']['speed'] # wind_gust = wea['current']['wind_gust'] wind_deg = list_of_data['wind']['deg'] # wind conversiont m/s to knots def wind_converter(w): knots = 2 kt = (float(w)) * knots return kt wind_response = wind_converter(wind_speed) #convert wind degree in cardinal direction. def degrees_to_cardinal(d): dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] ix = round(d / (360. / len(dirs))) return dirs[ix % len(dirs)] direction = degrees_to_cardinal(wind_deg) wind_data = { "wind_response":wind_response, "wind_direction":direction, } else: wind_data={} context = {"wind_data":wind_data} return render(request, 'API/wind_search.html',context) This is the html template: {% extends "API/base.html" %} {% block content %} <!--Jumbotron --> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Wind … -
'AnonymousUser' object is not iterable error when using custom context processors
I am using a custom context processor in Django. But when the user is logged in it works file but when I try to login the user it throws 'AnonymousUser' object is not iterable Here is the error: TypeError at / 'AnonymousUser' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: TypeError Exception Value: 'AnonymousUser' object is not iterable And the context_processers file looks like def noti_count(request): count1 = Notification.objects.filter(user=request.user, seen=False) count2 = Notification_general.objects.filter(seen=False) return {"count1": count1, 'count2':count2,} And the Context Processors Looks like TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'home.context_processors.noti_count', 'django.contrib.messages.context_processors.messages', ], }, }, ] Please help me out the code works fine for logged in user but when they they try to go to login page after the logout It throws me 'AnonymousUser' object is not iterable -
Nested Bootstrap modal creates an unwanted scrollbar in the middle of the page
I'm working with a Modal and its body consists of another Modal. The body of the inner modal is a Django / Crispy form. When the inner modal opens the form, it displays an unnecessary scrollbar in the middle of the page. I was unable to find a way to disable the scrollbar. Outer modal trigger button: When "New Transaction" is pressed: When "Add Debit" is pressed: The reason for a nested modal is that there will be multiple transaction options added, for example, Add Debit (Currently displayed), Add Credit, Fund Transfer, Standing Order, Recurring Income etc. Code: <!-- New Transaction Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-transaction-modal-lg">New Transaction</button> <div class="modal fade bd-transaction-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">New Transaction</h5> </div> <div class="modal-body"> <!-- NESTED MODALS --> <!-- Debit Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-debit-modal-lg">Add Debit</button> <div class="modal fade bd-debit-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Debit Transaction</h5> </div> <div class="modal-body"> <!-- Form START --> <form action="" method="POST"> {% csrf_token %} <div class="form-row"> <div class="col"> {{ debit_form.debit_name|as_crispy_field }} </div> <div class="col"> {{ debit_form.debit_value|as_crispy_field }} </div> </div> </div> <div class="modal-footer"> <button … -
Django ModelForm form.is_valid is false but with no form.errors
I have problems with Django ModelForm, I have the situation where form.is_valid() = false but with no form.errors. That's why I'm getting no updates in the database. This is what I have: #views.py def blog_update(request, slug): obj = get_object_or_404(BlogPost, slug=slug) form = BlogModelForm(request.POST or None, instance=obj) print(obj.content, obj.title) print(request.POST) print (len(form.errors)) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() form = BlogModelForm() template_name = 'form.html' context = {"form": form, "title": f"Update {obj.title}"} return render(request, template_name, context) # forms.py class BlogModelForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'slug', 'content'] # form.html {% extends 'base.html' %} {% block content %} <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> {% endblock %} I hope you can help me to find where the problem is. Thanks in advance -
How to write raw query and display result in listView in DRF
How can I write the raw query in DRF to get the list of the result? I have tried by my way but the problem is I don't this its returning what the query result. My code is: serlializers.py class MQTTFeedDataSerializer(serializers.ModelSerializer): class Meta: model = models.FeedDataValues fields = ('id','sensor','hardware_id','field1','field2','received_at',) views.py class MQTTGetAvgValue(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser, permissions.IsAuthenticated,) def get(self, request): queryset = models.FeedDataValues.objects.raw(' select id, hardware_id, Avg(CAST(field1 as DECIMAL(4,2))) as field1, strftime(\'%m\', received_at) as month, strftime(\'%Y\', received_at) as year from mqtt_FeedDataValues where hardware_id = \'XXXXXXXXX\' group by month, year;') serializer = serializers.MQTTFeedDataSerializer(queryset, many=True) return Response(serializer.data) Any suggestions will be of great help. -
Error when passing Javascript Variable to Django URL
I am trying to redirect to a URL using Django and a Value that I get after a user clicks a radio button. The code is rendered in overview.html and i get the following error when rendering it: Reverse for 'overview-office' with keyword arguments '{'year': 2021, 'month': 3, 'day': 20, 'office_id_from_filter': ''}' not found. 1 pattern(s) tried: ['overview/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/office/(?P<office_id_from_filter>[0-9]+)$'] Please see code below: $('input[type="radio"][id=office-radio]').change(function () { var redirect_value = this.value; var new_url = "{% url 'overview-office' year=day1.year month=day1.month day=day1.day office_id_from_filter=office_id %}".replace(/office_id/, redirect_value.toString()); window.location.replace(new_url) }); Can someone help me to debug? I think the reason is that the string replacement does not work properly... Thanks a lot! -
Disable collectstatic command when deploying Django App to Azure via Github
This is an error that has been giving me countless problems and unfortunately, there is no documented way around it. I have a Django APP that is running on Azure. I push local changes to Github and through Github actions, the changes are synced to Azure. This has been going on well without any trouble with the build/Deploy processing succeeding. Trouble came when I created a storage account for the media files and static files on Azure using django-storages[Azure]. So, everytime I pushed changes from localhost to Github, the build/deploy process from Github to Azure will run and manage to run the collectstatic command which unfortunately fails due to unknown error. Running collectstatic from SSH terminal on my Azure portal succeeds albeit after taking like forever, So, I am assuming that it is because of the process taking long that ends up failing. I do not need this process to run every time I make changes to the site because I can do so from the SSH terminal when there is a need. I have read from the documentation and most of them recommend setting the value DISABLE_COLLECTSTATIC = 1 to disable the process. However, I don't know how to … -
Why do I get 403 forbidden when using axios and django with CORS
I try to perform login + another POST request with axios and it seems that it works well if i use the same host ( i.e. localhost to localhost, or 127.0.0.1 to 127.0.0.1) but not when going from localhost -> 127.0.0.1 or vice versa. Please assist me finding what am I missing in my configuration, server settings: ALLOWED_HOSTS = [] REMOVE_SLASH = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:19006", "http://127.0.0.1:19006" ] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] client usage: let APIKit = axios.create({ withCredentials: true, baseURL: 'http://127.0.0.1:8000', timeout: 10000, }); APIKit.post("/user?action=login", {...}) APIKit.get('/requests/') Login succeeds but server sends new csrf token, which is ignored in axios as you can see in the following pictures, and thus receiving 403 Forbidden Login request headers : true Access-Control-Allow-Origin: http://localhost:19006 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Set-Cookie: csrftoken=Huur0KQgFMtokszTOUa1gGaWJNODn8blYvjfEO2UGnuyN75hWy1cZLVTaND2ypZ9; expires=Thu, 31 Mar 2022 08:03:39 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=r6alaupw0484mreqt8r4vlqe17hxdjsc; expires=Thu, 15 Apr 2021 08:03:39 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax POST /user?action=login HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Content-Length: 49 sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99" Accept: application/json, text/plain, */* sec-ch-ua-mobile: ?0 User-Agent: Mozilla/5.0 (Macintosh; Intel … -
Django inserting a user_id (ForeignKey) while submitting a form
Im struggling to figure out how can I update a model that has a ForeignKey. I have a User model called Companies and a CompaniesProfile model that has a user field set as a ForeignKey of the Companies model: class Companies(User, PermissionsMixin): company = models.TextField(max_length=100, unique=True) tel = models.TextField(max_length=20) reg_nr = models.TextField(max_length=50, unique=True) vat = models.TextField(max_length=50) class CompanyProfile(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) logo = models.ImageField(blank=True) street = models.TextField(max_length=256) city = models.TextField(max_length=36) postal_code = models.TextField(max_length=16) country = models.TextField(max_length=36) When the Company is register it can create a profile CompanyProfile. I have a form for that: class CompaniesProfileForm(forms.ModelForm): class Meta: model = CompanyProfile fields = ('street', 'city', 'postal_code', 'country', 'logo') and a view: class CreateProfile(CreateView, LoginRequiredMixin): template_name = 'companies/profile.html' form_class = CompaniesProfileForm success_url = reverse_lazy('home') Whenever the form in the view is submitted I get an error "integrityError at /companies/profile/ NOT NULL constraint failed: companies_companyprofile.user_id" I'ts probably because the user field is empty. My question is how to fill the user automatically based on which user currently is logged in. urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(template_name='companies/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('create/', views.CreateAds.as_view(), name='ads_create'), path('profile/', views.CreateProfile.as_view(), name='profile_create'), ] -
How to sorted the list of model instance by number of an other related model in django REST?
I have 2 models is Product and Watch. A Product may have multiple Wacht. When I call the API to get the list of products. I want to provide a feature for ordering the products by a number of watches that each product has like below. domainname/products/?ordering=numberOfWatch Here is my model class Product(models.Model): # product model fields and Wacht model class Watch(models.Model): product = models.ForeignKey( Product, related_name='watches', on_delete=models.CASCADE, ) # other fields and the ProductList View class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() permission_classes = (IsAuthenticated, IsAdmin,) name = 'product-list' filter_fields = ('category', 'brand', 'seller') search_fields = ('name',) ordering_fields = ('-updated_at', 'price', 'discount_rate', 'discount') ordering = ('-updated_at',) I'm thinking of add watch_count field in Product model and ordering for that field. But is that a good way to get what I need? -
Django forms vs HTML forms
when i use the Django {{ forms }} the forms i rendered with the build in functionalities, if user submits and fields are invalid the invalid fields are cleaned but rest of the information in the form is not cleaned, this provides the user to change only the fileds where error is raised. When i use HTML forms on submit if there is a error all the fields are cleaned and the user has to write all the information over again from scratch. How can i accomplish the same fuctionality in a html form as in Django {{ forms }} -
Best Way to integrate React with Django
My Question is that What will be the best way to integrate React App into Django project. React => Front-end Django => Backend i see there are 2 Options to do this: Keep Front-end and Back-end Separate and use API between them. Put front-end code into Django Project and link this projects template and static files in my_project/settings.py file. and run command "npm run build" every time when I made changes. What will be the best way?? -
What is the purpose of sending instance.title as second argument in validated_data.get function in DRF serializer update function
def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.date = validated_data.get('date', instance.date) instance.save() return instance What is the purpose of sharing instance.title etc in second argument of "validated_data.get" function instance.title = validated_data.get('title', instance.title) -
Django CSRF error on file upload view (CSRF verification failed. Request aborted.)
I'm trying to build a page with an upload form in Django and the GET request works fine but when I send the file I get the following error: CSRF verification failed. Request aborted. My view is very simple: class ImportView(generic.FormView): template_name = 'assignments/import.html' form_class = ImportForm success_url = reverse_lazy('assignment_import') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): # handle upload here assignments = pd.read_excel(request.FILES['file'].file) for i, assignment in assignments.iterrows(): assignment_obj = Assignment() assignment_obj.name = assignment['name'] assignment_obj.save() return self.form_valid(form) else: return self.form_invalid(form) And the form template (assignments/import.html): <h2>Import assignments</h2> {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} <form class="post-form assignments-import" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row flexibel" style="clear: left;"> <div class="col">{{ form.file|add_class:form.file.name|as_crispy_field }}</div> </div> <button class="save btn btn-success" type="submit">Assignment</button> </form> In my settings.py I have (the relevant parts): BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv('DJANGO_SECRET', default='...') DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.example.com'] MAPS_URL = os.getenv('MAPS_URL', default="https://www.example.com") DOMAIN_NAME = os.getenv('DOMAIN_NAME', default=".example.com") # Production settings CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = True DATA_UPLOAD_MAX_MEMORY_SIZE = True DATA_UPLOAD_MAX_NUMBER_FIELDS = True FILE_UPLOAD_MAX_MEMORY_SIZE = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = DOMAIN_NAME SECURE_REDIRECT_EXEMPT = DOMAIN_NAME SESSION_COOKIE_DOMAIN = DOMAIN_NAME … -
How to upload multiple different images in django with their associated names, basically creating a database of images associated with their names
I need to upload various images with their associated names and display them in django. I am doing this manually using admin window but its a nightmare since the number of image is huge. Is their any other way of uploading multiple images all at once using some python code? I already have a file containing all of the images that i need to upload. -
django-rest-framwork: AttributeError, 'Response' object has no attribute 'title'
AttributeError: Got AttributeError when attempting to get a value for field title on serializer QuestionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Response instance. Original exception text was: 'Response' object has no attribute 'title'. models.py class Question(models.Model): title = models.TextField(null=False,blank=False) status = models.CharField(default='inactive',max_length=10) created_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL) def __str__(self): return self.title class Meta: ordering = ('id',) urls.py urlpatterns = [ path('poll/<int:id>/', PollDetailsAPIView.as_view()), ] serializers.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields =[ 'id', 'title', 'status', 'created_by' ] views.py class PollDetailsAPIView(APIView): def get_object(self, id): try: return Question.objects.get(id=id) except Question.DoesNotExist: return Response({"error": "Question does not exist"}, status=status.HTTP_404_NOT_FOUND) def get(self, request, id): question = self.get_object(id) serializer = QuestionSerializer(question) return Response(serializer.data) on postman, i am trying to get an id that doesnt exist but instead of getting this response "error": "Question does not exist" and an Error: 404, i keep getting error 500 Internal server error. -
Hi trying to figure out the apscheduler library. Please help me figure it out
I need to get the last week of products and send email to subscribers using apscheduler it`s only for test class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') tags = models.ManyToManyField(Tag) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=150) slug = models.SlugField(max_length=150, unique=True) description = models.TextField(default=True) price = models.DecimalField(max_digits=10, decimal_places=2) is_active = models.BooleanField(default=True) create_date = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', kwargs={'pk': self.pk}) -
ImportError: cannot import name 'create_new_ref_number' from 'utils' in Django Rest Framework
I tried to create a random unique string in a charfield using create_new_ref_number() but it is giving me above error. I have already installed utils==1.0.1 and my django version is 2.2, as utils package are only allowed in lower django version. The full error is : ImportError: cannot import name 'create_new_ref_number' from 'utils' (C:\Users\User\Desktop\RupseOnline\rupseonline\myvenv\lib\site-packages\utils_init_.py) My model is: from utils import create_new_ref_number class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True orderItem_ID = models.CharField(max_length=12,unique=True,default=create_new_ref_number()) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) The issue arises when I try to run makemigrations. -
Preview image before upload with js
I am building a BlogApp and I am stuck on a Problem. What i am trying to do:- I am trying to preview image before upload. I am using cropping feature to crop the Image but I also want to preview cropped image before Upload too. template.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} <label for="id_file" class="mr-3 btn"><i class='fas fa-camera-retro'></i> Photo</label> <input type="file" name="file" id="id_file" style='display:none;'> <div class="modal fade" id="modalCrop"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Crop the photo</h4> </div> <div class="modal-body"> <img src="" id="image" style="max-width: 100%;"> </div> <div class="modal-footer"> <div class="btn-group pull-left" role="group"> <button type="button" class="btn btn-default js-zoom-in"> <span class="glyphicon glyphicon-zoom-in"></span> </button> <button type="button" class="btn btn-default js-zoom-out"> <span class="glyphicon glyphicon-zoom-out"></span> </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Go Back</button> <button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button> <button type="button" class="btn btn-primary js-crop-only">Select this image</button> <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js" integrity="sha384-SlE991lGASHoBfWbelyBPLsUlwY1GwNDJo3jSJO04KZ33K2bwfV9YBauFfnzvynJ" crossorigin="anonymous"></script> </div> </div> </div> What have i tried:- I saw many answers and found many answers but they didn't work for me. I also tried this :- document.getElementById("files").onchange = function () { var reader = new FileReader(); reader.onload = function (e) { // get loaded data and render thumbnail. document.getElementById("image").src = e.target.result; }; // … -
What is the best methode for check if only one dataset field is true
I have in Django this model: class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... Is_Default_Shipping_address = models.BooleanField(default=True, blank=True, null=True) Is_Default_Billing_address = models.BooleanField(default=True, blank=True, null=True) ... def __str__(self): return str(self.ID) How can I check if I add another address that is just one entry is Is_Default_Shipping_address or/and Is_Default_Billing_address is true? The customer may have two or more addresses, but he has in the most scenarios just one billing address which is always default. The best way is if customer adds another address which has the flag default and set the new also as default, the flag from the other entry will be removed. regards.