Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check all forms then call save methd - django dynamic form
i've created a page which has a formset, i want to check all forms if they have error, then call save method, but create() automatically call save method! is there away to prevent it please ? here is my views.py def addNewGuestPopup(request): if request.method == "POST": form_no = int(request.POST.get('form_no')) removed_form = request.POST.get('removed_form').split(",") error_form_exits = [] new_guests = [] for i in range(form_no): if str(i) not in removed_form: full_name = request.POST.get('fullname-'+str(i)) dob = request.POST.get('dob-'+str(i)).split("-") try: visitor = Vistor.objects.get(full_name=full_name, dob=datetime.datetime(int(dob[0]), int(dob[1]), int(dob[2]))) error_form_exits.append(i) except Vistor.MultipleObjectsReturned: pass except Vistor.DoesNotExist: visitor = Vistor.objects.create(full_name=full_name, dob=datetime.datetime(int(dob[0]), int(dob[1]), int(dob[2])), admin=request.user) new_guests.append(visitor) # return JsonResponse({'error_form':error_form}) print(len(error_form_exits)) return JsonResponse({'data':list(Vistor.objects.values_list('full_name', flat=True)), 'error_form':error_form_exits}, safe=True) return render(request, 'main/forms.html') i dont want to use django formset is there a way to prevent create from save until all forms been checked please? note : dob and full_name are unique together thank you .. -
Django session working normally locally but once deployed to Heroku they are refreshed upon every view change
The sessions work perfectly while changing views when working locally, but when deployed to Heroku it is as if the session was refreshed and all the information it contains is deleted upon every view change. I am using Heroku's Postgres Database. I have already taken a look at: Django Session Not Working on Heroku but the problem still persists. Other people are having the same problem but there is no clear answer. Here is my current settings file. Any help would be appreciated import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'e488a0185303170daa47fe1de243823fbb3db60f045e6eae' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'here goes the heroku host'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '....', '....', ] ASGI_APPLICATION = 'System.asgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'System.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'System.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db' AUTH_PASSWORD_VALIDATORS … -
201 Created - but no new object in SqLite database
I have a button that users can click on to add an object to their account. It's sent through django to my sqlite db, and in the console log there are no errors. It says "201 Created", and yet there is no new object in the database. Someone else had the same problem as me, the solution was getting rid of some methods in the serializer, but they don't specify what they got rid off. What's causing this? Here is my serializer: class RatSerializer(FlexFieldsModelSerializer, serializers.ModelSerializer): name = serializers.CharField() user = serializers.CharField(source='user.username', required=False) userid = serializers.CharField(source='user.id', required=False) body_colour = BodyColourSerializer() eye_colour = EyeColourSerializer() image = ImageSerializer(required=False) class Meta: model = rat exclude = ['bio'] def create(self, data): request = self.context.get("request") user = request.user return rat( name = data["name"], body_colour = BodyColour(name=data["body_colour"]["name"]), eye_colour = EyeColour(name=data["eye_colour"]["name"]), image = Image(), user = user) My views: class ratViewset(ModelViewSet, APIView): serializer_class = RatSerializer # queryset = rat.objects.all() def get_queryset(self): user = self.request.user if user.is_anonymous: return rat.objects.all() return rat.objects.filter(user=user.id) def post(self, request): rat = request.data.get('rat') # creates rat with the above data serializer = RatSerializer(data=rat) if serializer.is_valid(raise_exception=True): serializer.save() print(serializer.data, type(serializer.data)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status) Grateful for any help! -
django rest framework trigger goes in loop on network delay
1: I am working with django rest framework as backend and angular as frontend. I am using signals and receiver of django at many places in my project. on pre_save or post_save method i am facing a common problem. The problem is in case of network delay the requested signals gets executed more than one time. for instance, i am sending email notification to any customer using signal like this. pre_save.connect(send_new_coupon_notification_email, sender = coupon) if due to network email sending response gets delay, coupan table will created multiple records. If response is fast in that case it works fine. 2: we have two models on two server, once coupan is created on pre_save or post_save i need to create another record say in beneficiary model. as i am indicating in these two models. if Beneficiary returns acknowledge quickly than it works fine. but again in case of network delay Coupan creates multiple records. class Beneficiary(models.Model): name = models.CharField(max_length=50) coupon_code = models.ForeignKey(coupon, on_delete=models.CASCADE) miscValue = models.TextField(blank=True, null=True) def __str__(self): return self.name class coupon(models.Model): sl_no = models.CharField(max_length=50) @receiver(post_save, sender=coupon) def save_profile(sender, instance, **kwargs): Beneficiary.objects.create(name="added from reciever", coupon_code=instance) 3: In test environment this works fine as we work on LAN, but once it … -
Can't display picture on my django social app using imageField?
I need some fresh eyes, what am I missing here? In my Post Model imageField is defined as "picture" to be uploaded on the site, I seed it on my admin panel, it gets uploaded just fine but I can't seem to make it appear on the page: http://127.0.0.1:8000/posts/. I get ValueError at /posts/ The 'picture' attribute has no file associated with it. Highlited line is line 257, in post_comment_create_view return render(request, 'network/posts.html', context) Model: class Post(models.Model): # id is created automatically by Django picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])]) content = models.TextField() liked = models.ManyToManyField(Profile, blank=True, related_name="likes") author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__ (self): return str(self.content[:20]) Forms: class PostModelForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows':2})) class Meta: model = Post fields = ('content', 'picture') Views: @login_required def post_comment_create_view(request): qs = Post.objects.all() profile = Profile.objects.get(user=request.user) #Setting up pagination p = Paginator(qs, 5) page = request.GET.get('page') post_list = p.get_page(page) #Post form, comment form p_form = PostModelForm() c_form = CommentModelForm() post_added = False profile = Profile.objects.get(user=request.user) if 'submit_pForm' in request.POST: print(request.POST) p_form = PostModelForm(request.POST, request.FILES) if p_form.is_valid(): instance = p_form.save(commit=False) instance.author = profile instance.save() p_form = PostModelForm() post_added = True if 'submit_cForm' … -
Best wat to implement action button in django
I'm writing a Django app that has an action button called restart. When clicked this button should restart a service. The problem is how would I implement this I have the option to add some JavaScript to the button and call the public rest API that's contained inside the Django app. Would that be the way to go? And how can I add an endpoint to the rest API? The endpoint would look like this /API/v1/services/service_name/restart -
Python/Django "page not found" error: "The current path, ... , didn’t match any of these."
I'm learning Chapter 18 in Python Crash Course by Eric Matthes. I am using Django 4.0.1 and the book uses is 2.2.0 so I see that other people are having similar issues as me with this section. In other similar stackoverflow questions on this issue, proposed solutions using url instead of path seem also outdated. The solutions on the website therefore are unfortunately not helping me. Problem: when I open http://localhost:8000/ and I click on "topics" I get the 404 not found error as follows: Page not found (404) Request Method: GET Request URL: http://localhost:8000/(%25%20url%20'learning_logs:topics'%20%25%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='index'] topics/ [name='topics'] The current path, (% url 'learning_logs:topics' %}, didn’t match any of these. However, navigating manually to http://localhost:8000/topics shows me the page as intended. I believe this is an issue due to my urls.py located in my app folder. Here is my urls.py in learning_logs (app), where I think the issue lies: from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), #Page that shows all topics. path('topics/', views.topics, name='topics'), ] Here is my urls.py in learning_log (main project): … -
how to fix template does not exist in Django?
I am a beginner in the Django framework. I created my project created my app and test it, it work fine till I decided to add a template. I don't know where the error is coming from because I follow what Django docs say by creating folder name templates in your app folder creating a folder with your app name and lastly creating the HTML file in the folder. NOTE: other routes are working fine except the template Please view the screenshot of my file structure and error below. File Structure ERROR TemplateDoesNotExist at /blog/ Blog/index Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 4.0.1 Exception Type: TemplateDoesNotExist Exception Value: Blog/index Exception Location: C:\Python39\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\Maxwell\\Desktop\\Django\\WebApp', 'C:\\Python39\\python39.zip', 'C:\\Python39\\DLLs', 'C:\\Python39\\lib', 'C:\\Python39', 'C:\\Users\\Maxwell\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Python39\\lib\\site-packages', 'C:\\Python39\\lib\\site-packages\\win32', 'C:\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sun, 23 Jan 2022 12:04:18 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Maxwell\Desktop\Django\WebApp\Blog\templates\ Blog\index (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\admin\templates\ Blog\index (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\auth\templates\ Blog\index (Source does not exist) App/views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request,name): return HttpResponse(f'Hello {name}') def html(request): return … -
Deploy django project with more application using Apache
I'm trying to deploy a website using Apache and mod_wsgi, my project has more applications Project/ ├── Article │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Client │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── ManagementSoftware │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Order │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Sites │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── Supplier │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ … -
Is it possible to pass extra value with celery AsyncResult while celery task is in any state (RUNNING, PENDING, SUCCESS) in Django?
Actually, I wanted to receive the dictionary while the celery task is in running state For example: task = app.AsyncResult(task_id) response_data = task.get() print(response_data['key']) -
django rest framework and swagger : invalid literal for int() with base 10: 'None'
When I use rest_framework_swagger, I face some errors. as you can see it's more about library and port. is there something wrong about my other views? how can i fix it? here is my code : from rest_framework_swagger.views import get_swagger_view from . import views schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ path('', schema_view), ] and I face this is error which is about type of port which is none: Traceback (most recent call last): File "/home/alireza/anaconda3/lib/python3.7/site-packages/asgiref/sync.py", line 482, in thread_handler File "/home/alireza/anaconda3/lib/python3.7/site-packages/django_elasticsearch_dsl_drf/viewsets.py", line 160, in __init__ self.document._get_using() File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 109, in get_connection return self.create_connection(alias, **self._kwargs[alias]) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 84, in create_connection conn = self._conns[alias] = Elasticsearch(**kwargs) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 203, in __init__ self.transport = transport_class(_normalize_hosts(hosts), **kwargs) File "/home/alireza/anaconda3/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 52, in _normalize_hosts if parsed_url.port: File "/home/alireza/anaconda3/lib/python3.7/urllib/parse.py", line 169, in port port = int(port, 10) Exception Type: ValueError at /swagger/ Exception Value: invalid literal for int() with base 10: 'None' ```. can you help me? -
Django template websocket URL tag
I am trying to load ws_urlpatterns to template with tags: routing.py from django.urls import path from .consumers import WSConsumer ws_urlpatterns = [ path('ws/some_url/', WSConsumer.as_asgi(), name="ws"), ] <div class="container"> <div class="row"> <div class="col-6 mx-auto mt-5"> <h1>{{ text }}</h1> </div> </div> </div> <script> let socket = new WebSocket('ws://localhost:8000/ws/some_url/'); const h1 = document.querySelector('h1'); socket.onmessage = function(event){ let data = JSON.parse(event.data); h1.innerText = data.message; } </script> I tried let socket = new WebSocket("{% url 'ws' %}"); but I got Reverse for 'ws' not found. 'ws' is not a valid view function or pattern name. I am new to Django channels, will be very glad if you can give me a hand. -
How interdependent db calls handled in transaction.atomic
I have two DB calls inside the transaction.atomic() Sample codes with transaction.atomic(): result1, created = SomeModel.objects.get_or_create(**somedata) if not created: flag = SomeOtherModel.objects.filter(somemodel=result1).exists() if flag: result1.some_attr = value1 if flag else value2 result1.save() AFAIK about the transaction.atomic when my python codes do not cause an exception, so all the DB calls will be committed on the database. If any of the exceptions raised inside the block, no database operation will be committed to the database. So how is this thing handled when the DB call of one is used in the python logic to make other DB operations? Didn't find this species in the documentation, if any good source, please mention it. -
How to integrate machine learning model with Django website
I am new to Django and machine learning models. I am trying to build a simple recommendation system using item-based collaborative filtering. Where there will be a search bar where you search for a userid, it will query the database for that user and display recommendations for that user. I created a model using KNN in jupyter notebook. However, I don't know how to integrate the model with my website. Furthermore, I don't know how to connect my search input to the model and get recommendations for the searched userid. This is what I did so far. Any help would be appreciated immensely. My views.py def search_user(request): if request.method == "POST": searched = request.POST['searched'] search_result = Ratings.objects.filter(Q(UserID__name__icontains=searched)) return render(request, 'admin_panel.html', {'searched': searched}, {'search_result': search_result}) else: return render(request, 'admin_panel.html', {}) def get_recommendation(request): num_ratings = Ratings.objects.count() all_user_names = list(map(lambda x: x.UserID, Ratings.objects.only("UserID"))) all_product_ids = set(map(lambda x: x.Product_ID, Ratings.objects.only("Product_ID"))) num_users = len(list(all_user_names)) # create sparse matrix productRatings_m = sp.sparse.dok_matrix((num_users, max(all_product_ids) + 1), dtype=np.float32) for i in range(num_users): # each user corresponds to a row user_ratings = Ratings.objects.filter(UserID=all_user_names[i]) for user_rating in user_ratings: productRatings_m[i, user_rating.Product_ID] = user_rating.rating productRatings = productRatings_m.transpose() # create pivot table coo = productRatings.tocoo(copy=False) df = pd.DataFrame({'Product_ID': coo.row, 'UserID': coo.col, 'rating': coo.data}) … -
Django display images from local resource
In case I'm: at a very early stage of developing; using Chrome, which doesn't allow images from local resource, and storing my images in a local /static folder, what could be the best workaround for displaying images, other than through the {% static %} tag? I have been using {% load static %}...{% static variable/path %} in my templates, but now I'm trying to display images in the admin page, which requires a good deal of overriding, and admin templates aren't easy to find where exactly to override. Lately I tried format_html, as in: from django.contrib import admin (...) @admin.display(description='Foto') def show_foto(self): return format_html( '<img src=https://media.(...)>' ) Which works fine as long as the image resource isn't local. Also, Django tags don't seem to work inside format_html(). -
Django Unit tests can't ovveride variable from tessting when post
I need a test for update view. My update view creates folders. For tests I want to change path of the folders. I tried to change settings with override_settings decorator and with with self.settings(): statment from https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.modify_settings But when I run post in my test the folders are created according to settings of my project not test settings. The path for creating the folders in my settings is saving in variable CERTIFICATION_WORKS_ROOT. In my view I import it as from django.conf import settings and then output_path = settings.CERTIFICATION_WORKS_ROOT. For debugging I added in view print(f'output_path in view - {output_path}'), and in my test print(f'test settings - {settings.CERTIFICATION_WORKS_ROOT}'). Here is my test module: from datetime import date import os from django.test import TestCase, Client, override_settings from django.urls import reverse from django.contrib.auth.models import User from django.core.files.images import ImageFile from case.models import * TEST_WORKS_ROOT = os.path.join('/home/oleh/Documents/test_output/') @override_settings(CERTIFICATION_WORKS_ROOT=TEST_WORKS_ROOT) class TestCases(TestCase): fixtures = ['cases_test_data.json'] def setUp(self): body1 = Body.objects.get(name='body_one') body1.logo.save('uploads/logo-UC.svg', ImageFile(open('/home/oleh/Downloads/logo-UC.svg', 'rb'), 'logo-UC')) self.client = Client() # remember url to case list page self.url = reverse('update_case', kwargs={'pk': 1}) #self.url = reverse('cases') def test_form(self): user = User.objects.get(id=1) self.client.force_login(user) response = self.client.get(self.url) #print(response.url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'ЗМІНИТИ СПРАВУ') self.assertContains(response, 'Додати роботу') self.assertContains(response, 'Друк') self.assertContains(response, 'Тип договору') self.assertContains(response, … -
How to regroup result by fields?
I need to do a "stats" view on some products sold. Unfortunately, I get lost with annotate, aggregate, I can't get the desired result. I have 2 models: class SaleProduct(models.Model): name = models.CharField(_('Name'), max_length=80) price = models.FloatField(_('price')) unit = models.CharField(_("unit"), max_length=20, default="€") tva = models.FloatField(_('tva')) dlc = models.DateField('dlc') class Sale(models.Model): products = models.ManyToManyField( "sale.SaleProduct", related_name="sale_saleproducts", verbose_name=_("Products"), blank=True ) paiement_method = models.CharField(_("paiement method"), max_length=255) sale_ok = models.BooleanField(_("status"), default=True) total = models.FloatField(_("Total")) I have a table of values with 6 columns: Total Total quantity Name (of product) DLC Total per DLC Total quantity per DLC First thing I can't do: group the products by name and DLC. Indeed, each line of the table must correspond to a product with a name and a unique DLC. Once this query is correctly filtered, the first column calculates the sum of the price of the products that have the same name regardless of the DLC. The second column is the count of the products that have the same name whatever the DLC. The 3rd column is the name of the product. The 4th column is the DLC The 5th column is the sum of the price of the products that have the same name and … -
The model objects from django admin aren't connected to the backend model objects
So I'm using a $5 digital ocean droplet using ubuntu and nginix to host a django website, I followed along this this tutorial and this guide. So a part of the guide said to run gunicorn --bind 0.0.0.0:8000 myproject.wsgi from the virtual env, it worked and as a test I created a highlights object to see if it would show, it did and this is what it looked like: After which I added a gunicorn socket and completed the article till the point where it told me to run sudo ufw allow 'Nginx Full', however after I ran it, first of all, the css for the admin page was gone but the bigger concern was that after I added a few extra objects from the admin panel the changes didn't seem to be noticed by my views.py as when I displayed the contents of Highlights.objects.all() it only showed the one from above. But the admin page does show that the objects had been successfully added. Also the github repo's media folder didn't show any of the new images in them including the one uploaded from gunicorn --bind 0.0.0.0:8000 myproject.wsgi they only had the images I uploaded while in local development … -
Django siteframework, How often django create sitemap.xml file?
I have a Django siteframework to create dynamic sitemap.xml sheet. class NewsSitemap(Sitemap): changefreq = "daily" priority = 0.8 protocol = 'https' def items(self): return News.objects.all() # news objects def lastmod(self, obj): return obj.date_posted def Newstitle(self, obj): return obj.titleEnglish def location(self,obj): return '/news/'+ obj.country + '/' +obj.slug will server create sitemap file only once in a day according to above code ? If server create sitemap file each time when different user visit , it would take lot of processing power as my database is huge. -
How can we use two different serializers in a single generics.ListAPIView while overriding get_queryset() method
My Views.py class RelatedFacultyProfile(generics.ListAPIView): serializer_class = FacultyProfileGenericSerializer permission_classes = [IsAuthenticated] def get_queryset(self): helper = UserTypeHelper(self.request, path=False) if helper.user_type == 'F': queryset = Faculty.objects.filter(department=self.request.user.faculty.department) if helper.user_type == 'S': queryset = Faculty.objects.filter(department=self.request.user.student.branch) return queryset class RelatedStudentProfile(generics.ListAPIView): serializer_class = StudentProfileGenericSerializer permission_classes = [IsAuthenticated] def get_queryset(self): helper = UserTypeHelper(self.request, path=False) if helper.user_type == 'F': queryset = Student.objects.filter(branch=self.request.user.faculty.department) if helper.user_type == 'S': queryset = Student.objects.filter(branch=self.request.user.student.branch) return queryset I want to combine the querysets of these two views to generate a single JSON response which will require two different serializers So how to achieve this ? -
Function in python generate str lik that QW300
How i can write funtion in python generate sting like that "QW300" and the next string of that function QW310 -
Nested unique data entry Django rest API
I have two view-set one named as Menu and other user.The user contain a filed name as items which has nested data { "id": 30, "email": "loop@loop.com", "name": "loop", "items": [ { "id": 171, "item_name": "burger", "cost": 343 "menu": 30 } ] }, { "id": 31, "email": "as@com.com", "name": "ak", "items": [ { "id": 180, "item_name": "burger", "cost": 343, "menu": 31 }, { "id": 182, "item_name": "burger", "cost": 343, "menu": 31 } ] } Problem Now my question is how can I have only unique data in every specific user like different users can have same item_name but a single user can't have the same item_name Eg: user with name loop has an item_name : burge and also the user with name ak has an item_name : burger this case can exists but a single user can't have multiple item with the same name like ak has burger multiple time so is there any way to avoid repeated data entry in every specific user if any of the file is required pls let me know i will attach it over hear Thank You:) -
API request should take User Object as input and update the user
The task is to create an API endpoint “/updateUser” for updating the user information. The API request should take the User object as input and update the user. My model is this: class UserModel(AbstractUser): name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True, primary_key=True) phone = models.CharField(max_length=10, unique=True) gender = models.CharField(max_length=10, null=True) dob = models.DateField(null=True) username = models.CharField(max_length=50, unique=True) REQUIRED_FIELDS = [] Serializer is: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ['id','name','username','email','phone','password'] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password !=None: instance.set_password(password) instance.save() return instance url is: from django.urls import path from . views import RegisterView, UpdateUserView urlpatterns = [ path('register/', RegisterView.as_view()), path('updateUser/', UpdateUserView.as_view()) ] Now, how to create view for this which takes object as input and update it?! -
Click on a button and start Time counting on redirected page (JavaScript)
I am trying to develop a quiz app with Django. Where I want to add a functionality like this - "When the users will click on start test button, they will be redirected to the questions page, and exam time will be started". Here I am using JavaScript "setInterval" to count time. It's working on the same page, but it's not working on the redirected page. My Js code : var check = null; function printDuration() { if (check == null) { var cnt = 0; check = setInterval(function () { cnt += 1; document.getElementById("para").innerHTML = cnt; }, 1000); } } function stop() { clearInterval(check); check = null; document.getElementById("para").innerHTML = '0'; } console.log("Time counting... ... ...") Button <a href="{% url 'test' %}" class="btn btn-primary mt-5"id="btnStart" type="button" value="Start" onclick="printDuration();">Start Test</a> Redirected page code: , here time counting will be started: <h2 class="pb-5">Welcome to test page</h2> <p id="para">0</p> -
Error while exporting excel file using Django and xlwt
Working with the xlwt library for exporting Excel docs using the Django framework, the following problem appeared: invalid literal for int() with base 10: 'Name of product' I tried to use different conversions in data types, but it didn't help. I would like to know how to solve this problem, thank you for any advice. models.py: class Product(models.Model): name = models.CharField(max_length=100, null=True) quantity = models.PositiveIntegerField(null=True) category = models.CharField(max_length=50, choices=CATEGORY, null=True) def __str__(self): return f'{self.name}' views.py: def export_excel(request): response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment: filename=Expenses' + \ str(datetime.datetime.now())+'.xls' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Expenses') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns= ['Name of product', 'Category', 'Quantity'] for col_num in range(len(columns)): ws.write(row_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Product.objects.filter(owner=request.user).values_list( 'name', 'quantity', 'category') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, str(row[col_num]), font_style) wb.save(response) return response