Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - AttributeError at /signup/ 'User' object has no attribute 'profile'
I implemented 2FA in my Django application however I am getting AttributeError at /signup/ 'User' object has no attribute 'profile' error when clicking submit in my SignIn form. It shows me that error occurs in six.text_type(user.profile.email_confirmed) line. I don't have any custom User model. I am using default User model. Could you please tell me wjere is the issue and how to fix it? tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() views.py from django.contrib.auth import login from django.contrib.auth.models import User from .forms import SignUpForm from django.views.generic import View from django.shortcuts import render, redirect from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from django.contrib import messages from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.utils.encoding import force_text from django.contrib import messages # Sign Up View class SignUpView(View): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = … -
PayU payment integration failed on Django
I used payu payment integrations on django using paywix. Now i faced a problem payment failed on success payment and payu not response any data about that. Payu redirect to sucess page but not response any data about payment can any one help me on this -
limiting the number of records return with getattr in django model
currently working on a billing application for multi company database. Where some data are company code dependent and some are not. to filter the data for each data model i am trying to make a generic function to filter each data model. i am using a Model level indication for each data model to know if the data is company dependent or not. my generic method is like below. def filter_Company_or_Group(dbModelName, compGroup, compId, filter = {}, ModelLevel = '', orderByField = '', recordLimit = -1, unique = False): if ModelLevel == '': ModelLevel = getdbModelLevel(dbModelName) if ModelLevel == '': ModelLevel = 'Global' q_objects = Q() modelFilter = {} if ModelLevel == 'Company': modelFilter = {'company_id' : compId} q_objects = Q(company_id = compId) if ModelLevel == 'Group': modelFilter = {'company_Group_id' : compGroup} q_objects = Q(company_Group_id = compGroup) if ModelLevel == 'Company OR Group': q_objects |= Q(company_id = compId) q_objects |= Q(company_Group_id = compGroup) if ModelLevel == 'Global' or ModelLevel == 'ANY': q_objects = Q() if filter != {}: for key, value in filter.items(): q_objects &= Q(**{key: value}) if orderByField == '' : orderByField = 'id' objList = getattr(billing.models, dbModelName).objects.order_by(orderByField).filter(q_objects) if recordLimit != -1: objList = objList[:recordLimit] return objList here method getdbModelLevel … -
Django admin doest work on production. Forbidden (403) CSRF verification failed. Request aborted
I have a problem with admin login on Production. Everything works fine on local I use httpS I've already cleaned my browser cache for several times. It doesn't help Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ALLOWED_HOSTS = ['tibrains.com'] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_REPLACE_HTTPS_REFERER = True CORS_ORIGIN_WHITELIST = ( 'https://www.tibrains.com', 'https://www.tibrains.com/admin/login/?next=/admin/', 'tibrains.com', 'www.tibrains.com' ) CSRF_TRUSTED_ORIGINS = ['tibrains.com', 'https://www.tibrains.com/admin/login/?next=/admin/', 'https://www.tibrains.com/admin/', ] CSRF_COOKIE_DOMAIN = '.tibrains.com' SESSION_COOKIE_DOMAIN = "tibrains.com" CSRF_COOKIE_SECURE=True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Nginx location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } -
AttributeError : 'super' object has no attribute 'get'
i'm creating a simple webstore, in the product template i put the order form using FormMixin. When i submit the order, and AttributeError appears saying that : 'super' object has no attribute 'get' models.py class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) views.py class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Product, name=self.kwargs['product_name']) customer = form.save() # Order.objects.create(customer=customer) instance = Order.objects.create(customer=customer) instance.product.add(product) return super(TemplateView, self) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context urls.py urlpatterns = [ path('', views.ProductListView.as_view(), name='index'), path ('products/<str:product_name>/', views.ProductDetailView.as_view(), name='product'), path('categories/', views.CategoryListView.as_view(), name='categories'), ] Here is the traceback Traceback Traceback (most recent call last): File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\utils\deprecation.py", line 119, in … -
React and Django simple jwt profile update not null error
my problem I created a user profile model that is one to one relationship to django custom user model to update the profile from react. when i click update button in my ui, it says update user profile failed. I tried changing the model to null=True and I make makemigrations and migrate for many times but it doesn't work. Thank you for your answer in advanced! My error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: profiles_userprofile.user_id [09/Dec/2021 16:00:49] "PUT /profile-api/update-profile/ HTTP/1.1" 500 198827 User profile model from django.db import models from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=30, default='') address = models.CharField(max_length=300, default='') profile_image = models.ImageField(upload_to="profile_images", default='') User profile serializer from rest_framework import serializers from .models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('phone', 'contact', 'profile_image',) User profile view class UserProfileView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = (permissions.IsAuthenticated,) def put(self, request, format=None): user = self.request.user email = user.email data = self.request.data phone = data['phone'] address = data['address'] profile_image = data['profile_image'] UserProfile.objects.filter(user=user).update_or_create( phone=phone, address=address, profile_image=profile_image) user_profile = UserProfile.objects.get(user=user) user_profile = UserProfileSerializer(user_profile) return Response({'profile': user_profile.data, "email": str(email)}, status=status.HTTP_200_OK) Update profile react actions export const update_profile = (phone, address, profile_image) => … -
Django - Time difference right way
In the following code i'm trying to get the difference between two times, if the difference is not equal to 15 minutes throw an error. I use the following way which seems to work, however i have a feeling that is not the proper way. def clean(self): cleaned_data = super().clean() start_appointment = cleaned_data.get("start_appointment") end_appointment = cleaned_data.get("end_appointment") difference = end_appointment - start_appointment if difference != '0:15:00': raise forms.ValidationError("Start appointment should have a 15 minutes difference from end appointment!") Please have a look and let me know if this is the right way. Thank you -
string concat causing 'str' object has no attribute 'object'
I have a view like below: I get the error: 'str' object has no attribute 'object' it must have something to do with my string concat - what has gone wrong :) thanks def edit_skill_plan(request): #t = skills.objects.get(skill_id='django_5158517') skillid = request.POST.get('editbut') user = request.user t = skills.objects.get(creator=user, skill_id=skillid) t.status = 'closed' t.save() # this will update only complete_date = datetime.today().strftime('%Y-%m-%d') week_num = datetime.today().strftime('%V') x = t.skill_name user = request.user points = t.points cat = t.category year = datetime.today().strftime('%Y') status = str(request.user.username) +' completed the task: ' + str(x) + ' which was worth: ' + str(points) + ' points' status.object.create(creator=user, status=status, status_date=complete_date) -
Django custom decorator with redirect and re-redirect after decorator condition has been satisfied
I am trying to build a decorator that has a similar function like the @login_required decorator in Django. However, I do not want to force a login but rather that the requesting user accepts an agreement and then after the user accepted the agreement, it should be redirected to the actual target page. The @login_required decorator appends the following to the URL, when calling the home page before authentication: ?next=/en/home/ I need the custom decorator to also be able to append and process the actual target URL. Does anyone of you know how to do that? Does Django offer any function for that? -
Is it a good way using a DjangoModelFactory and other factories in API requests?
I noticed that DjangoModelFactory has got more functionality than DRF ModelSerializers. I want to use DjangoModelFactory to create records in database in my API, but it seems no one do this. In most cases, Factories are used only for tests, not in usual code. Why? Is it a good way using them in API requests, for example? -
Django app deployed on Heroku is painfully slow on Firefox & Safari - potential causes?
I've deployed an e-commerce site app to Heroku with the static files and media photos being hosted from an Amazon S3 bucket. The app is totally smooth on Chrome and Brave (both mobile / desktop), but tends to be appallingly slow on Firefox and Safari, regardless of device. As an example, here's a screenshot of how long some of the assets took to load when opening the app via Firefox. Project link: MyShop If I run the project on local machine (also with static & media assets being loaded from S3 directly), it is still quite slow, albeit to a lesser degree. Any ideas on how to troubleshoot? -
Django using include with a dynamic view does not work
I created a view that allows me to have a dynamic slider and I render it in an html file called slider. i have a main page called test where i include this slider file, the problem is it doesn't render anything for me,it's like it doesn't see my slider view and therefore nothing is rendered, but the file is included anyway. someone can make me understand why and would you give me a hand to solve this problem? views class SlideListView(ListView): model = Slide template_name = 'slider.html' context_object_name = 'slides' def get_queryset(self): queryset = Slide.objects.all().order_by(F('ordine').asc(nulls_last=True)) #ordine con None a fine slider return queryset url path('', TemplateView.as_view(template_name="test.html")), html iclude <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">SLIDER</h1> <a href="{% url 'bo_slider' %}" class="btn btn-outline-primary">VARIE SLIDE</a> </div> <hr> <div class="row justify-content-center mt-5"> <div class="col-lg-6"> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for slide in slides %} {% if slide.attivo == True %} <!--se lo switch è on mostro la slide--> <!--aggiungo classe active alla prima in modo da farlo partire--> <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img src="{{ slide.immagine.url }}" class="d-block w-100"> {% if forloop.first %} <!--alla prima slide metto il tag h1--> <h1>{{ slide.titolo … -
Download file stored in a model with FileField using Django
I'm planning on creating a simple file upload application in Django (incorporated in some bigger project). For this one, I'm using two links: /files/ - to list all the uploaded files from a specific user, and /files/upload/ - to display the upload form for the user to add a new file on the server. I'm using a PostgreSQL database, and I'm planning to store all my files in a File model, that looks like this: class File(models.Model): content = models.FileField() uploader = models.ForeignKey(User, on_delete=models.CASCADE) My file upload view looks like this: @login_required def file_upload_view(request): if request.method == "POST" and request.FILES['file']: file = request.FILES['file'] File.objects.create(content=file, uploader=request.user) return render(request, "file_upload_view.html") else: return render(request, "file_upload_view.html") while my file list view looks like this: @login_required def file_view(request): files = File.objects.filter(uploader = request.user) return render(request, "file_view.html", {'files': files}) The problem is, I want my file_view() to display all files uploaded by a certain user in a template (which I already did), each file having a hyperlink to its download location. I've been trying to do this in my file list template: {% extends 'base.html' %} {% block content %} <h2>Files of {{ request.user }}</h2> <br> {% for file in files %} <a href="{{ file.content }}" … -
when should use regex for urls in django? [closed]
when is better and prefered to use regex in django (or drf) urls? -
Django project, data deleted from the database
I am new in web development with Django and MySQL database, I got to develop a web application with Django framework, after deployment of my project in the server. after 2 months, I noticed that data from my order table was deleted as well as the data of one user is displayed in the profile of another, I want to know what I must do as a test to know the PR eventual error and to stop the deletion of data in my database. data often deleted in the order and customer table. the ORDER model bind with a foreign key to other Model: class Order(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) created = models.DateTimeField( auto_now_add=True, verbose_name=_('Creation Date')) payed = models.DateTimeField( verbose_name=_('Payment Date'), default=datetime.now, null=True, blank=True) reference = models.IntegerField( verbose_name=_('Order Reference'), default=0, null=True, blank=True ) customer = models.ForeignKey( Customers, verbose_name=_('Customer'), null=True, blank=True, on_delete=models.CASCADE ) company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE ) class Customers(models.Model): company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE ) forename = models.CharField( verbose_name=_('First Name'), max_length=255, null=True, blank=True) GENDER = [('M', _('Male')), ('F', _('Female'))] gender = models.CharField( verbose_name=_('Gender'), max_length=1, choices=GENDER, null=True, blank=True) city = models.ForeignKey( City, verbose_name=_('City'), null=True, blank=True, on_delete=models.CASCADE ) additionalNum = models.CharField( verbose_name=_('Additional Number:'), … -
How to Build the Github Portfolio
I am a web developer and I want to build my GitHub portfolio for my Clients and remote jobs. Can anyone guide me on this? I have experience in Reactjs, Vuejs and Python Django. Should I contribute to exisitng open source projects or should I develop my own? -
Cutom Form with auto Certificate generation using django
I wanted to develop one functionality for django website. Idea: I want to create forms for categories like (event-x, event-y, etc..) through django admin and users will fill up the form through frontend. The form data will be stored in the database and it will generate pdf certificate and will send to respective users. And also should store the status of the certificate. The idea derived from google forms.. Any suggestions... -
My JQurery-AJAX code in my Django project for displaying a default value in a calculation based field fails to do so?
These are two of few models in my project: class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) package_date=models.DateTimeField(auto_now_add=True) class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) rt_number=models.CharField(max_length=15) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) receivables_date=models.DateTimeField(auto_now_add=True) I needed the approved_package in Receivables to display a default value calculated by subtracting discount from the total_package in Package. And it should all be in real time. So I wrote an AJAX code in Jquery in an HTML file and included the file in my main template. The code looks like: <script> $('select').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var textSelected = optionSelected.text(); var csr = $("input[name=csrfmiddlewaretoken]").val(); console.log(textSelected); pkg={patient:textSelected, csrfmiddlewaretoken:csr} $.ajax({ url:"{% url 'pt_name' %}", method: "POST", data: pkg, dataType: "json", success: function(data){ console.log(data); console.log(data.pkg); console.log(data.ptt); var tp=data.pkg; var ptt=data.ptt; $('#id_discount').change(function(){ console.log('tp value: ', tp); console.log('ptt value: ', ptt); var discount=document.getElementById('id_discount').value; console.log('discount value: ', discount); var approved_package=document.getElementById('id_approved_package').value; if (ptt=='CASH') approved_package=tp-discount; console.log('approved package new value: ', approved_package); }); } }); }); </script> The code runs fine in the console of the browser. It fires all the codes. It calculates the approved_package but the result still does not show up in the field … -
Parallel with Django using gevent
I'm trying to run some tasks in parallel in a Django view. Specifically, running queries from different databases at the same time. I've implemented the code, and the queries still run in series. To test, I've created simple parallel code: from gevent.pool import Pool def test(request): def run(i): print("Running " + str(i)) for j in range(1, 100000000): x = 2 / 2.2 pool = Pool(50) pool.map(run, range(1, 10)) The code also runs in series to my surprise Any idea what I'm doing wrong ? Is there some Django internal processes that blocks multi-threading ? How would I go about implementing parallel processes if gevent is not the answer ? -
how to know when an activity date has passed - django
so i'm still on my todo list and i want to know when an activity has passed so as to flag it as expired. my views.py def progress(request): activities = ToDo.objects.all() today = timezone.localtime(timezone.now()) context = { 'activities' : activities, 'today' : today, } return render(request, 'percent.html', context) in my templates i have it as: {% for activity in activities %} {% if activity.end.date < today.date %} {{activity}} <br> {% endif %} {% endfor %} i'm going to add my models.py for referencing class ToDo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) todo = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True) created = models.DateField(auto_now=True) end = models.DateField() start = models.DateField() completed = models.BooleanField(default=False) def __str__(self): return f'{self.owner} - {self.todo}' or would it be easier to add an expired boolean field to my models? i'm so confused -
How to import a object of another model (A) inside model (B) in Django?
I want to create a new object in model B when specific condition are met in Model A, I am new to Django so that I am unable to figure out how exactly I can achieve this. For example I have two models( Product and Product Variant), when specific condition on Product Variant is met then I want to calculate new object value in Product Model. My product model is like this: PRODUCT_TYPE = ( ('s', 'simple'), ('v', 'varaible') ) class Products(models.Model): name = models.CharField(max_length=250,null=True, blank=True,) slug = models.SlugField(max_length=200, unique=True,null=True) short_description = HTMLField() description = HTMLField() category = models.ForeignKey(Categories, related_name="products",on_delete=models.SET_NULL,null=True,blank=True,) brand = models.ForeignKey(Brands,on_delete=models.CASCADE, default=None, null=True, blank=True,) warranty_support = HTMLField() product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50) And my Product Attribute Model is like this: class ProductVariant(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None) managed_stock = models.IntegerField(choices=STOCK_MANAGED, default=0) stock = models.IntegerField(default=None) stock_threshold = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) sku = models.CharField(max_length= 250, default=None) sale_price = models.DecimalField(max_digits=10, decimal_places=2) sale_start_date=models.DateField(auto_now_add=False, auto_now=False, default=None) sale_end_date=models.DateField(auto_now_add=False, auto_now=False,default=None) I am trying to create regular_price and sale_price on Product model if product_type is variable and if sale_end_date is greater than today. I want to set the price from the variant which has lowest price. I tried doing … -
Django Rest Framework returning duplicate data when returning a nested json response
I have a pricing table that contains the following fields: id, date, price_non_foil, price_foil, card_id. This table holds pricing data for each card for each day. For Example: "23a6c413-7818-47a8-9bd9-6de7c328f103" "2021-12-08" 0.24 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "c51a72ab-f29f-4465-a210-ff38b15e83a1" "2021-12-05" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "17289b71-3b73-4e16-a479-25a7069a142e" "2021-12-09" 0.38 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "fa88f619-ec32-4550-9a57-c77b6e1a8e11" "2021-12-07" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "f996d6cb-7d98-415c-bd70-2fca8f4e03a5" "2021-12-06" 1.27 0.80 "2ab9aecc-ce3c-4aaa-bf3c-fe9da4bba827" "2f8c00f3-4d47-478d-a653-7d7a476e9bae" "2021-12-09" 0.43 3.33 "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" "15b20912-4103-4e08-8f91-fed820b761af" "2021-12-05" 0.66 5.08 "2e5e1d78-0818-4ecd-a8f0-37e280aaa30a" Currently there is pricing data for 5 dates for each card. I am trying to create an endpoint to return the latest 2 prices for each card using Django rest framework. I have managed to get the response to be nest under the card id, but my issue is that it returns multiple card ids, I assume based on the number of pricing data records for each card. views.py class individual_set_pricing(ListAPIView): serializer_class = SerializerSetsIndividualPricing def get_queryset(self): code = self.kwargs.get('code', None) qs = magic_sets_cards_pricing.objects.filter(card_id__set_id__code=code.upper()).values('card_id') return qs serializers.py class SerializerSetsIndividualPricing(serializers.ModelSerializer): card = serializers.SerializerMethodField('get_card') class Meta: model = magic_sets_cards_pricing fields = ['card_id', 'card'] def get_card(self, obj): date = magic_sets_cards_pricing.objects.filter(card_id=obj['card_id']).values('date', 'price_non_foil', 'price_foil').order_by('-date')[:2] return date Response [ { "card_id": "3a261180-c1b3-4641-9524-956be55bee7a", "card": [ { "date": "2021-12-09", "price_non_foil": 1.15, "price_foil": 1.54 }, { "date": "2021-12-08", "price_non_foil": 0.43, "price_foil": 1.62 } ] }, { "card_id": … -
Django ORM my ID growth non linear when save() data into model
In my django project i have a very strange behaviour from a model related to the Primary id field values in db. I have this model: class Results(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) def __str__(self): return self.device class Meta: indexes = [ models.Index(fields=['device', 'unit', 'proj_code', 'read_date']), ] well, in a .py file i save data into this table like this: try: p = Results(device=Device.objects.get(mac_id=macid), proj_code=projid, res_key=datalist[x]['key'], read_date = topic_date, unit=unit_ck) p.save() except IntegrityError as e: if 'UNIQUE constraint' not in e.args[0]: pass except ObjectDoesNotExist: pass so, data where saved in db but if i inspect the "id" field i see strange behaviours like these: |id|Others... |1 |data |2 |data |3 |data |11|data |12|data !99|data I don't know why but my id does not growth linear as i expected. Have someone experienced the same behaviour? How can i force save data with inear id growth? So many thanks in advance Manuel -
How do you change a many-to-many field for a form in django?
I don't know why the below code is not working in the def form_valid of my Modelview: lesson = Lesson.objects.all().first() for i in lesson.weekday.all(): form.instance.weekday.add(i) form.instance.save() Here, weekday is a many to many field. However, the form just saves what the user submitted for weekday, not the changed version above using lesson.weekday. I hope you guys could help me out, and please leave any questions you have. -
javascript addEventListener and click function not working for me on Anchor tag <a>
i hava also tried jquery but not worked for me i dont know why. this is my javascript code ''' var cartLinks = document.getElementsByClassName('update-cart') console.log(cartLinks) for (var i = 0; i < cartLinks.length; i++) { console.log('enterd in loop') cartLinks[i].addEventListener("click", function () { console.log('print...') var productId = this.dataset.product console.log(productId) }) } ''' this is the tag where i want to use. ''' <a href="#" data-product={{product.id}} data-action="add" data-toggle="tooltip" class ="update-cart" title="Add To Cart"><i class="ion-bag"></i></a> ''' this is how i used script in my code. ''' <body> some code some scripts <script src="{% static 'js/cart.js' %}"></script> </body> '''