Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest framework | TypeError: Field 'id' expected a number but got OrderedDict()
I am trying to upload a product with multiple images and have a category or a author of a product. but getting a error TypeError: Field 'id' expected a number but got OrderedDict(). Models.py## class Product(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=5000, blank=True, null=True) price = models.CharField(max_length=100, ) discount = models.CharField(max_length=100, ) length = models.CharField(max_length=100) width = models.CharField(max_length=100) depth = models.CharField(max_length=100) category = models.ForeignKey( Category, null=True, blank=True, on_delete=models.CASCADE) author = models.ForeignKey( User, editable=False, null=True, blank=True, on_delete=models.CASCADE) status = models.CharField(max_length=1, choices=statuses, default='1') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: db_table = 'products' verbose_name = 'Product' verbose_name_plural = 'Products' Serializers.py class ProductSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=False,) category = ProductCategorySerializer(many=False,) images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = ('id', 'name', 'description', 'price', 'discount', 'length', 'width', 'depth', 'status', 'images', 'category', 'author', 'created_at', 'updated_at') def create(self, validated_data): name = validated_data.get("name") description = validated_data.get("description") price = validated_data.get("price") discount = validated_data.get("discount") length = validated_data.get("length") width = validated_data.get("width") depth = validated_data.get("depth") status = validated_data.get("status") category = validated_data.get('category') # category = validated_data.pop('category') author = validated_data.get("author") # author = validated_data.pop('author') imgs = self.context.get('view').request.FILES product = Product.objects.create( name=name, description=description, price=price, discount=discount, length=length, width=width, depth=depth, status=status, category_id=category, author_id=author ) for image in imgs.values(): ProductImage.objects.create(image=image, … -
Django get_or_create then update race condition
I have the following model: class UserProductBinding: product = models.ForeignKey(Product) user = models.ForeignKey(User) purchased = models.BooleanField(default=False) liked = models.BooleanField(default=False) class Meta(object): unique_together = ['product', 'user'] Now I need a function that makes a purchase of a product by a user, which should Get UserProductBinding with corresponsing user and product, or create one if it doesn't exist Make sure "purchased" field is False Set "purchased" to True and deduct money from user's balance I'm doing it with the following code: binding, created = UserProductBinding.objects.get_or_create(product=product, user=user) if binding.purchased: raise Error() with transaction.atomic(): binding.purchased = True user.money -= price binding.save() user.save() The problem is that I have a race condition in this code. If this function is called twice in separate threads within a short time period, there is a chance that "if binding.purchased:" check will return False for both threads, hence the function will do its job twice and user's money will be deducted twice as well. select_for_update doesn't work for me, because I need to create the binding if it doesn't exist. update_or_create doesn't work either because it doesn't make sure that "purchased" field is false before making an update. Looks like using get_or_create followed by select_for_update would do the trick, … -
Django-filters - FilterSet model ... does not match queryset model ... when using Proxy model
I have a proxy model ClientAsUser which has it's own ModelViewSet and now I'm trying to setup a FilterSet. The problem is that django-filters returns this error: FilterSet model <class 'clients.models.client.ClientAsUser'> does not match queryset model <class 'users.models.user.User'> ClientAsUser has it's own manager with get_queryset method that returns only users with role=='client' class ClientAsUserFilterSet(django_filters.FilterSet): class Meta: model = ClientAsUser fields = { 'client_profile__agent': ['in', 'exact'] } class ClientAsUserViewSet(UserViewSet): queryset = ClientAsUser.objects.all() http_method_names = ['get', 'post'] permission_classes = [IsAuthenticated] serializer_class = ClientAsUserSerializer filter_backends = [DjangoFilterBackend] filterset_class = ClientAsUserFilterSet How to make it work? When I tried to change the model in FilterSet to User it returned all the users, even those that are not clients. -
What is the recommended way to deploy django app for free in prod
I have a simple django application(using a DB), I want to deploy that to a publically accessible URL. Do folks have recommendation on how to host it for free? I am hoping to deploy more pet/side projects in the future, so looking for suggestions. Heroku/DigitalOcean were top of my research, but looking to learn more. -
How do I display Images and audio in React from a Django Rest API?
how do i get the image and audio file from api in my react app. Its only displaying their location where they are saved. also tried using <img src="{{songs.image}}" alt="error"/> cant get it to work urls.py router = routers.DefaultRouter() urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include(router.urls)) , path('',TesView.as_view(), name='test ') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Student(models.Model): songName = models.CharField(max_length=1000) image = models.ImageField( upload_to="chapters") data_enrolled = models.DateTimeField(auto_now=True) audio = models.FileField(upload_to='musics' ) def __str__(self): return self.songName react folder app.js function App() { const [song, setSong] = useState([]) useEffect(() => { async function getAllSong(){ try { const song = await axios.get("http://127.0.0.1:8000/") console.log(song.data) setSong(song.data) } catch(error){ console.log(error)} } getAllSong() }, []) return ( <div className="App"> <h1>Connect js to django</h1> { song.map((songs, i)=>{ return ( <div key={i}> <h2>{songs.songName} </h2> <img src="{{songs.image.url}}" alt="error"/> <h2 > {songs.audio}</h2> </div> )}} </div>);} export default App; output -
I am getting Proxy errors after deploying to pythonanywhere
I developed a web application that uses the Omdb API to import movie data into the database using json(), I have successfully deployed this project to PythonAnywhere, and the web app runs at first glance. However when I search a movie and then try to click on said movie to import to database and review, I get this error: "HTTPSConnectionPool(host='m.media-amazon.com', port=443): Max retries exceeded with url: /images/M/MV5BMTIwMzExNDEwN15BMl5BanBnXkFtZTYwODMxMzg2._V1_SX300.jpg (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))" Can anyone tell me what the problem is and how to solve this? Also to add, when I run the application on my local machine and host, it runs successfully without any error. So I am guessing the error is from deploying. -
python success message not printing
i am trying to print a success message after an add operation in my python django project.but the success message is not printing.it prints None.below is my code.what am i doing wrong? def edit_toners_save(request): if request.method == "POST": toner_id = request.POST.get("toner_id") toner_model = request.POST.get("toner_model") toner_printer_id = request.POST.get("toner_printer") toner_printer = Items.objects.get(id=toner_printer_id) # issued_to_id = request.POST.get("issued_to") # issued_to = Prosecutions.objects.get(id=issued_to_id) total_qty = request.POST.get("total_qty") Toners_model = Toners(id=toner_id, toner_model=toner_model, toner_printer=toner_printer, total_qty=total_qty) Toners_model.save() print(messages.success(request, "done")) calc_total_qty() print(messages.WARNING) return redirect('view_toners') else: return redirect('view_toners')[![enter image description here][1]][1] -
Django type object 'Account' has no attribute 'USERNAME_FIELD' django
i tried to adding username=None didnt work Account model is for auth other models that are diffrent languge are just profile pic or date joined nothing important to the error i imagine models.py class Account(AbstractBaseUser): email= models.EmailField(verbose_name='ایمیل', max_length=60, unique=True) username = models.CharField(max_length=255, unique=True) مسکن = models.CharField(max_length=255) تاریخ_ثبت_نام = models.DateTimeField(verbose_name='تاریخ_ثبت_نام', auto_now_add=True) اخرین_ورود = models.DateTimeField(verbose_name='اخرین_ورود', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) عکس_پروفایل = models.ImageField(max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username'] def __str__(self): return self.username def get_profile_image_filenames(self): return str(self.عکس_پروفایل)[str(self.عکس_پروفایل).index(f'uploads/{self.pk})/'):] def has_perm(self,perm, obj=None): return self.is_admin def has_module_perm(self , applabel): return True -
javascript querySelector question input radio
Am working on a javascript star review for my django app, the comment is working, however my problem is that the JS code isn't picking up the input radio selector. error: Uncaught TypeError: Cannot read properties of null (reading 'value') at HTMLButtonElement. here is my JS file: text_f = document.querySelector("#add-text"); book = document.querySelector("#book"); btn = document.querySelector("#add-btn"); root = document.querySelector("#root"); star = document.querySelector("input[type=radio]:checked"); btn.addEventListener("click", () => { text = text_f.value; book = book.value; star = star.value; if (text.length != 0) { form = new FormData(); form.append("post", text.trim()); form.append("book", book.trim()); form.append("star", star); fetch("/addpost/", { method: "POST", body: form, }) .then((res) => res.json()) .then((res) => { if (res.status == 201) { add_html( res.post_id, res.username, text.trim(), star, res.post_date, ); text_f.value = ""; } }); } }); here is my html file <h2>Reviews</h2> <div class="card"> <div class="card-body my-card"> Did you read the book? Add your Review <div class="stars"> <input class="star star-5" id="star-5" value="5" type="radio" name="star"/> <label class="star star-5" for="star-5"></label> <input class="star star-4" id="star-4" value="4" type="radio" name="star"/> <label class="star star-4" for="star-4"></label> <input class="star star-3" id="star-3" type="radio" value="3" name="star"/> <label class="star star-3" for="star-3"></label> <input class="star star-2" id="star-2" type="radio" value="2" name="star"/> <label class="star star-2" for="star-2"></label> <input class="star star-1" id="star-1" type="radio" value="1" name="star"/> <label class="star star-1" for="star-1"></label> </div> <textarea … -
HTML validation error message reveals correct value unintentionally
I am trying to use an HTML number input field to validate a one-time code a user has. The one-time code is a Django model attribute under the user model, with the user object passed into the HTML template. Currently it is set up as such: <input type="number" name="auth_code" value="" min="{{user.auth_code}}" max="{{user.auth_code}}" onchange="this.setCustomValidity('')" onkeypress="this.setCustomValidity('')" oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('This authorization code is incorrect.')" required /> If the user's code is 100000, and I enter 100001, I get the oninvalid message (as expected). However, if I delete a digit (or the whole number), I get a message stating "The value must be user.authcode." Clearly I don't want this value shown. If I set any message in the onchange or oninput field other than ('') (i.e. ('Enter a code.')), I can't validate any code (correct or incorrect). I run into the "This authorization code is incorrect." message even when validating 100000. How can I get around this? -
How to make dynamic field serializer in Django RestFramework
I want to add Dynamic Field Array serializer in my drf project: My get response looks something like this: { "title": "some", "created_at": "2022-03-06T15:59:52.684469Z", "fields": [ { "id": 1, "title": "Some title?", "parent_field": 1 }, { "id": 2, "title": "Yet another fields", "parent_field": 1 } ] } This is the item detail serializer, and fields is another model serializer. I achieved this by using this code: class AnotherFieldSerializer(serializers.ModelSerializer): class Meta: model = AnotherModel fields = "__all__" class FirstSerializer(serializers.ModelSerializer): fields = serializers.SerializerMethodField() class Meta: model = FirstModel fields = "__all__" def get_fields(self, obj): serializer_context = {'request': self.context.get('request')} children = obj.fields if not children.exists(): return None serializered_children = FirstSerializer( children, many=True, context=serializer_context ) return serializered_children.data This works only for GET requests I want this to also work with POST and PUT requests. So, imagine I want to add/edit an item into my model FIRST model and add fields associated with it by just sending this JSON: { "title": "some", "created_at": "2022-03-06T15:59:52.684469Z", "fields": [ { "id": 1, "title": "Some title?", }, { "id": 2, "title": "Yet another fields", } ] } I know I can get fields from the response and loop through each item to create an instance of Another Model but … -
Trying to call Django view using AJAX
I want to call the Django view (mentioned below) using AJAX every one second to show all the messages in the room My JQuery <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> This is my JQuery code (on the browser console I keep getting an error saying $.ajax is not defined) <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : window.location.origin+"/room/{{room_name}}/"+username+"/", success: function(response){ console.log(JSON.stringify(response)); }, error: function(response){ alert(JSON.stringify(response)) } }); },1000); }) </script> This is my Django view def room(request,room_name,current_user): # print("[PROMPT] current_user :"+current_user) try: all_images = Image.objects.all() all_users = Account.objects.all() room_obj = ChatRoom.objects.get(room_name=room_name) room_user_1 = room_obj.room_user_1 room_user_2 = room_obj.room_user_2 if room_user_1.username != current_user and room_user_2.username != current_user: return redirect('chat') room_messages = Message.objects.filter(room_name=room_obj) current_user = Account.objects.get(email=str(request.user)) profile = Profile.objects.get(user=current_user) user_following = [] friends = [] for a in profile.user_has_follower.all(): if a not in friends: friends.append(a) for b in profile.user_is_following.all(): if b not in friends: friends.append(b) query = profile.user_is_following.all() for i in query: user_following.append(i) context={ 'username':current_user.username, 'room_name':room_name, 'room_user_1_username':str(room_user_1.username), 'room_user_2_username':str(room_user_2.username), 'room_messages':room_messages, 'user_following':user_following, 'friends':friends, 'all_users':all_users, 'all_images':all_images, } return render(request,"chat.html",context) except Exception as e: log_exception(request,e,view_name="room") return render(request,"error.html") This is my urlpattern for the above view urlpatterns = [ path('room/<str:room_name>/<str:current_user>/',views.room,name='room'), ] -
Django Bad file descriptor when saving resized image
I am new to Django and Python. I am attempting to resize images as they are being saved. I am getting the following error when I try to save an image: OSError at /company_profile/add_logo/ [Errno 9] Bad file descriptor. So far I haven't been able to solve this. I know there may be other errors in the code as well. The model: from django.db import models from PIL import Image import PIL from constrainedfilefield.fields import ConstrainedFileField class CompanyNavbarLogo(models.Model): date = models.DateTimeField(auto_now_add=True, null=True) title = models.CharField(default='navbar logo', max_length=50) image = ConstrainedFileField( null=True, blank=True, upload_to='company_profile/logo', content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'], max_upload_size=2097152, ) def save(self, *args, **kwargs): super().save(*args, **kwargs) image = self.image img = Image.open(self.image.path) fixed_height = 50 height_percent = (fixed_height / (img.size[1])) width_size = int((float(img.size[0]) * float(height_percent))) if img.height > 50: width_size = int((float(img.size[0]) * float(height_percent))) image = img.resize((width_size, fixed_height), PIL.Image.NEAREST) image.save(self.image) def __str__(self): return self.title The view: from django.shortcuts import render from .models import CompanyNavbarLogo from django.views.generic.edit import CreateView class CompanyLogoCreateView(CreateView): model = CompanyNavbarLogo template_name = 'company_accounts/add_logo.html' fields = ['image'] def get_success_url(self): return reverse('home') The template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="section-container container"> <h1>Add logo</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.media … -
Django Multiple User and Two tables data saving
Is my first time asking a question here, thanks for greeting me. I'm a rocky in programming. I'm working on a Student management project in Django. I want my project to have multiple user types (Admin, student, lecture). But for me I want, when the admin creates a new student/lecture it saves the student/lecture in both the User table and student/lecture table at the same time. I'm using a custom user model. Please help me I've tried but I'm getting values error, attribute error, missing value error,... I'm looking forward to your answer, thanks. Here my models.py class Student(models.Model): rn= models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, db_column="Roll_Number") fn = models.TextField(db_column="First_Name") ln = models.TextField(db_column="Last_Name") sex = models.CharField(db_column="Sex",choices=sex_choice, default='Male', max_length=20) sc = models.ForeignKey( School,related_name='departs',on_delete=models.CASCADE, db_column="Scholl_Institute") dp = models.ForeignKey( Department,on_delete=models.CASCADE, db_column="Department") year = models.ForeignKey( Year,on_delete=models.CASCADE,db_column="Year") tel = models.TextField(db_column="Telephone") em = models.EmailField(verbose_name="email", max_length=100, unique=True,db_column="Email") def __str__(self): return str(f"{self.ln} {self.fn}") def clean_rn(self): if self.instance: return self.instance.rn else: return self.fields['rn'] def get_absolute_url(self): return reverse('student:update', kwargs={'id': self.pk}) def save(self, *args, **kwargs): try: default_password = make_password(self.rn) Student.objects.create() name = f"{self.ln} {self.fn}" User.objects.create_user(username=name, email=self.em, password=default_password) User.is_student = True User.type = "Student" super(Student, self).save() except IndexError: print('IndexError') except RecursionError: print('RecursionError') class Lecture(models.Model): lid= models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,db_column="Lecture_Id") fn = models.TextField(db_column="First_Name") ln = models.TextField(db_column="Last_Name") sex … -
Cross domain cookie not being sent in the subsequent request even when it is set in the last response
I have my app at app.exampledomain.com which is in reactjs(axios for api call) and it is consuming api from api.exampledomain.com. in the response to an api call the server at api.exampledomain.com is setting the cookie in the response header like: sessionid=fyytiannsv29edvn4zgkr1orfcfscyh3; expires=Sat, 26 Mar 2022 14:02:49 GMT; HttpOnly; Max-Age=604800; Path=/ but in the subsequent requests from app.exampledomain.com the cookie is not being sent in the request header and again set cookie is received in the response header. moreover, the cookie that api sets is not visible in the cookies tab of the browser. I think the browser is rejecting the cookie sent by the server as both the client and server have different subdomains/sites (api.exampledomain.com vs app.exampledomain.com). I want to set cookies having sessionid and this sessionid to be sent in request headers cookies in subsequent requests from app to api. if i make SESSION_COOKIE_DOMAIN = '.example.com' i am able to see the cookie in the browser with domain '.exampledomain.com', still it is not being sent in the subsequent requests and new sessionid is being sent in set cookie in response headers. I tried modifying SESSION_COOKIE_SAMESITE, SESSION_COOKIE_SECURE but it did not help. -
Implementing OAuth Flow with Django+DRF+Vue with JWT
I'm trying to implement Dropbox OAuth Flow on my project, it's working fine without DRF and Vue, when i moved on Vue for my frontend, things get messy. Here are the Django views when only working with Django: (In this scenario all redirect flow happen in same page.) @login_required def dropbox_oauth2_authorize(request): return redirect(DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('driver:dropbox-callback')), # Belongs to the following view session=request.session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret=settings.DPX_APP_SECRET, locale="en", token_access_type="offline").start()) def dropbox_oauth2_callback(request): try: result = DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('driver:dropbox-callback')), session=request.session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret=settings.DPX_APP_SECRET, locale="en", token_access_type="offline").finish( request.GET) cursor = dropbox.Dropbox( oauth2_access_token=result.access_token, oauth2_refresh_token=result.refresh_token, oauth2_access_token_expiration=result.expires_at, app_key=settings.DPX_APP_KEY, app_secret=settings.DPX_APP_SECRET) ... return redirect(reverse('driver:account')) # Redirects account page where authorization started except dropbox.oauth.BadRequestException as e: raise e except dropbox.oauth.BadStateException as e: raise e except dropbox.oauth.CsrfException as e: raise e except dropbox.oauth.NotApprovedException as e: raise e except dropbox.oauth.ProviderException as e: raise e I'm managing authorization in Django with djangorestframework-simplejwt for Vue frontend. Also using axios for DRF. For managing oauth flow on backend (in DRF view), what would you suggest me to do? I tried to get dropbox authorization link via DRF view but it didn't let me open this in new tab, because of CORS headers. Here is the DRF and Vue code: @api_view(['GET']) @permission_classes([permissions.IsAuthenticated & ReadAndWritePermission]) def dropbox_acc_oauth2_authorize(request): return HttpResponseRedirect(DropboxOAuth2Flow( consumer_key=settings.DPX_APP_KEY, redirect_uri=request.build_absolute_uri(reverse('api:user_cloudaccs_dropbox_oauth2_callback', … -
django test a modelform - ValidationError not a valid UUID
I am testing a modelform and getting a ValidationError. My model, view and test are as follows: model class Course(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_name = models.CharField(max_length=30) grade_level = models.CharField(max_length=4, default="SEC") view @ method_decorator([login_required, teacher_required], name='dispatch') class CourseUpdateView(PermissionRequiredMixin, UpdateView): raise_exceptions = True permission_required = 'gradebook.change_course' permission_denied_message = "You don't have access to this." model = Course fields = ['course_name', 'grade_level', ] template_name_suffix = '_update' def get_success_url(self, *args, **kwargs): return reverse('gradebook:coursedetail', kwargs={'course_pk': self.object.pk}) form class CourseForm(ModelForm): class Meta: model = Course fields = ('course_name', 'grade_level',) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.qc = Course.objects.filter(user=user) def clean(self): super(CourseForm, self).clean() course_name = self.cleaned_data.get('course_name') if course_name and self.qc.filter(course_name__iexact=course_name).exists(): raise ValidationError("A course with that name already exists.") if len(course_name) > 20: if len(course_name) > 10: raise ValidationError( "Your course name cannot be longer than 20 characters") return self.cleaned_data Test class CourseUpdateTests(TestCase): @classmethod def setUpTestData(cls): cls.user = CustomUser.objects.create_user( username='tester', email='tester@email.com', password='tester123', is_teacher=True, is_active=True, ) cls.user.save() def test_CourseUpdate_valid(self): request = HttpRequest() request.POST = { 'user': self.user, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46', 'course_name': "Science", 'grade_level': "SEC" } form = CourseForm(request.POST) self.assertTrue(form.is_valid()) The error I get: Raise exceptions.ValidationError( django.core.exceptions.ValidationError: ["“{'user': <CustomUser: tester>, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46', 'course_name': 'Science', 'grade_level': 'SEC'}” is not a valid UUID."] I have tried … -
JS - function sends 2 POST requests
I have JS function that sends POST request let username = document.querySelector('.fw-user').innerText; if (document.querySelector('.follow')) { let followButton = document.querySelector('.follow'); followButton.addEventListener('click', () => { fetch(`/follow/${username}`, { method: 'POST', }) .then(() => { window.location.reload(); }) }) } urls.py path("follow/<creator>", views.follow, name="follow") views.py @csrf_exempt @login_required def follow(request, creator): if request.method == "POST": get_acc_id = User.objects.get(username=request.user.username) get_creator_name = User.objects.get(username=creator) follow = Followers.objects.create(follower_id=get_acc_id.id, creator=get_creator_name.username) get_creator_name.followers += 1 get_creator_name.save() return HttpResponse(status=204) html <button type="button" class="follow btn btn-outline-light btn-sm">Follow</button> When i press this button, function sends 2 POST requests, instead of 1. Screenshots: Network Console -
Rebuilt indices not showing in elasticsearch
I'm using django-elasticsearch-dsl and recently added a model field to my index but could not get elasticsearch to update the index. So, I deleted the index using CURL: curl -XDELETE localhost:9200/[index] I've rebuilt and repopulated and it looks like everything was deleted, created and indexed: $ python manage.py search_index --rebuild --refresh But I'm getting a 'index_not_found_exception' when running: curl -XGET localhost:9200/[index]/ -
Reuseable form on CreateView
Trying reuse form_class in CreateView i get the error: Field 'id' expected a number but got 'cadastrar-imovel' Where: urls.py urlpatterns = [ #... path('cadastrar-imovel/',ProductCreateView.as_view(),name='product_create'), #... models.py (I use default id field), i suspect the problem is in get_absolute_urlmethod, idk... class Product(models.Model): #...commom fields def __str__(self): return self.slug or '' @property def fn_product_title_seo(self): self.product_title_seo = self.product_goal.capitalize() + " " + self.product_type + " " + self.product_status + " " + self.product_district.title() + " " + self.product_room + " dorms" return self.product_title_seo def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = self.fn_product_title_seo self.product_title = self.product_title.capitalize() self.slug = slugify(self.product_title_seo) return super().save(*args, **kwargs) forms.py class ProductForm(ModelForm): #...commom fields definitions class Meta: model = Product fields = [#...fields views.py class ProductCreateView(CreateView): form_class = ProductForm template_name = 'product_create.html' This model and form work in admin when user i logged, but i need use the same combo to create product without login user, and after all fields are filled, i gona signup that new user(is other step). All tips are welcome -
Render DjangoCKEditor in React CKEditor
I would like to know whether it is possible to render RichTextField from Django CKEditor using CKEditor from ckeditor5-react ? As far as I know, we could manually render django field in anyway as long as the name and id is the same as the form field. But I have no idea how do I replicate Django CKEditor using React CKEditor. -
Model.Form Queryset
I have a model.form which I need to apply a queryset to filter the choices available within a select field. class AnswerForm(ModelForm): class Meta: model = ProjectQuestionnaireAnswer fields = ('answer','notes') widgets = { 'answer': forms.Select(choices = Choice.objects.filter(question_id = 1),attrs={'class': 'form-control select2'}), 'notes': forms.Textarea(attrs={'class': 'form-control','placeholder': 'Add notes to question here'}), } class Choice(models.Model): question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return str(self.choice_text) I'm not sure how to write the query to only return the choices related to the question. I've tested with choices = Choice.objects.filter(question_id = 1) which does return me the choices for question 1, but need it for each question? And then how do I present this in my template? {{ form.answer.choices }} ?? Thanks -
How to get table data (including child table and sub child data) based on id which obtains from another table data? Django
views company = Company.objects.get(id = company_id) # getting input from django urls (<int:company_id>) vehicles = CompanyContainVehicles.objects.filter(company_id=company.id) # Give all rows having same id (company.id) all_vehicles = Vehicle.objects.filter(companies=company) # Gives all row with id provide by company all_vehicles_parts = VehiclePart.objects.filter(__________) # Not Working models class Company(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) description = models.TextField() class Vehicle(models.Model): vehicle_number = models.IntegerField() name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) companies = models.ManyToManyField( Company, through='CompanyVehicle', related_name='companies' ) class CompanyVehicle(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class VehiclePart(models.Model): id = models.AutoField(primary_key=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) type = models.ForeignKey(PartType, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) How do I get VehiclePart's with their Vehicle? (I think I will give all the data in a variable and we should divide it and add it with their Vehicle). Also, what can we do to access data if VehiclePart contains a child class named VehiclePartDetail? -
Unable to fetch model data in Django Async conusmers . working in channels and websockets
I am working on a chat application with channels and websockets using async programming. I am unable to get the model data / object in consumers.py but able to create one . As someone in the group sends the message , it is echoed to the whole group but not saved and thus is flushed after the page is refreshed . I want to save the message in the database as the message is sent to the group using websockets . But I am facing problem. This is my consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from chat.models import ChatMessage , ChatRoom from channels.db import database_sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.roomId = self.scope['url_route']['kwargs']['roomId'] self.room_group_name = 'chat_group_%s' % self.roomId await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self , close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] roomId = text_data_json["roomId"] roomName = text_data_json["roomName"] await self.save_message(message , username , roomId , roomName) await self.channel_layer.group_send( self.room_group_name, { 'type': 'the_message', 'message': message } ) async def the_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) @sync_to_async def save_message(self , message , username … -
Not all files called with django static appear
I have index.html file in template file and I have js, css, image, files in my static file. I am writing the codes correctly, but the site does not appear properly. Animations, images and text are not in the correct place. (In fact, the logo of the project I used to work with appears in this project. Both are called "logo.png", I think pycharm is confusing the codes. But I opened my project with Visual Studio Code, and the logo of my old project appeared again. Why is this happening? Do I need to delete something?) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] index.html <!DOCTYPE html> {% load static %} <html lang="en"> <!-- Basic --> <head> <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" type="image/x-icon"> <link rel="apple-touch-icon" href="{% static 'images/apple-touch-icon.png' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Site CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- Responsive CSS --> <link rel="stylesheet" href="{% static 'css/responsive.css' %}"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- ALL JS FILES --> <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static …