Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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); … -
'WSGIRequest' object has no attribute 'owner'
I am getting this error and I can't seem to figure it out. I tried changing the middleware, but that didn't seem to work. This is the error: The serializer field might be named incorrectly and not match any attribute or key on the WSGIRequest instance. Original exception text was: 'WSGIRequest' object has no attribute 'owner'. views.py import json from django.http import JsonResponse from rest_framework import viewsets, serializers from .models import * from django.views.decorators.csrf import csrf_exempt class CreateTodoRequest(serializers.Serializer): owner = serializers.IntegerField() title = serializers.CharField() class CreateTodoResponse(serializers.Serializer): id = serializers.IntegerField() owner = serializers.IntegerField() title = serializers.CharField() @csrf_exempt def create_todo_list(request): data = CreateTodoRequest(request) params = {'owner': data['owner'], 'title': data['title']} todo = models.List.objects.create(**params) serial = CreateTodoResponse(todo) return JsonResponse(todo.data, status=200) class UpdateListRequest(CreateTodoRequest): id = serializers.IntegerField() class UpdateListResponse(UpdateListRequest): """ """ @csrf_exempt def update_todo_list(request): data = UpdateListRequest(request) params = {'owner': data['user_id'], 'title': data['title']} rows_affected = models.List.objects.filter(id=data['id']).update(**params) todo_list = models.List.objects.get(id=data['id']) serial = UpdateListResponse(todo_list) return JsonResponse(serial.data, status=200) class DeleteListRequest(serializers.Serializer): id = serializers.IntegerField() @csrf_exempt def delete_todo_list(request): data = DeleteListRequest(request) models.List.objects.filter(id=data['id']).delete() return JsonResponse(True, status=200, safe=False) class CreateTaskRequest(serializers.Serializer): title = serializers.CharField() task_list = serializers.CharField() completed = serializers.BooleanField() due_date = serializers.DateTimeField() class CreateTaskResponse(CreateTaskRequest): """ """ def create_task(request): data = CreateTaskRequest(request) params = {'title': data['title'], 'task_list': data['task_list_id'], 'completed' : data['completed'], 'due_date' : data['due_date']} … -
Having "permission denied" when I try to upload image to /media/ dir, DJANGO
I setup django framework into apache server, normally there is no problem when I try to insert record to DB. But if I try to upload something into media dir, permission problem occurs. I already give the chmod -R 755 to /var/www/ project's parent folder. But still having the problem. settings.py STATIC_URL = '/static/' MEDIA_URL = "/media/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, "media") and .conf settings are below. <VirtualHost *:8001> ServerName example.com DocumentRoot /var/www/ Alias /static /var/www/example.com/src/static <Directory "/var/www/example.com/src/static"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/example.com/media <Directory "/var/www/example.com/media"> Options FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> ErrorLog /var/www/example.com/logs/apis_error.log CustomLog /var/www/example.com/logs/apis_access.log combined WSGIPassAuthorization On WSGIDaemonProcess example.com python-path=/var/www/example.com:/var/www/venv36/lib/python3.6/site-packages WSGIProcessGroup example.com WSGIScriptAlias / /var/www/example.com/src/wsgi.py <Directory /var/www/example.com/src> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Any idea what is the problem here? -
How do you query a model for an aggregate of a ForeignKey computed field
How do you query a model for an aggregate of a ForeignKey 'computed' (Autofield?) field I have two models: class Job(models.Model): name = models.CharField(…) class LineItem(models.Model): job = models.ForeignKey(Job, …) metric_1 = models.DecimalField(…) metric_2 = models.DecimalField(…) metric_3 = models.DecimalField(…) # Making this a @property, @cached_property, or the like makes no difference def metric_total(self): return (self.metric_1 + self.metric_2 * self.metric_3) In the view: class StackoverflowView(ListView, …): model = Job def get_queryset(self): return Job.objects .select_related(…) .prefetch_related('lineitem_set') .filter(…).order_by(…) def get_context_data(self, **kwargs): context_data = super(StackoverflowView, self).get_context_data(**kwargs) context_data['qs_aggregate'] = self.get_queryset() \ .annotate( # Do I need to Annotate the model? ).aggregate( # This works for any of the fields that have a model field type metric1Total=Sum('lineitem__metric_1'), metric2Total=Sum('lineitem__metric_2'), # This will error : # Unsupported lookup 'metric_total' for AutoField or join on the field not permitted. # How do I aggregate the computed model field 'metric_total'? metricTotal=Sum('lineitem__metric_total'), ) return context_data When I try to aggregate the computed field, I get the error: Unsupported lookup 'metric_total' for AutoField or join on the field not permitted.. How do I aggregate these special fields? -
Django Annotations
So I'm working on a website, and I want to have some kind of a summary page to display the data that I have. Let's say I have these models: class IceCream(TimeStampedModel): name = models.CharField() color = models.CharField() class Cupcake(TimeStampedModel): name = models.CharField() icing = models.CharField() So on this page, users will be able to input a date range for the summary. I'm using DRF to serialize the data and to display them on the view actions. After I receive the filter dates, I will filter out the IceCream objects and Cupcake objects using the created field from TimeStampedModel. @action(detail=False, methods=['get']) def dessert_summary(self, request, **kwargs): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') cupcakes = Cupcake.objects.filter(created__date__range=[start_date, end_date]) ice_creams = IceCream.objects.filter(created__date__range=[start_date, end_date]) After filtering, I want to count the total cupcakes and the total ice creams that is created within that period of time. But I also want to group them by the dates, and display the total count for both ice creams and cupcakes based on that date. So I tried to annotate the querysets like this: cupcakes = cupcakes.annotate(date=TruncDate('created')) cupcakes = cupcakes.values('date') cupcakes = cupcakes.annotate(total_cupcakes=Count('id')) ice_creams = ice_creams.annotate(date=TruncDate('created')) ice_creams = ice_creams.values('date') ice_creams = ice_creams.annotate(total_ice_creams=Count('id')) So I want the result to be … -
Django migrations.RunSQL visibility to other connections during tests
I am creating a postgresql function in a migrations.RunSQL, and it gets created just fine. I have the default connection and another connection ('userdata') that, in this case, actually point to the same DB. The problem is that during tests, the function created in RunSQL is not visible to the 'userdata' connection. Is is visible to the default connection (which I'm guessing runs the RunSQL). Fine, I say, it's just in tests so I will close and reopen after migrations are run (by overriding setup_databases in my DiscoverRunner, for example) and then the 'userdata' connection will also see the new function. Alas, the ONLY place that the connections['userdata'].connect() call seems to actually have the desired effect is calling it actually in the test method (or in the classes being tested of course). The new function remains invisible if I do a connect() in the setup_databases or setUp for the TestCase. The same is true of connections.close_all(), which also only works in the test method. There seems to be some magic going on, with different connections being returned at different times. Is there a way to tell Django to reopen all stale connections that will work in tests? -
Field Serializers Django
I have a serializer with some custom fields and those fields depends on a specific query. The problem is that each time the serializer tries to get the value for this field It must perform the query to the DB. What about if the serializer is a many=True serializer?. class ExampleSerializer(serializers.ModelSerializer): field_one = serializers.SerializerMethodField() field_two = serializers.SerializerMethodField() field_three = serializers.SerializerMethodField() . . . def get_field_one(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field one stuff except Exception: # Do exception stuff def get_field_two(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field two stuff except Exception: # Do exception stuff def get_field_three(self, obj): try: # This is where i do the query query_result = obj.objects.filter(filter=self.context.get("filter").first() if query_result: # Do field three stuff except Exception: # Do exception stuff Is there a way to store that result inside a property in the serializer? Also, if I set a value in one of the serializer field, how do I retrieve and do some maths on another field in the same serializer? -
Integrate the JSON file via an API-Rest in MongoDB database
I generated a JSON file from Django to integrate it via an API-Rest in a MongoDB database. Generate a JSON file from Django: with open("fichier.json", "w") as out: data = serializers.serialize("json", User.objects.all()) out.write(data) data2 = serializers.serialize("json", Categories.objects.all() ) out.write(data2) the second step about integrating the JSON file via an API-Rest in a MongoDB database? I don't have any idea about doing it! Thanks for your help. -
Set field update in address url json django rest framework
I need update the field 'plan': The view @api_view(['GET','PUT']) def set_plan(request, nr_acc, nr_plan): plan = Plan.objects.get(pk=nr_plan) acc = Account.objects.get(pk=nr_acc) #return Response(plan.id) if request.method == 'PUT': #acc.plan.id = plan.id #acc.save() serializer = AccountSerializer(acc, data=request.data) if serializer.is_valid(): serializer.data['plan'] = request['plan'].id serializer.save() serializer_dict = serializer.data serializer_dict['message'] = "Consegui fazer o update do plano." return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) else: return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) return JsonResponse({'Conta':acc.id,'Novo plano': acc.plan.id}, status=200) In browser (http://127.0.0.1:8000/account/set-plan/1/1) I cant set update, the plan are with id 2, when i access the address http://127.0.0.1:8000/account/set-plan/1/1 dont update -
Function based view - dependent dropdown list
<script> $("#id_category").change(function () { var url = $("#newrequestForm").attr("data-sector-url"); // get the url of the load_cities view var categoryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'scholar_category': categoryId // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function $("#id_sector").html(data); // replace the contents of the city input with the data that came from the server } }); }); -
Is there a way to update an app config based on an overridden setting in a Django TestCase?
For example, if given a method that relies on the app config: def foo(): if apps.get_app_config('some_app').bar: return True Where some_app.bar is False by default, but I want to test it when it's True: class TestFoo(TestCase): @override_settings(BAR=True) def test_foo_enabled(self): # Fails because the app config isn't updated when using override_settings self.assertTrue(foo()) Is there a way to update the app config with the new setting from override_settings? Ideally, I want to avoid duplicating the app config setting in foo(): def foo(): if getattr(settings, BAR, False): return True -
How can I divide and set 2 decimal place in Django template?
I'm trying to do something like this: divide the product.sell_price by 3 and then use 2 decimal places. My code in Django template: {% widthratio product.sell_price 3 1 | floatformat:'2' %} If I only {% widthratio product.sell_price 3 1 %} everything goes OK but I need to insert 2 decimal places. Any help? Thank you!