Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: It takes a long time to filter the m2m model from the m2m-connected model by specifying the field values of the m2m model
The m2m through table has about 1.4 million rows. The slowdown is probably due to the large number of rows, but I'm sure I'm writing the queryset correctly. What do you think is the cause? It will take about 400-1000ms. If you do filter by pk instead of name, it will not be that slow. # models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) sources = models.ManyToManyField(Source) duration = models.CharField(max_length=6) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Video.objects.filter(tags__name='word').only('id').order_by('-published_at'); Query issued SELECT "videos_video"."id" FROM "videos_video" INNER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") INNER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE "videos_tag"."name" = 'word' ORDER BY "videos_video"."published_at" DESC; EXPLAIN(ANALYZE, VERBOSE, BUFFERS) QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=4225.63..4226.23 rows=241 width=24) (actual time=456.321..473.827 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Sort Key: videos_video.published_at DESC Sort Method: external merge Disk: 4504kB Buffers: shared hit=540568 read=11368, temp read=563 written=566 -> Nested Loop (cost=20.45..4216.10 rows=241 width=24) (actual time=5.538..398.841 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Inner Unique: true Buffers: … -
Python Django ERROR: 'int' object has no attribute 'lr' [closed]
I am trying to build my Keras model using TensorFlow and Keras. code is following: This Django project is to find the predictive analysis of data. This project is running live. but I am going to run it locally for militance. An issue is found that, " 'int' object has no attribute 'lr', here 'lr' is the learning rate. Admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" Build.py # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True Utils.py # train models for project with id project_id def train_project_models(project_id): # get relevant data project, df = fetch_project_data(project_id) if project is None: return None, None, None # extract list parameters dense_shape = [int(x) for x in project.dense_shape.split(',')] lstm_shape = … -
Filtering in a many-to-many relationship in Django
I have three models, here I show two: class Product(models.Model): description = models.CharField(max_length=50) price = models.IntegerField() stock = models.IntegerField() def __str__(self): return self.description # Many-to-many relations class ProductsCategories(models.Model): idProduct = models.ForeignKey(Product, on_delete=CASCADE) idCategory = models.ForeignKey(Category, on_delete=CASCADE) How can I get in the views.py file products filtered by the category number 3 for instance? I have this: products_list = Product.objects.all() Thanks in advance. -
django-bootstrap-modal-forms saving instance twice (couldn't resolve with other issues open)
I am implementing a django-bootstrap-modal-forms 2.2.0 on my django app but I am having a problem. Every time I submit the modal form, the instance is created twice. I read that it is expected to have two post requests...the issue is that I am doing a few things on the form before saving it (adding a many to many value) and as I am trying to override the save function now it ends up saving the model twice. class DirectorModelForm(BSModalModelForm): class Meta: model = Contact exclude = ['owner', 'matching_user', 'id', 'referral', 'name_surname','title','city'] class NewDirectorView(BSModalCreateView): template_name = 'action/forms/DirectorModelForm.html' form_class = DirectorModelForm success_message = 'Success: Director was created.' success_url = reverse_lazy('action:new_jobproject') def get_object(self): pk = self.kwargs.get('pk') director = get_object_or_404(Contact, pk=pk) return director def form_valid(self, form): obj = form.save(commit=False) obj.owner = self.request.user obj.save() obj.title.add(Title.objects.get(title_name='Director', title_department='Production')) return super().form_valid(form) -
Expo Push Notification not Working on Heroku App (Back End)
Expo Push Notifications are working locally. I use Django on backend. But, once the app is deployed on Heroku server, Expo Push Notifications are not working, and I get an error. The code is breaking on backend, when communicating with Expo Backend Service (when calling https://exp.host/--/api/v2/push/send). -
Django Search returning the detailed view page
in models.py class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) in views.py def index(request): entry = Person.objects.all() context = {'entry':entry} return render(request, 'searching/index.html', context) def detail(request, pk): entry = Person.objects.get(id=pk) context = {'entry':entry} return render(request, 'searching/detail.html', context) in urls.py path('name/', views.index, name='index'), path('name/<str:pk>/', views.detail, name='detail'), I am stuck, i want to make a search bar where if you search the exact id, example my model has id of 1 if i search 1 in the box it should return mysite.com/name/1 instead of getting a page with results of queries that contain the 1 i want the exact one i searched for. I have looked so hard but i can't find a solution, it seems like a simple question and i feel so dumb. Is there an easy solution that i am missing? -
How to give tabs in django admin inline?
I am using django-baton and like to give tabs inside inline, but unable to give it Here is my code for admin.py and model.py file admin.py class ContentInLine(admin.StackedInline): model = Content extra = 1 class schoolProfileAdmin(admin.ModelAdmin): # exclude = ('content',) inlines = [ContentInLine] save_on_top = True list_display = ('school_name',) fieldsets = ( ('Main', { 'fields': ('school_name', ), 'classes': ('baton-tabs-init', 'baton-tab-group-fs-multi--inline-items', 'baton-tab-group-inline-things--fs-another', ), 'description': 'This is a description text' }), ('Multiple inlines + fields', { 'fields': ('email', ), 'classes': ('tab-fs-multi', ), }), ) models.py class SchoolProfile(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True) school_name = models.CharField(max_length=255) school_logo=models.FileField(upload_to='media/', blank=True) incharge_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, blank=True) phone_num = models.CharField(max_length=255, blank=True) num_of_alu = models.CharField(max_length=255, blank=True) num_of_student = models.CharField(max_length=255, blank=True) num_of_cal_student = models.CharField(max_length=255, blank=True) #content = models.ManyToManyField(Content, blank=True, related_name='groups') def __str__(self): a = Content.objects.all() for e in a: print(e.shows_name,'************************') return self.school_name class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255) # show=models.CharField(max_length=255) show=models.ForeignKey(Show,on_delete=models.CASCADE) sponsor_link=models.CharField(max_length=255) status=models.BooleanField(default=False) added_on=models.DateTimeField(null=True) content_file=models.FileField(upload_to='media/') title = models.CharField(max_length=255) shows_name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255) description = models.CharField(max_length=500) publish_now = models.BooleanField(default=False) schedule_release = models.DateField(null=True) expiration = models.DateField(null=True) tag = models.ManyToManyField(Tag) topic = models.ManyToManyField(Topic) category = models.ManyToManyField(Category) school_profile = models.ForeignKey(SchoolProfile, on_delete=models.CASCADE,unique=True, blank=True) def __str__(self): return self.title Following is link for screenshot of admin page where i am unable to get … -
'int' object has no attribute 'lr' in python Django?
I am trying to build my Keras model using TensorFlow and Keras. code is following: This Django project is to find the predictive analysis of data. This project is running live. but I am going to run it locally for militance. An issue is found that, " 'int' object has no attribute 'lr', here 'lr' is the learning rate. Admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" Build.py # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True Utils.py # train models for project with id project_id def train_project_models(project_id): # get relevant data project, df = fetch_project_data(project_id) if project is None: return None, None, None # extract list parameters dense_shape = [int(x) for x in project.dense_shape.split(',')] lstm_shape = … -
Kindly help here, am stuck and keep getting this error. ModuleNotFoundError: No module named 'webHomePage'
Below are my Url Patterns from django.conf.urls import include from django.contrib import admin from django.urls.conf import path from.import index urlpatterns = [ path('admin/', admin.site.urls), path('',index.webhomepage,name='HomePage'), path('PublicSchools',index.webpublicschoolspage,name='PublicSchools'), path('PrivateSchools',index.webprivateschoolspage,name='PrivateSchools'), ] And this is my Function definitions from django.http import HttpResponse from django.shortcuts import render def webhomepage(request): return render(request,"HomePage.html") def webpublicschoolspage(request): return render(request,"PublicSchools.html") def webprivateschoolspage(request): return render(request,"PrivateSchools.html") This is the image to the structure of the code. [enter image description here][1] [1]: https://i.stack.imgur.com/UZM12.jpg -
Django: why does annotate add items to my queryset?
I'm struggling to do something simple. I have Item objects, and users can mark them favorites. Since these items do not belong to user, I decided to use a ManyToMany between User and Item to record the favorite relationship. If the user is in favoriters item field, it means the user favorited it. Then, when I retrieve objects for a specific user, I want to annotate each item to specify if it's favorited by the user. I made the add_is_favorite_for() method for this. Here is the (simplified) code: class ItemQuerySet(query.QuerySet): def add_is_favorite_for(self, user): """add a boolean to know if the item is favorited by the given user""" condition = Q(favoriters=user) return self.annotate(is_favorite=ExpressionWrapper(condition, output_field=BooleanField())) class Item(models.Model): objects = Manager.from_queryset(ItemQuerySet)() favoriters = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) This does not work as expected, it seems Django adds an item for every user that favorited the item. It leads to crazy things like: Item.objects.count() # 10 Item.objects.add_is_favorite_for(some_user).count() # 16 -> how the hell an annotation can return more results than initial queryset? I'm missing something here... -
What are DCC packages in programming?
enter image description here This is the requirement of a job profile of a company i want to apply in future. They're asking for having knowledge about DCC packages, but i have no idea about them. I've searched on internet but couldn't find anything. Can anyone pleaseee tell me what it is. I'd be grateful. -
Google Cloud Storage Bucket is not associated with CNAME on DNS record for using my domain as origin
I intend to use Google Cloud Storage through my own domain name supereye.co.uk . However, When I try to associate CNAME on my DNS record for supereye.co.uk with the Google Cloud Bucket production-supereye-co-uk, I get the following message when I try to access to production-supereye-co-uk.supereye.co.uk/static/default-coverpng : <Error> <Code>NoSuchBucket</Code> <Message>The specified bucket does not exist.</Message> </Error> What shall I do ? -
Stored procedure in PyODBC writes: not all arguments converted during string formatting
I have this code: with connections["mssql_database"].cursor() as cursor: sql = "EXEC SaveActivity @id_workplace=?, @personal_number=?, @id_activity=?" params = (id_workplace, personal_number, id_activity) cursor.execute(sql, params) TypeError: not all arguments converted during string formatting -
Chartjs not showing charts in my django project
I am trying to visualize data in my django project using Chartjs. right now I'm only concerned with the visualize part and not the backend stuff but for some strange reason the charts refuses to display even though I copied and pasted them directly from Chartjs website. <div id="chart_div" class="option-chart"> <canvas id="myChart" width="648" height="495"></canvas> </div> <script> const ctx = document.getElementById('myChart'); const myChart = { type : 'bar', data : { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options : { scales: { y: { beginAtZero: true } } } }; </script> As you can see from the code above. its boilerplate but I just cant get it to visualize. -
The client noticed that the server is not a supported distribution of Elasticsearch?
I am using elasticsearch (version 7.10.2 ) with python (django version 3.0) but I am getting this error The client noticed that the server is not a supported distribution of Elasticsearch While searching on the internet I found that downgrading the version of elastic search from 7.14 is was working for a lot of people as version 7.14 was updating a few internal scripts. But in my case the version is already lower than 7.14. I used curl -X GET "HTTP://localhost:9200" to check its version. Also, other such issues included NODE, Angular and other frameworks which were not relevant to my case. How can I solve this issue? If I need to downgrade then which version am I supposed to downgrade? -
TypeError: Field 'id' expected a number but got (<Group: customer>, True) DJANGO ERROR
I am learning how to use Django through a small project ... I am trying to connect my project to a Postgreslq database and I get this type of error models.py from django.db import models from django.db.models.deletion import SET_NULL from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default='profile1.png',null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name = models.CharField(max_length=200, null=True) prince = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=SET_NULL) status = models.CharField(max_length=200, null=True, choices=STATUS) date_created = models.DateTimeField(auto_now_add=True, null=True) note = models.CharField(max_length=1000, null=True) def __str__(self): return self.product.name signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User, Group from .models import Customer def customer_profile(sender, instance, created, **kwagrs): if created: group = Group.objects.get_or_create(name='customer') instance.groups.add(group) Customer.objects.create( user = instance, name = instance.username … -
(Django) HTML: Table columns are displaying vertically
I'm currently trying to display a bunch of Information of a model inside the template. Therefore I've been creating a table to show all of the information horizontally for every "previous game" in the database: <table style="height: 100%"> {% for previous_game in previous_games %} <tr> <th> {{ previous_game.name }}</th> </tr> <tr> <td> <img id="Videogame_Picture" src="{{ previous_game.image.url }}"> </td> </tr> <tr> <td> {{ previous_game.date }} </td> </tr> <tr> <td> {% load static %} <img id= "Result_Icon" src="{% static previous_game.min_req %} "></td> </tr> <tr> <td> {% load static %} <img id= "Result_Icon" src="{% static previous_game.rec_req %} " ></td> </tr> <tr> <td> PC Rig {{ previous_game.config }}</td> </tr> {% endfor %} </table> But currently all the Table columns are displaying vertically underneath instead of horizontally next to each previous game and I can't figure out why. Can you help me out here? Thanks in Advance! -
How To Create UpdateView CBV with relationship
I'm tired to find the best way for UpdateView with CBV. Im test some tutorial but always got error. Maybe someone can help me. I have 2 models. Account and UserProfile. First. I Register Account User Like This, And Extending the user in UserProfile Model. Thats Success. UserProfile models My Question is, how to Update The data ini this field ? authentication/models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.email dashboard/models.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik = models.CharField(max_length=11, blank=True, unique=True, default="") nidn = models.CharField(max_length=11, blank=True, unique=True, default="") email_alternatif = models.EmailField(_('email address'), blank=True, default="") jenis_kelamin = models.CharField(max_length=6, blank=True, default="", choices =JENIS_KELAMIN_CHOICE) tempat_lahir = models.CharField(max_length=30, blank=True, unique=True, default="") tanggal_lahir = models.DateField(null=True, blank=True) nomor_handphone = models.CharField(max_length=13, blank=True) alamat = models.CharField(max_length=255, blank=True, default="") dashboard/forms.py class UserProfil(models.Model): JENIS_KELAMIN_CHOICE = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) #Profil user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) gelar_depan = models.CharField(max_length=11, blank=True, default="") gelar_belakang = models.CharField(max_length=20, blank=True, default="") nik … -
FileField in nested serializer is holding a path, when updated throws error "The submitted data was not a file. Check the encoding type on the form."
I have created a nested serialiser and custome create and update methods in it. While POST(Create) methos i am not getting any error, but while Updating i am getting error "The submitted data was not a file. Check the encoding type on the form.". Model: class SmsModelMaster(models.Model): SRNumber = models.CharField('Request Number', max_length=50, blank=True, unique=True) SRState = models.CharField(max_length=100, choices=STATUS_CHOICES, default='Requested', blank=False, null=True, unique=False) PreviousSRState = models.CharField(max_length=100, blank=True, null=False) SRCategory_SMS = models.ForeignKey(ServiceBucket, related_name='SRCategory_SMS', blank=True, on_delete=models.CASCADE) SRName_SMS = models.ForeignKey(ServiceBucket, related_name='SRName_SMS', blank=True, on_delete=models.CASCADE) RequestType = models.CharField(max_length=100, blank=True, null=False) RequesterName = models.CharField(max_length=100, blank=True, null=False) RequestedOnBehalfOf = models.CharField(max_length=100, null=True) SMETSVersion = models.CharField(max_length=100, blank=True, null=True) TPName = models.CharField(max_length=150, null=True) Expected_Completion_Time = models.DateTimeField(default=timezone.now, blank=True, null=True) Request_Time = models.DateTimeField(default=timezone.now, null=True, blank=True) CompletionDate = models.DateField(default=timezone.now, null=True, blank=True) MetersetUseEndDate = models.DateField(default=timezone.now, blank=True, null=True) ActivitySummary = models.CharField(max_length=3000, blank=True, null=True) DocumentUpload = models.FileField(upload_to='Support_Request/SMS_Model/', default=None, null=True, blank=True) Assigned_To = models.CharField(max_length=100,blank=True, null=True) def __str__(self): return self.SRNumber class Meta: verbose_name_plural = "SMS Administrator" Serializer: class sms_adminserializer(serializers.ModelSerializer): commentdata = sms_commentserializer(many=True, required=False) metersetdata = sms_metersetserializer(many=True, required=False) devicedata = sms_deviceserializer(many=True, required=False) Expected_Completion_Time = serializers.DateTimeField(required=False) class Meta: model = SmsModelMaster fields = ('SRNumber', 'SRState', 'PreviousSRState', 'SRCategory_SMS', 'SRName_SMS', 'RequestType', 'RequesterName', 'RequestedOnBehalfOf','SMETSVersion', 'TPName', 'Expected_Completion_Time, 'Request_Time','CompletionDate', 'MetersetUseEndDate', 'ActivitySummary', 'DocumentUpload', 'commentdata', 'metersetdata', 'devicedata','Assigned_To') read_only_fields = ('Request_Time', ) def create(self, validated_data): commentdata = validated_data.pop('commentdata') metersetdata … -
Curl syntax error suspected, JSON parse error, django app
I am trying to use Django Rest Framework to allow different systems to post data to my app. I need a verification on whether or not my curl request is correct so I can investigate further. I do not have many experience with curl so I'm not sure about my syntax. curl -v -H "Content-Type:application/json" -u Admin:Admin http://192.168.2.54:8082/api/zam/ -d '{"my_id":"96/Admin/2021","data_z":"2021-04-15","data_r":"2021-04-29","status":"0","kom":"","uwg":"","products":[{"ean":"200000011111","model":"AAA","kolor_f":"KOLOR","kolor_k":"KOLOR","kolor_b":"KOLOR","symbol":"SYMBOL OF PRODUCT","qty":"15","zam_id":"138"}]}' Error I get: * Trying 192.168.2.54... * TCP_NODELAY set * Connected to 192.168.2.54 (192.168.2.54) port 8082 (#0) * Server auth using Basic with user 'Admin' > POST /api/zam/ HTTP/1.1 > Host: 192.168.2.54:8082 > Authorization: Basic QWRtaW46OWlqbm1rbzA= > User-Agent: curl/7.55.1 > Accept: */* > Content-Type:application/json > Content-Length: 258 > * upload completely sent off: 258 out of 258 bytes < HTTP/1.1 400 Bad Request < Date: Tue, 21 Dec 2021 11:34:53 GMT < Server: WSGIServer/0.2 CPython/3.10.0 < Content-Type: application/json < Vary: Accept, Cookie, Accept-Language < Allow: GET, POST, HEAD, OPTIONS < X-Frame-Options: DENY < Content-Length: 73 < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Content-Language: pl < {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}* Connection #0 to host 192.168.2.54 left intact -
Add extra value from ImportForm to model instance before imported or saved
I have the following model that I want to import: class Token(models.Model): key = models.CharField(db_index=True,unique=True,primary_key=True, ) pool = models.ForeignKey(Pool, on_delete=models.CASCADE) state = models.PositiveSmallIntegerField(default=State.VALID, choices=State.choices) then a resource model: class TokenResource(resources.ModelResource): class Meta: model = Token import_id_fields = ("key",) and a ImportForm for querying the pool: class AccessTokenImportForm(ImportForm): pool = forms.ModelChoiceField(queryset=Pool.objects.all(), required=True) This value shouls be set for all the imported token objects. The problem is, that I did not find a way to acomplish this yet. How do I get the value from the form to the instance? The before_save_instance and or similar methods I cannot access these values anymore. I have to pass this alot earlier I guess. Does someone ever done something similar? Thanks and regards Matt -
Django Integrity error from Abstractbaseuser
IntegrityError at / UNIQUE constraint failed: pages_profile.username Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: pages_profile.username How would you update an Abstractuser's custom avatar field? Specifically obj = Profile.objects.create(avatar = img) from django.shortcuts import redirect, render from .forms import UserProfileForm from .models import Profile def index(request): context = {} if request.method == "POST": form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data.get("avatar") obj = Profile.objects.create( avatar = img ) obj.save(commit=False) print(obj) return redirect(request, "home.html", obj) else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='', null=True, blank=True) forms.py from django import forms from django.core.files.images import get_image_dimensions from pages.models import Profile class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('avatar',) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not … -
How to get the value for the particular user from the anchor tag in django view?
urls.py urlpatterns = [ path('vendors/', views.loomerang_admin_vendors, name="loomerang_admin_vendors"), path('vendor_profile/<str:userid>', views.loomerang_admin_vendor_profile, name="loomerang_admin_vendor_profile"),] template {% for vendor in vendors %} <tr> <th scope="row">{{vendor.id}}</th> <td>{{vendor.date_joined|date:"d-m-Y"}}</td> <td name="vendor_id"><a href="{% url 'loomgerang_admin:loom_admin_vendor_profile' userid %}">{{vendor.userid}}</a></td> <td>{{vendor.first_name}}</td> <td>{{vendor.status}}</td> <td>20-12-2021</td> <td>Lokesh</td> </tr> {% endfor %} views.py def loomerang_admin_vendor_profile(request, userid): print(request.user.userid) vendor_name = request.POST.get("vendor_id") basic_details = CustomUser.objects.filter(id=request.user.id) store_details = basic_details[0].vendor_details.all() print(store_details) return render(request, 'loom_admin/vendor_profile.html', {'basic_details':basic_details, 'store_details': store_details}) I have shown all the details of the users as a table. If I click the Id in one row, It will redirect me to another page and get all the information the particular user has. Here I am don't know to do that. please, expecting an answer. -
{"errors":{"errors":[{"detail":"You do not have permission to perform this action.","code":"permission_denied"}]}}
When I visit http://127.0.0.1:8000/ after running python manage.py runserver inside my virtual env I got this error permission denied my Django is still in the default folder structure and no change yet I have tried to instll pip install django-cors-headers and add all the below into the setting.py file file from corsheaders.middleware import CorsMiddleware from corsheaders.middleware import CorsMiddleware CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALL_ALL =True CORS_ALLOWED_ORIGINS = [ "https://example.com", "https://sub.example.com", "http://localhost:8080", "http://127.0.0.1:9000", ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.example\.com$", ] CORS_URLS_REGEX = r"^/api/.*$" CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders' ] 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', "django.middleware.common.CommonMiddleware" ] -
Losing microseconds when inserting date to database
I have this code snippet in a view: time_from = datetime.strptime(req.POST['time_from'], "%Y-%m-%d %H:%M:%S.%f") with connections["mssql_database"].cursor() as cursor: sql_statement = "EXEC SaveActivity @TimeFrom='%s'" % (time_from) print(sql_statement) cursor.execute(sql_statement) It prints this SQL statement: EXEC SaveActivity @TimeFrom='2021-12-01 08:34:54' Microseconds are missing. They are zeros, but I need them in a database. How can I correct this?