Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SAVE CHECKED STATE OF CHECKBOX AFTER CLOSING THE WEBSITE
I'm working on a django project in which i have a list of checkboxes. I'd like to know how do i save the fact that the checkbox has been checked after i close the website? the checkbox's label are the values of a Model that i created. As database i'm using the default one given by django, sqlite3. here's a little snippet of my code: <ul class="list-group list-group-flush"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> {{project.description}} </label> .... </ul> -
Make, migrate model programmatically, and reload / repopulate django application's new settings / configurations
I am making a model programmatically using the following code: modelObj = type(m.get("name"), (models.Model,), m.get("attrs")) After that I am trying to run the makemigrations, migrate, and autoreload command using the following code. def migrate_and_reload(): management.call_command("makemigrations") lm = MigrationRecorder.Migration.objects.filter(app=modelObject._meta.app_label).last() management.call_command("migrate", modelObject._meta.app_label, lm.__dict__.get("name"), "--database==test") from django.utils import autoreload autoreload.restart_with_reloader() But: And, get the Message from autoreloader that the server port is already use If I comment the autoreloader then Migration is not run into the database. However, Makemigration works and a migration file is created in the app's migration folder) My basic goal is to register the dynamic model programmatically, make respective migrations (handle any errors if there), migrate it to Db, and reload the server I will prefer not to reload the server, but seems like I have no other options to reload all the settings or populate the configurations in Django 3.0.3. Any help is welcome -
Django use rowspan in DataTables
I have a problem with DataTables in Django. I want to use DataTables to show some information, and use rowspan to group information by position. Look at the code below. <table id="example" class="display" style="width:100%"> <thead> <tr> <th colspan="2">HR Information</th> <th colspan="3">Contact</th> </tr> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </thead> <tbody> {% for x in pos %} {% for y in emp %} <tr> {% if forloop.first %} <td rowspan={{emp|length}}>{{ y.position }}</td> {% endif %} <td>{{ y.salary}}</td> <td>{{ y.office}}</td> <td>{{ y.extn}}</td> <td>{{ y.mail}}</td> </tr> { % endfor %} { % endfor %} </tbody> <tfoot> <tr> <th>Position</th> <th>Salary</th> <th>Office</th> <th>Extn.</th> <th>E-mail</th> </tr> </tfoot> </table> But I got "Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined" Could you explain to me, how can I resolve this issue? Have you any idea? -
Why is the data in the serializer not shown in django?
I'm going to make four serializers and put three serializers in one serializer. However, only one of the three serializers operates normally and the other two do not. I made the structure of the three serializer almost identical, but I don't understand if only one works. Please help me solve the problem. JSON { "pk": 1, "author": { "username": "username", "email": "email", "profile": "image_link" }, # AuthorSerializer is worked "title": "title1", "text": "text1", "view": 0, # ImageSerializer is not worked "like_count": 0, # LikerSerializer is not worked "comment_count": 0, "tag": "hash tag", "created_at": "time" } serializers.py class AuthorSerializer (serializers.ModelSerializer) : profile = serializers.ImageField(use_url=True) class Meta : model = User fields = ('username', 'email', 'profile') class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image', ) class LikerSerializer (serializers.ModelSerializer) : id = serializers.IntegerField(source='liker.pk') class Meta : model = Like fields = ('id', ) class PostSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) image = ImageSerializer(read_only=True, many=True) like_count = serializers.ReadOnlyField() liker = LikerSerializer(read_only=True, many=True) comment_count = serializers.ReadOnlyField() class Meta : model = Post fields = ('pk', 'author', 'title', 'text', 'image', 'view', 'like_count', 'liker', 'comment_count', 'tag', 'created_at') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data) for … -
Issue with forms.ModelForm and ForeignKey
I am writting ToDo application with user login possibility. I want to do that, each user can see his own individual task-list. Problem - I can see the particular tasks for each user after login, but I can not add task via form in my app after adding ForeignKey to my TaskModel. I can only add task in admin panel Should I add ForeignKey - query to my form somehow? Model: from django.db import models from django.contrib.auth.models import User class Task(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) created_time = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) def __str__(self): return self.title Form: from django.contrib.auth.models import User class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' class CreateAccount(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] View: def tasks_list(request): tasks = Task.objects.filter(owner=request.user) form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'todo/base.html', context) -
MultiValueDictKeyError, when submitting the form
I am new to django and faced an unpleasant problem that I cannot solve for a couple of days, please help.Everything works for me for two forms, but when I add a third, the third form does not work, and the form with a page change is very important to me. How can I fix the error: ""? Exception Type: MultiValueDictKeyError Exception Value: 'ProfileUpdateForm-valuta' Exception Location: C:\Users\Maxim\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\datastructures.py, line 78, in __getitem__ file views.py: #from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class ProfilePage(UpdateView): model=Profile template_name="market/profile.html" form_class=UserUpdateForm second_form_class= ProfileUpdateForm third_form_class=PasswordChangeForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get(self, request, *args, **kwargs): self.object = get_object_or_404(Profile,slug=self.kwargs['slug']) ctx = self.get_context_data(**kwargs) return self.render_to_response(ctx) def get_context_data(self, **kwargs): ctx = super(ProfilePage,self).get_context_data(**kwargs) ctx['UserUpdateForm'] = self.form_class( prefix='UserUpdateForm', data = self.request.POST if bool(set(['UserUpdateForm-submit']).intersection(self.request.POST)) else None, instance=self.request.user, ) ctx['ProfileUpdateForm'] = self.second_form_class( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) ctx['PasswordChangeForm'] = self.third_form_class( prefix='PasswordChangeForm', data = self.request.POST if 'PasswordChangeForm-submit' in self.request.POST else None, user=self.request.user, ) return ctx def post(self, request, *args, **kwargs): self.object = Profile.objects.get(user__username=self.request.user) ctx = self.get_context_data(**kwargs) recalculation_of_сost(self,ctx['ProfileUpdateForm']) if ctx['UserUpdateForm'].is_valid(): return self.form_valid(ctx['UserUpdateForm']) elif ctx['ProfileUpdateForm'].is_valid(): return self.form_valid(ctx['ProfileUpdateForm']) elif ctx['PasswordChangeForm'].is_valid(): return self.form_valid(ctx['PasswordChangeForm']) return self.render_to_response(ctx) -
Adding Inline HTML Code to Wagtail Rich Text Editor
I am using Wagtail CMS to build a website. I now want to embed a link with image into a paragraph. As I use the wagtail rich text editor I am wondering if there is any way to use inline html inside the rich text editor. Greetings -
IndexError at /user_upload/ (list index out of range for user model)
Even though the following code works, it throws the mentioned error. This is for importing data to user model. def user_upload(request): template = "client_admin/user_upload.html" data = User.objects.all() if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.objects.update_or_create( username=column[0], first_name=column[1], last_name=column[2], email=column[3], ) context = {} return render(request, template, context) and user model is class User(AbstractUser): is_approved = models.CharField(max_length=80, choices=APPROVAL_CHOICES, default='t-2') is_member = models.BooleanField(default=False) is_premium_member = models.BooleanField(default=False) -
How to use DRF OrderingFilter inside @action view?
I can't find information on how to use OrderingFilter from django rest framework inside ModelViewSet @action, does anyone know how would i implement that? I have categories and those categories have products that i get with that action, i want to order those products with a query string. Basically i would need to know how to use it on a queryset, but i cant find any info about that. Example url: http://example.com/categories/2/get_products/?ordering=price And here is the code, thanks for any help. class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer @action(detail=True) def get_products(self, request, pk=None): categories = Category.objects.get(id=pk).get_descendants( include_self=True).values_list('product_type__id', flat=True) products = Product.objects.filter( product_type__id__in=list(categories) ) paginator = ProductPagination() paginated_products = paginator.paginate_queryset(products, request) serializer = ProductSerializer( paginated_products, many=True, context={'request': request}) return paginator.get_paginated_response(serializer.data) -
Problem while changing input value through jquery and django?
Here I have the many values but in the input values only one value(last) will be placed. I want to display all the values in the input. How can I do this ? Example. I have values like this [10,12,13,14] but in the input only one value changes. I want to place all these values in my html input value. I think I need some changes in my script. I want to do something like this. $("#input").val(data.name); views.py def attribute_values(request): attribute = Attribute.objects.get(pk=request.GET.get('pk')) values = list(attribute.attributevalues_set.all()) serializer_values = serializers.serialize('json', values) data = { 'values': serializer_values } return JsonResponse(data, safe=False) script $("#select").change(function () { var attribute_pk = $(this).val(); console.log(attribute_pk) $.ajax({ url: ' {% url 'attribute_values' %}', data: { 'pk': attribute_pk }, dataType: 'json', success: function(data) { var values = data.values; data = $.parseJSON(values); console.log(data) $.each(data, function (index, el) { var name = el.fields.name; $("#input").val(name); }) } }); }); -
adding multiple image in django model
I am trying to add multiple images to a django model, it works in admin but i am completely blank on how to show it on my template. here is what i tried, it doesn't give any error but the image doesn't show. models.py class Export_Trade_Data(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) # country_name = models.CharField('Country Name', max_length=100, default='') trade_text = models.TextField('Text for Trade Data', null=True) # date added date_added = models.DateTimeField('Date Updated', auto_now=True) def __str__(self): return "Export Trade Data" class ExportImage(models.Model): country = models.ForeignKey( BannerandInformation, on_delete=models.CASCADE, null=True) export_trade_data = models.ForeignKey(Export_Trade_Data, on_delete=models.CASCADE) export_sample_image = models.ImageField( 'Export Sample Image', upload_to='country', null=True) def __str__(self): return "Export Trade Data" views.py def country(request, country): exch_val = '' banners = BannerandInformation.objects.filter(country=country) for b in banners: country_name = b exch_r = b.exch_rate exch_cur = exch_r.split("/")[0] ######Export_Trade_Data Model####### etrds = Export_Trade_Data.objects.filter(country_id=ct_id) ######ExportImage Model####### expics = ExportImage.objects.filter(country_id=ct_id) for s in expics: etd_pic = s.export_sample_image content = { "etrds": etrds, "etd_pic": etd_pic, } return render(request, 'country/country-page.html', content) country-page.html <tbody> {% for expics in etrds %} <tr> <img src="/country/{{expics.export_sample_image}}" height="604px" width="527px" alt=""> </tr> {% endfor %} </tbody> -
Django manage.py dumpdata returns an error
Hello there! I have a Windows Home 10 (rus), Python 3.7, Django 3.1, Postgresql 12. When executing the command manage.py dumpdata returns an error. python manage.py dumpdata --traceback > db.json Traceback (most recent call last): File "manage.py", line 24, in execute_from_command_line(sys.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\commands\dumpdata.py", line 195, in handle object_count=object_count, File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers_init_.py", line 128, in serialize s.serialize(queryset, **options) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers\base.py", line 115, in serialize self.end_object(obj) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\serializers\json.py", line 54, in end_object json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) File C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\json_init_.py", line 180, in dump fp.write(chunk) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\management\base.py", line 147, in write self._out.write(style_func(msg)) File "C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xe9' in position 6: character maps to undefined The code '\se9' is Latin accented e - é (my database stores strings containing English, French and Russian words.) -
DJANGO datetime wrong on template even after timezone setup
I have a DJANGO application, and I am completely lost about times. I am located in Budapest, Hungary, my current time for these test is: 09:26 I have my timezone correctly set in settings.py ... TIME_ZONE = 'Europe/Budapest' USE_I18N = True USE_L10N = True USE_TZ = True ... Lets say I store a datetime object in my SQLite database, the admin page will show the correct time: If I query that data in a view the date is suddenly wrong. 2020-10-06 07:26:41.040463+00:00 I have read solutions that I need to activate timezone in my view, but it does not work: tzname = pytz.timezone("Europe/Budapest") timezone.activate(tzname) for i in MyObject.objects.all(): print(i.date) returns 2020-10-06 07:26:41.040463+00:00 I usually fill my templates with Ajax JS calls, so I was not able to try template filters like this: {{ value|timezone:"Europe/Budapest" }} How can I change the time so that my JsonResponse sends the correct time to my templates? -
Using firebase with django
I want to use firebase with my django project. Well I didn't find any proper documentation to connect with the firebase. Except for connecting firebase with django with pyrebase. Proper documentation I mean without using the REST API can I use firebase for my project to save the model and to make migrations. -
Django IntegrityError 'author_id' violates not-null constraint
I don't know why Django raise IntegrityError when I try to post a comment form. It forces me to defin author and halp to null=True and blank=True but I don't want to. In my project, when someone post a comment, the author and the post (halp) attached must not be null. 1st: 'author_id' violates not-null constraint 2nd: 'halp_id' violates not-null constraint models.py: class Comment(models.Model): STATE_CHOICES = [ ('open', _('Ouvert')), ('deleted', _('Supprimé')) ] halp = models.ForeignKey("Halp", on_delete=models.CASCADE) text = models.TextField() comment = models.ForeignKey("self", on_delete=models.CASCADE, related_name="comment_child", null=True, blank=True) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField(max_length=20, choices=STATE_CHOICES, default='open') is_solution = models.BooleanField(default=False) class Meta: ordering = ['halp', '-id'] def __str__(self): return self.halp.title def get_text(self): return self.text[:20] forms.py: class CommentForm(forms.ModelForm): text = forms.CharField( label='', widget=forms.Textarea(attrs={ 'class': 'form-control form-custom', 'placeholder': _('Redigez une réponse ou un commentaire...') }) ) class Meta: model = Comment fields = ['text'] views.py: class CommentCreate(LoginRequiredMixin, CreateView): model = Comment form_class = forms.CommentForm def form_valid(self, form): text = form.cleaned_data['text'] self.halp = Halp.objects.get(slug=self.kwargs['slug']) self.comment = Comment.objects.create( text=text, author=self.request.user, halp=self.halp, ) return super(CommentCreate, self).form_valid(form) def get_success_url(self, **kwargs): return reverse_lazy('forum:halp-detail', kwargs={'slug': self.halp.slug}) If anyone can help me, I think I have missed something. Thank you in advance. Best regards. -
Django: Changing directory structure and adding an apps and scripts folder
I want to optimize my django directory structure. Therefore I had a look at this structure: Best practice for Django project working directory structure This is my current structure: django_project | |--project_name # Directory created by django |-manage.py |--project-name |--__init__.py |--asgi.py |--settings.py |--urls.py |--wsgi.py |--app_1 |--__init__.py |--app_2 |--__init__.py | |--docs | |--static |--admin |--css |--fonts |--js |--images |--vendor | |--templates |--errors |--includes | |--venv # virtual enviroment | |--README.text |--requirements.txt The new structure I want to archieve is listed below. I tried to create some new folders manually, for instance creating the scripts folder with and move manage.py into it which caused an error. I would be happy about a detailed explanation because I am working with django just for a few weeks and I am not familiar with the whole functionality / python. I am still learning yet. I would like to change the following things: Scripts folder Adding a scripts folder which contains manage.py. I had a look at Using setup.py in Your (Django) Project but it wasn't quiet helpful. Apps New created apps should be inside an apps directory. Can I do this manually after I create a new app via startapp command? For instance, creating the … -
How to perform the join on multiple fields in django queryset?
Here is my models : class Picture(models.Model): picture_id = models.IntegerField(db_column='PictureID', primary_key=True) gold_item =models.ForeignKey(GoldItem,db_column="GoldItemID",related_name="pictures",on_delete=models.CASCADE) gold_item_branch = models.ForeignKey(GoldItemBranch, db_column="GoldItemBranchID", related_name="pictures", on_delete=models.CASCADE) code = models.CharField(db_column='Code', max_length=5, blank=True, null=True) class GoldItemBranch(models.Model): gold_item_branch_id = models.IntegerField(db_column='GoldItemBranchID', primary_key=True) gold_item_id = models.IntegerField(db_column='GoldItemID') gold_item_branch_name = models.CharField(db_column='GoldItemBranchName', max_length=30, blank=True, null=True) I need to perform the join operation on multiple columns in above models. The columns are gold_item_id and gold_item_branch_id I wrote the SQL Query : select * from Pictures join GoldItemBranches on Pictures.GoldItemID = GoldItemBranches.GoldItemID and Pictures.GoldItemBranchID = GoldItemBranches.GoldItemBranchID How I can do the same query in Django queryset ? -
Django - Table is not creating after migration
I want to add new functionality to my Django project on DigitalOcean server using Postgres database. The problem is that, everything works finely on local server, but on production server new table for new model is not creating. I've deleted all migration files, made migrations again, but again can't see new table on database. Please, help me to fix that problem. My exact error: relation "documents_app_employee" does not exist LINE 1: INSERT INTO "documents_app_employee" ("fin", "name", "surnam... Here are my codes: models.py: class Employee(models.Model): fin = models.CharField(max_length=10, blank=True, null=True) name = models.CharField(max_length=20) surname = models.CharField(max_length=20) def __str__(self): return self.name + " " + self.surname forms.py: class CreateEmployeeForm(ModelForm): def save(self, commit=False): employee = super(CreateEmployeeForm, self).save(commit=False) Employee.objects.create( fin = employee.fin, name = employee.name, surname = employee.surname, ) class Meta: model = Employee fields = '__all__' scripts for deleting and undo migration: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete pip3 uninstall django pip3 install -r requirements.txt python3 manage.py makemigrations python3 manage.py migrate But again getting: ProgrammingError at /employee_document relation "documents_app_employee" does not exist LINE 1: INSERT INTO "documents_app_employee" ("fin", "name", "surnam... -
Django map model data to external data
I want to map data from the https://developer.microsoft.com/en-us/graph/graph-explorer api as a data source to have the additional required data on the model. Using a computed property on the model does not work as it is going to query for each instance in the set and is too time consuming. I could not find anything on this topic, besides maybe abusing the from_db() method as an override, if this even works. TLDR; I want data from an external API on my local model -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 1: invalid continuation byte in Django
This is very possibly a duplicate, since I saw a certain amount of similar questions but I can't seem to find a solution. My problem is as stated in the description. I am working on a Django project on python 3.8.5. My professor wanted me to program a website and use PostgreSQL as db. I did use it but I always got the following error when I used python manage.py runserver. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 1: invalid continuation byte I uninstalled PostgreSQL and tryed to start a older project of mine that uses sqlite3, but it did not work and threw the same error. Following the stack trace. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run run(self.addr, int(self.port), handler, File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Startklar\PycharmProject\Modul133_Movie\venv\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Startklar\AppData\Local\Programs\Python\Python38\lib\socket.py", line 756, … -
Facial Recognition using django
I am using django to access client webcam so that facial recognition process can be done. Right now I am using django channels to transfer the frame to the server and then return the annotated frame back to the same page. const FPS = 3; chatSocket.onopen = () => { console.log(`Connected to socket`); setInterval(() => { chatSocket.send(JSON.stringify({ 'message': getFrame() })); }, 1000 / FPS); } this message is then decoded and converted to a frame so as to use Opencv and facial detection, once the predictions are made, the data is returned back to the same page using the same websocket. This process is working fine, but the final page lags way too much , is there any other option to transfer the data in real-time? -
How to convert a Django Rest Framework Request object with data to a Django HttpRequest object?
I'm new to Django world and I'm trying to build a Django application with 2 function based views wherein one function/view should be able to call the other view. The reason I'm trying to do this is to reduce avoid writing the logic again which is available in my other API. @api_view(['POST']) def PerformActionOne(request): result_one = PerformActionTwo(request) result_two = DoSomethingElse(result_one) return Response(result_two) @api_view(['POST']) def PerformActionTwo(request): # Performs some calculation and returns rest_framework.response Response with some data in it # result is a dictionary result = Calculate() return Response(result) In the above code I'm getting an error in this line result_one = PerformActionTwo(request) Error: Exception Type: AssertionError Exception Value: The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request. I tried to look it up online and read documentation but I couldn't get a solution to this. I apologize if this is a duplicate question. Any leads on this will be greatly appreciated. -
Django cors headers error because of recent documentation update
I'm trying to use django-cors-headers to add CORs to my server, but when I load the page I receive this error on the server. i think the documentation is recently updated now should we still use : CORS_ALLOWED_ORIGINS=True or the should we leave it to default? PS C:\Users\Ganesh Akshaya\Desktop\lcodev\ecom> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\ganesh akshaya\appdata\local\programs\python\python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\ganesh akshaya\appdata\local\programs\python\python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\management\base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E006) CORS_ALLOWED_ORIGINS should be a sequence of strings. System check identified 1 issue (0 silenced). and my settings.py file contains: 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', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS=True -
How to move mail to specified folder in Outlook using Django and imaplib?
Im trying to move mail to a specific folder say "Tickets". Im unable to achieve that. Trying to achieve it using imaplib with Django. This issue im facing while accessing outlook mail. For Gmail im able to add label using +X-GM-LABELS adding code snippet below. Mails are getting deleted. Thanks for any help in advance for uid in id_list: imap.store(uid,'+FLAGS', '(Tickets)') imap.store(uid,'+FLAGS', '\Deleted') -
How to solve Django Axios Ajax Bad Request Error
Have two issues First: I get the following error in the terminal when i post comment Bad Request: /post/comment/ "POST /post/comment/ HTTP/1.1" 400 37 Second: body:formData returns empty JSON(i resolved this by directly assigning the JavaScript variable that stores form body content body:content) Just want to know why formData returns empty Here is the code for my project Model: class Comment(models.Model): body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) post = models.ForeignKey('Post',related_name="post_comment",on_delete=models.CASCADE) class Meta: ordering =['-created_on'] Form class PostCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) View class PostComment(LoginRequiredMixin,FormView): form_class = PostCommentForm def form_invalid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': return JsonResponse({"error": form.errors}, status=400) else: return JsonResponse({"error": "Invalid form and request"}, status=400) def form_valid(self,form): if self.request.headers.get('x-requested-with') == 'XMLHttpRequest': form.instance.author = self.request.user post = Post.objects.get(pk=self.kwargs['pk']) form.instance.post = post comment_instance = form.save() ser_comment = serializers.serialize("json", [comment_instance, ]) return JsonResponse({"new_comment": ser_comment}, status=200) else: return JsonResponse({"error": "Error occured during request"}, status=400) Url path('post/comment/', views.PostComment.as_view(), name='post-cmt'), JavaScript Ajax using Axios.js <script type="text/javascript"> axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; function createComment(formData) { console.log("Posting Comment"); axios.post("{% url 'post-cmt' %}", { body: content }).then(function(response) { console.log(response) }).catch(function(error){ console.error("Error", error); }); } const content = document.getElementById("id_body").value const cform = document.getElementById("comment-form"); cform.addEventListener('submit', function(e){ e.preventDefault(); if(content){ let formData = new FormData(cform); …