Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local and heroku database out of sync (Django/Heroku)
I have been having challenges with my migrations from local to heroku. It appears that the schemas are out of sync. Here is my local database schema from python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict testingland [X] 0001_initial Here is the heroku schemas from heroku run python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict I believe the problem stems from deleting the migrations folder in my testingland app earlier. I ran python3 manage.py makemigrations testingland and the migrations folder came back but when I run: python manage.py makemigrations git commit -a git push heroku main … -
Overwrite django rest default validation errors handler
I am using django-rest for my back-end and want to overwrite default errors for fields. My current code looks like this. class DeckSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( "id", "title", "get_absolute_url", "description", "price", "image", "category_id", "category", "title" ) extra_kwargs = { 'title': {"error_messages": {"required": "Title cannot be empty"}}, 'image': {"error_messages": {"required": "Image cannot be empty"},} } After writing these 2 kwargs i realised i would just be repeating something that could be solved by code. By default the serializer validation returns this when the field is missing {title:"This field is required"}. Is there any way that i can overwrite the current message so it can display directly the name_of_the_field + my_message . Example {title: Title is required} I am not looking on how to write custom error message for a single field , im looking on how to write generic costum messages for every field that for example is missing or null. -
Object has no attribute for Django Foreign key reverse lookup
I have a many to one relationship between Ticket and Project. I am trying to reverse lookup to see all the tickets that belong to a specific project. class Project(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField(default='', blank=False) created_on = models.CharField(max_length=20, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='created_by') assigned_users = models.ManyToManyField(User, related_name='assigned_users') def __str__(self): return self.title class Ticket(models.Model): PRIORITY_CHOICES = [ ('Urgent', 'Urgent'), ('High', 'High'), ('Medium', 'Medium'), ('Low', 'Low') ] title = models.CharField(max_length=100, blank=True) description = models.TextField(default='', blank=True) created_on = models.CharField(max_length=20, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) priority = models.CharField(max_length=6, choices=PRIORITY_CHOICES, default='low') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tickets', null=True) history = HistoricalRecords() def __str__(self): return self.title If I try to project = Project.objects.get(id=4) print(project.tickets.all()) I get "AttributeError: 'Project' object has no attribute 'tickets'". Any ideas what I'm doing wrong? Thanks -
NoReverseMatch error with unicode characters in the URL
Here's my model: class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published')) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, allow_unicode=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') lead = RichTextField(config_name='lead') body = RichTextUploadingField(config_name='body') created_on = models.DateTimeField(auto_now_add=True) published_on = models.DateTimeField(default=timezone.now) updated_on = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') is_featured = models.BooleanField(default=False, verbose_name='Featured Post') objects = models.Manager() published = PublishedManager() featured = FeaturedManager() class Meta: ordering = ('-published_on',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.slug]) Project's urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ] and app's urls.py: app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<slug:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] And my views: class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post Here's the template: {% for post in object_list %} <p><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></p> {% endfor %} And I get this: Reverse for 'post_detail' with arguments '('فایل-gitignore-برای-پروژههای-جنگو',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] when browsing blog/. What I'm missing here? It's in the early stage of the development and first time I'm working with unicode characters in the slug. It's Django 4.0.3. -
Changing the format of a field depending on another fiel in the same model
Using Django I'm trying to change the format of a field depending on another field in the same model. I have a group of persons who give me a detail which could be in two different formats: time, or decimal. I would like to have all the results in the same table. Is that possible? This is what I tried in models.py: class Time_manager(models.Manager): def get_queryset(self): return super().get_queryset().filter(result_format='T') class Kilo_manager(models.Manager): def get_queryset(self): return super().get_queryset().filter(result_format='K') class Guest(models.Model): name = models.CharField(max_length=30) result_format=models.CharField(max_length=5, default="K") result= models.DecimalField(max_digits=6,decimal_places=2) class Guest_time(Guest): objects=Time_manager() class Meta: proxy = True def formato_resultado(self): self.resultado=models.DurationField() But when I try to add a new Guest_time I'm not able to do it. I get an error asking me to introduce a decimal data. Is there a way of doing this using the same table? -
How to download generated python docx file using Ajax
I need to get some data from my template and send it back to my Django function using ajax, create a docx file and download it Django Function def download_docx_file(request): if request.method == 'GET': language = request.GET['lang'] data = request.GET['data'] converter = {'data': 'This is the real data'} document = Document() document.add_heading(f'{language} -- {converter[data]}', 0) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response return HttpResponse("hello") AJAX $("#dwnBtn").click(function(){ $.ajax({ url : "docx/", type:"GET", data : { lang : 'lang', data:'data' }, success : function(data){ console.log(data) } }) }); I am getting sth like the below response from AJAX response: Response console.log(data) �ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�@��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$� �#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���*�J\�� ���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{ ��4&/ ��LM9�98� �&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M� how can I save this binary data as a .docx file? Thank you in advance -
Django regex start with 3 characters followed by digits
I'm trying to have a regex in djagno form to match 3 characters followed by 3 digits : XXX000 here's what I did so far : validator import re def number_code_validator(value): if not re.compile(r'^[a-zA-Z]{3}.*[0-9]{3}').match(value): raise ValidationError('Organization key format : XXX000.') form field key= forms.CharField( required=True, validators=[number_code_validator] ) yet it's not working and it accepts any value, is there something wrong with the regex ? thanks -
Django web app not work on AWS, There is a ERROR=TemplateDoesNotExist and {% extends 'index2.html' %} not working
My web app work on local server but it is not working on AWS. 1 {% extends 'index2.html' %} 2 3 {% load static %} 4 5 {% block title %} Who am I? {% endblock %} 6 {% block content %} 7 8 9 10 <section class="space-sm mt-3"> 11 <div class="container"> I am sorry it my first questioan, how can i solve this problem? -
Django - request to database Postgres (inside Django code)
Where exactly inside the Django code is the execution of a query to the postgres database? Can someone show me and explain? When I use debug, I see several database queries (in the postgres docker logs), but I know that the actual query is one (the last one). And there is no way I can catch the line of code inside Django that makes the actual request. If you can show me the script and function/method, thanks! -
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', …