Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to get multiple model data with single POST request?
I have 2 such models. I need to POST the data of 2 models in single POST API Call. Is it possible using viewsets ? class Customer(models.Model): id = models.AutoField(primary=True) customer_name = models.CharField(max_length=255) customer_number = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CustomerReferences(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) reference_name = models.CharField(max_length=255) reference_address = models.CharField(max_length=255) reference_number = models.IntegerField() -
Django Integrity Error NOT NULL constraint failed
I have searched this error over and over now and can't find a response that relates to my issue. I have a modal in my home page which I would like to allow users to update their posts from. I am using an inclusion tag and fbv for this. Here is my view: def update_view(request): profile = Profile.objects.get(user=request.user) if 'submit_u_form' in request.POST: u_form = PostUpdateForm(request.POST) if u_form.is_valid(): instance = u_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() return redirect('posts:index') And here is my custom tag: @register.inclusion_tag('posts/update.html') def update_tag(): u_form = PostUpdateForm() return {'u_form': u_form} Forms.py is here: class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'image', 'category',] Urls.py: urlpatterns = [ path('update/', update_view, name='update'), ] My modal in index.html includes this form: <form action="{% url 'posts:update' %}" method="post" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} <input type="hidden" name="post_id" value={{ post.id }}> {% update_tag %} </div> <div class="modal-footer"> <button type="submit" value="submit" name="submit_u_form">Update Post</button> </div> </form> And update html simply contains {{ u_form }} My form shows up in the modal how I would like it to however upon submit I receive this error: NOT NULL constraint failed: posts_post.author_id Please can someone explain to me why this is happening and how … -
Updating models with unique fields in Django Rest Framework
I get a "value already exists" error when I try to update the existing record. example: I have 10 Companies in a database. Now I want to edit the 4th record. Am looking to update the company "short_name" and leaving the "full_name" unchanged. When I hit submit, an error message is displayed in postman for full_name field "Already Exist" How can I avoid this? Model.py class CompanyProfile(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='ID',) short_name = models.CharField(max_length=30, null=True, blank=True,) full_name = models.CharField(max_length=255, unique = True,) def __str__(self): return str(self.full_name) Serializers.py class RegisterationCompanySerializer(serializers.ModelSerializer): short_name = serializers.CharField( max_length=30, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Short Name already exists or already in use")], ) full_name = serializers.CharField( max_length=255, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Full Name already exists or already in use")], ) class Meta: model = CompanyProfile fields = '__all__' extra_kwargs = { 'short_name': {'required': True}, 'full_name': {'required': True}, } views.py class MainCompanyProfileView(viewsets.ModelViewSet): queryset = CompanyProfile.objects.all() serializer_class = RegisterationCompanySerializer permission_classes = (permissions.AllowAny,) def update(self, request, pk=id ,*args, **kwargs): partial = kwargs.pop('partial', False) instance = get_object_or_404(CompanyProfile, id = pk) serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return super().update(request, *args, **kwargs) urls.py router = DefaultRouter() router.register('', MainCompanyProfileView) urlpatterns = [ path('v1/', include(router.urls)), ] Stacktrace Note: There are a lot of fields in each company have … -
VSCode Formatter causing error on my django project
Currently i am working on my django project with VSCode, and in my .html files i select the Django-Html as my language mode. And i have multiple blocks {%__%} in my html files. for example: {% block navbar %} {% endblock navbar %} {% block footer %} {% endblock footer %} enter image description here The problem is when i save the file, VSCode will auto format my html and move my _%} to next line which will make the endblock cannot recognize it properly after saving: {% block navbar %} {% endblock navbar %} {% block footer %} {% endblock footer %} enter image description here So is there anyone who has experienced this and knows how to fix it? -
How does the view in the app get the parameters in the urls.py under the project?
My directory structure(omit other unnecessary files): root urls.py app urls.py views.py root/urls.py: urlpatterns = [ path('<slug:_key>', include('app.urls')) ] app/urls.py: urlpatterns = [ path('', views.my_view, name="my_view"), ] app/views.py def my_view(request, key): res = my_func(key) return HttpResponse(res) Then my_view cannot get the parameter key -
I Can't able to Upload multiple Images using Django Forms, I tried to upload multiple images using Filepond in Django
I tried to upload Multiple images using Filepond, and it is working from frontend but not from the backend. And also not getting data from backend to edit the form. A form showing Blank only. I added my code below as models.py, forms.py, views.py, and HTML code also. I tried a lot of ways to upload multiple images but every time got errors only. Please, help me to resolve it ASAP. Thanks, in advance :). models.py class UserDetail(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(null=True) firm_name = models.CharField(max_length=75, null=True) slug = models.SlugField(max_length=75, null=True, blank=True) person_name = models.CharField(max_length=40, null=True) designation = models.CharField(max_length=20, null=True) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=UserDetail) class UploadImages(models.Model): userdetail = models.ForeignKey(UserDetail, default=None, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) def __str__(self): return self.userdetail.firm_name class Meta: verbose_name_plural = "Upload Extra Images" forms.py from django import forms from customer.models import UserDetail from django.contrib.auth.forms import UserChangeForm class EditForm(UserChangeForm): person_name = forms.CharField(label='Full Name') image = forms.ImageField(label='Logo Image') def __init__(self, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'input' class Meta: model = UserDetail fields = ('image', 'firm_name', 'person_name', 'designation') admin.py class UploadImagesAdmin(admin.StackedInline): model=UploadImages @admin.register(UserCardDetail) class UserCardDetailAdmin(admin.ModelAdmin): inlines = [UploadImagesAdmin] class Meta: model = … -
How can I move my media files stored in local machine to S3?
I have a Django application running on EC2. Currently, all my media files are stored in the instance. All the documents I uploaded to the models are in the instance too. Now I want to add S3 as my default storage. What I am worried about is that, how am I gonna move my current media files and to the S3 after the integration. I appreciate the help. I am thinking of running a python script one time. But I am looking for any builtin solution or maybe just looking for opinions. Thanks! -
Print Syntax error when testing out django script
When running this from django.urls import path from . import views from . import util encyclopedia_list = util.list_entries() urlpatterns = [ path("", views.index, name="index") ] for encyclopedia in encyclopedia_list: urlpatterns.append(path(f"{encyclopedia}", views.encyclopedia, name='encyclopedia_page') print(urlpatterns) script in a django app in order to test if the urlpatterns list is being updated acordingly I get a syntax error with the print function on the last line, any idea on what could be happening? -
How to store objects of custom class as session variables in django?
In my case i wants to store object of my USER class to be stored as session variable To be more precise my class contains several methods for USER structure of my USER class class USER: def __init__(self , phone_number_of_user = None , user_name = None): self.phone_number = phone_number_of_user self.user_name = user_name def login(self): login_code_will_be_here def get_user_name(self): return self.user_name def set_data_of_user_in_firebase(self , data = None): code to set data of user will be here firstly i create a USER object user = USER(phone_number = 9******** , user_name = John) But when i tries to store my objects in session of django like this request.session['user'] = user django shows me following error Object of type USER is not JSON serializable -
Django server not running? [closed]
I'm trying to run an existing Django server, but when I try to run it, CMD doesn't output anything? The server has already been created by someone else and I've already installed Python, Pip and Django. Screenshot -
objects.filter to get if string is contained in one or other field
I'm trying to filter my clients with a query. The user can look for the cif code and the client name writing in the same field so I can't know if he's looking for one thing or another. I'm trying to figure it out how to filter in both fields without excluding the other. I'll try give an example: I have this on my client table: [ { "company_name":"Best Bar EUW", "cif":"ABCD1234" }, { "company_name":"Word Bar EEUU", "cif":"POIU4321" }, { "company_name":"Not a bad bar", "cif":"MNVB1321" } ] Now I want to look for the "EE" string: the result that I want is the second object but the string "EE" is not included in the "cif" so it won't give me the result I want because it is included in one field but not in the other. This is my Client model: class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField('consumptions.Platform', verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) What can I do with this? Thanks in advance ! -
getting error in Chrome browser: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found
I realize I already posted on this same subject but I think that post was too long (and I didn't get a response) so this is a condensed version. Again, I'm trying to get this app to work, it was running fine, I logged in as a superuser, made a comment, but after that I just get the error: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)$'] it says that the problem is at line 10 in my base.html, here is my base.html file, is the bootstrap cdn link no longer valid? line 10: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> base.html: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Blogging!</title> <!-- Bootstrap --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> {# MEDIUM STYLE EDITOR#} <script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One" rel="stylesheet"> </head> <body class="loader"> <!-- NAVBAR --> <nav class="navbar navbar-default techfont custom-navbar"> <div class="container"> <ul class="nav navbar-nav"> <li><a class= 'navbar-brand bigbrand' href="{% url 'post_list' %}">My Blog</a></li> <li><a href="{% url … -
Is there a way to add my django-tenant schema name to MEDIA_ROOT?
I have modified my Geonode project, which is a GeoDjango project, to enable multi-tenancy using django-tenants. I am currently not able to view my thumbnails due to broken routing... How do I correctly route my generated thumbnails like this: http://d3.demo.com(current_tenant_domain_url)/uploaded/d3(tenant)/thumbs/document-8a72dc8c-0151-11eb-a488-1062e5032d68-thumb.png The thubnail url that is currently generated is as follows: http://localhost:8000/uploaded/thumbs/document-fcdea3a4-015c-11eb-a488-1062e5032d68-thumb.png?v=c1855f6a urls.py urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.LOCAL_MEDIA_URL, document_root=settings.MEDIA_ROOT) My current settings.py MEDIA_ROOT = os.getenv('MEDIA_ROOT', os.path.join(PROJECT_ROOT, MEDIAFILES_LOCATION)) MEDIA_URL = os.getenv('MEDIA_URL', '%s/%s/%s/' % (FORCE_SCRIPT_NAME, MEDIAFILES_LOCATION, MULTITENANT_RELATIVE_MEDIA_ROOT)) Any help will be appreciated -
Accept only some variables in form fields from CSV and not all in Django?
I have a Django model with 2 fields as latitude and longitude. I've declared them both as a CharField. My model needs to accept more than 1 coordinates (latitude and longitude), so while entering in the rendered form (in the UI), I'm entering these coordinates separated by commas. It's this char input which I'm then splitting in the function and doing my computations.. This is my models.py class Location(models.Model): country = models.ForeignKey(Countries, on_delete=models.CASCADE) latitude = models.CharField(max_length=1000,help_text="Add the latitudes followed by comma") longitude = models.CharField(max_length=1000,help_text="Add the longitudes followed by comma") This is my view.py function def dashboard(request): form = LocationForm if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() latitude = list(map(float, form.cleaned_data.get('latitude').split(','))) longitude = list(map(float, form.cleaned_data.get('longitude').split(','))) ......... ......... return render(request, dashboard/dashboard.html, { 'form':form }) Now, I want my model to accept the coordinates as a CSV file too. I want an option in the UI to add a CSV file (having multiple latitudes and longitudes) which then populates these two char fields (as comma-separated values). Note that, my CSV file won't have the country name. I shall be entering the country using the form UI only. Thus, in short, I need to accept some of the form fields as … -
gitignore how to exclude a table
I have a questions. So im working on my Django project for school and its almost done. And also i have to include a gitignore file which looks like this: venv/* .idea/* db.sqlite3 Nothing fancy just simple. My problem here is, that i have a table in db.sqlite3, and i need those 3 entries my project. So when somebody merges my project, the entries in this table should exist. Otherwise u just have an emtpy table and then my function on my Website is not working. I already googled for this, but i just found how to exlude files or folders. So i hope there is a solution. Anyway thanks for your help. :) -
How to create an add favorite button with ajax in Django without reloading the page?
I want to create an add favorite button in my Django project I succeed in it b8ut I want to perform this action via ajax as I don't want to reload the page when the user clicks on add favorite can you help me to convert my code with ajax so that when anyone clock on the add favorite it does not reload the page. Here are the model, URL, views, and template. Profile Model with the field favorite: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,) bio = models.TextField(max_length=350) website_url = models.CharField(max_length=350) profile_pic = models.ImageField(default='images/profile_pics/default.png', upload_to="images/profile_pics/") date_joined = models.DateTimeField(auto_now_add=True, null= True) favorites = models.ManyToManyField(Fervid) likes = models.ManyToManyField(Fervid, related_name='fervid_likes') Url for add favorite: path('favorites/', views.favorites, name='favorites'), Views function for add_favorite : @login_required def favorite(request, fervid_id): user = request.user fervid = Fervid.objects.get(id=fervid_id) profile = Profile.objects.get(user=user) if profile.favorites.filter(id=fervid_id).exists(): profile.favorites.remove(fervid) else: profile.favorites.add(fervid) return HttpResponse('<script>history.back();</script>') Add favorite functionality in my template: {% if fervid.id in ffervids %} <a class="savehrt" href="{% url 'core:fervidfavorite' fervid.id %}"><img src="{% static 'images/saved.png' %}" width=26 height=26 alt="save picture"></a> {% else %} <a class="savehrt" href="{% url 'core:fervidfavorite' fervid.id %}"><img src="{% static 'images/unsaved.png' %}" width=26 height=26 alt="save picture"></a> {% endif %} Note:-> I request you to convert this algorithm with ajax capability so that it … -
Django REST Framework class-based views inheritance
I am using Django REST Framework and I found myself in the following situation: I have two APIViews that are identical to one another except for the ordering of the objects they return: # Route: "/new" class NewView(APIView): """ Returns JSON or HTML representations of "new" definitions. """ renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def get(self, request): # Queryset definitions = Definition.objects.filter(language=get_language()) definitions = definitions.order_by("-pub_date") # HTML if request.accepted_renderer.format == "html": context = {} context["definitions"] = definitions context["tags"] = get_tags(definitions) return Response(context, template_name="dictionary/index.html") # JSON serializer = DefinitionSerializer(definitions, many=True) return Response(serializer.data) # Route: "/random" class RandomView(APIView): """ Returns JSON or HTML representations of "random" definitions. """ renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def get(self, request): # Queryset definitions = Definition.objects.filter(language=get_language()) definitions = definitions.order_by("?") # HTML if request.accepted_renderer.format == "html": context = {} context["definitions"] = definitions context["tags"] = get_tags(definitions) return Response(context, template_name="dictionary/index.html") # JSON serializer = DefinitionSerializer(definitions, many=True) return Response(serializer.data) As you can see, the only line that changes between these two views is the one that orders the Definition objects. How can I create a parent view to contain the shared code and a child view to sort objects? -
DB is overwhelmed by background periodic tasks in Django App
We have a Django application that has to consume a third-party API periodically to fetch a large amount of data for a set of users. The tasks are performing fine and fullfill their purpose. But after a period of time, we start getting too many connection errors from postgres FATAL: sorry, too many clients already Info The project is dockerized and all components are running in separate containers including the app and the database (postgres). The periodic tasks are performed with dramatiq and scheduled by periodiq. We also use redis as the system broker. I have tried various workarounds to make it stop but none of them worked including various solutions proposed here in SO. Attempt 1 I have used connection.closes() before and after each task execution to make sure no ghost connections are left open by the workers. Attempt 2 Add a task limiter in order to limit the number of active connections at a given time and prevent the database from being overwhelmed. While this solution is not even serving the actual scope of our implementation as it obviously, reduces the performance of the execution of the task It did not help with the problem. Attempt 3 Increase … -
Can't connect Django and my react native app... [Network request failed]
I can't get a response from the rest API that I have created to my React Native Applications. Eventhough, I run django server and the rest api is still running, but I cant get response from rest API. The request in working on postman and I can get response there but not in react native app.I have attached my code below. Kindly, go through it React Native Code useEffect(() => { fetch('http://localhost:8000/api/movies/') .then(res => console.log(res.json)) .catch(err => console.log(err)); }, []); settings.py """ Django settings for movietracker project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'v23d&&w#*&g4q+mse7nbby4rms79(r7@feg&j1d*wf=3vq8)&4' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'api' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', … -
SystemCheckError: System check identified some issues:
I am building a project to place an order. when I run makemigrations command then it gives an error of SystemCheckError: System check identified some issues and I have deleted the migration file from migrations ERRORS: order.Order.price: (fields.E304) Reverse accessor for 'Order.price' clashes with reverse accessor for 'Order.product'. HINT: Add or change a related_name argument to the definition for 'Order.price' or 'Order.product'. order.Order.product: (fields.E304) Reverse accessor for 'Order.product' clashes with reverse accessor for 'Order.price'. HINT: Add or change a related_name argument to the definition for 'Order.product' or 'Order.price'. My models.py is as follows: class Order(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.company + self.product + self.price -
How do I POST a json file to Django and MySQL containing a base64 image string? (also using NGINX and Angular)
I've been trying to post this for days but haven't had any luck. Post method: public postDict(name: any, postData: Object) { var key = localStorage.getItem("access") var httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key, }), }; return this.http .post<any>( 'http://example.com:80/images/', putData, httpOptions ) .subscribe((data) => { console.log("sup") }); /* The data I'm sending looks like this in Angular: let item = {key: imgTimeKey, url: this.imgURL , owner: 'idiot'} where url is: data:image/jpeg;base64,/9j/...( bout 5mb worth of characters after this D-8 ) I've gotten past the problem of transmitting so much data in one post, but now its giving me a 404 Bad Request error. (It works if I replace the url with a regular string.) Now I have been storing these as regular strings in indexeddb just fine and I figure it should work the same with Django and MySQL. It should be fine to store the url in a string no? Here is my data model in Django: from django.db import models class Image(models.Model): created = models.DateTimeField(auto_now_add=True) key = models.CharField(max_length=100, blank=True, default='') url = models.TextField() owner = models.ForeignKey('auth.User', related_name='images', on_delete=mod> class Meta: ordering = ['created'] And finally, my NGINX server configuration: server { listen … -
How to run .py files as cronjob in aws?
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.1.1). I have been trying to run a .py file as a cronjob that works at 4 a.m every day in AWS and I have created a .config file into .ebextensions for that such as below. cron.config file: files: "/etc/cron.d/cron_process": mode: "000644" owner: root group: root content: | 0 4 * * * root /usr/local/bin/task_process.sh "/usr/local/bin/task_process.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date source /var/app/venv/staging-LQM1lest/bin/activate cd /var/app/current python Bot/run_spiders.py exit 0 commands: remove_old_cron: command: "rm -f /etc/cron.d/cron_process.bak" run_spiders.py file: from first_bot.start import startallSpiders from .models import Spiders import importlib test = Spiders.objects.get(id=1) test.spider_name = "nigdehalk" test.save() I'm trying to change an attribute of one of my objects for testing but it didn't work. Am I missing something? How can I create this cronjob? -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(h_code): testhospital = HospitalList.objects.filter(code = h_code).values('code') print(testhospital) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'h_code' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I have to specify it? (Some code has been omitted to make it easier to see.) view.py (add) class ListDoctor(generics.ListCreateAPIView): queryset = DoctorList.objects.all().order_by('-d_code') serializer_class = DoctorListSerializer -
Celery task can't access volume file in docker
Admin page can get access to the image file saved in database but Celery task can't get access to that image file and shows error FileNotFoundError(2, 'No such file or directory'). docker-compose.yml version: "3" services: app: &app build: context: . ports: - "8000:8000" volumes: - ./backend:/backend command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - SECRET_KEY=mysecretkey - DB_HOST=db - DB_NAME=election - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db - redis db: image: postgres:12-alpine environment: - POSTGRES_DB=election - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword volumes: - postgresql_data:/var/lib/postgresql/data ports: - 5432:5432 redis: image: redis:6-alpine celery: <<: *app command: celery -A app worker -l INFO ports: [] depends_on: - app - redis - db volumes: postgresql_data: Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 # Face-recognition model RUN apt-get -y update RUN apt-get install -y --fix-missing \ build-essential \ cmake \ gfortran \ git \ wget \ curl \ graphicsmagick \ libgraphicsmagick1-dev \ libatlas-base-dev \ libavcodec-dev \ libavformat-dev \ libgtk2.0-dev \ libjpeg-dev \ liblapack-dev \ libswscale-dev \ pkg-config \ python3-dev \ python3-numpy \ software-properties-common \ zip \ # web3 libssl-dev \ # QR code zbar-tools \ libzbar-dev \ && apt-get autoremove \ && apt-get clean && rm -rf /tmp/* /var/tmp/* … -
django-parler-rest avoiding "translations" objects
While I'm creating an app by using django-parler-rest for internationalization support I realized that TranslatedFieldsField and TranslatableModelSerializer serialize the data in the following format: { "id": 528, "country_code": "NL", "translations": { "nl": { "name": "Nederland", "url": "http://nl.wikipedia.org/wiki/Nederland" }, "en": { "name": "Netherlands", "url": "http://en.wikipedia.org/wiki/Netherlands" }, "de": { "name": "Niederlande", "url": "http://de.wikipedia.org/wiki/Niederlande" } } } Is there any way to serialize the data in the following format? { "nl": { "id": 528, "country_code": "NL", "name": "Nederland", "url": "http://nl.wikipedia.org/wiki/Nederland" }, "en": { "id": 528, "country_code": "NL", "name": "Netherlands", "url": "http://en.wikipedia.org/wiki/Netherlands" }, "de": { "id": 528, "country_code": "NL", "name": "Niederlande", "url": "http://de.wikipedia.org/wiki/Niederlande" } }