Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Lack of correct display of Persian in PDF format in Django
I used reportlab in Django to make a pdf of Persian words in Django as follows: from reportlab.pdfgen import canvas from reportlab.lib.units import inch from reportlab.lib.pagesizes import letter import io from django.http import FileResponse from django.conf import settings import reportlab def pdf(request): reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) +'/static') pdfmetrics.registerFont(TTFont('Samim','Samim.ttf')) buf=io.BytesIO() c=canvas.Canvas(buf,pagesize=letter) txt=c.beginText() txt.setTextOrigin(inch,inch) txt.setFont('Samim',14) lines=[ 'سلام', 'خوبی', 'چه خبر' ] for l in lines: txt.textLine(l) c.drawText(txt) c.showPage() c.save() buf.seek(0) return FileResponse(buf,as_attachment=True,filename='me.pdf') But the output is as follows: I also used other fonts like Nazanin but the result did not change and I even used the xhtml2pdf library but the result was still in this format. In fact, there is a problem with the output format, which must be right to left, which is left to right, unfortunately! How should I solve this problem? -
Error while deploying Django to Heroku using GitHub
I am trying to deploy my GitHub repository on Heroku, the build is successful but when I am going to the domain it is showing an Application Error and the logs are showing this. What I think: I am sure that the problem is in INSTALLED_APPS setting in settings.py. Heroku isn't recognising my 'app_name', may be some namespace problem. GitHub - https://github.com/vivekthedev/savetheearth Heroku Logs File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-10-29T18:52:58.335358+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-10-29T18:52:58.335359+00:00 app[web.1]: File "/app/core/core/wsgi.py", line 16, in <module> 2021-10-29T18:52:58.335359+00:00 app[web.1]: application = get_wsgi_application() 2021-10-29T18:52:58.335359+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-29T18:52:58.335359+00:00 app[web.1]: django.setup(set_prefix=False) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup 2021-10-29T18:52:58.335360+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate 2021-10-29T18:52:58.335360+00:00 app[web.1]: app_config = AppConfig.create(entry) 2021-10-29T18:52:58.335360+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 90, in create 2021-10-29T18:52:58.335361+00:00 app[web.1]: module = import_module(entry) 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-10-29T18:52:58.335361+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-10-29T18:52:58.335361+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked … -
fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error
have tried everything in the forum, but nothing works for me, I am a nube please if you provide the explanation I would like a detailed explanation. Please help to find the problem. I have tried to upload wheels enter image description here I tried to implement MariaDB in \Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb and \Program Files (x86)\MySQL\MySQL Connector C 6.1\lib\mariadb But nothing works form me. PS C:\Users\info\Desktop\storefront> pipenv install mysqlclient Installing mysqlclient... Error: An error occurred while installing mysqlclient! Error text: Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py): started Building wheel for mysqlclient (setup.py): finished with status 'error' Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient: started Running setup.py install for mysqlclient: finished with status 'error' ERROR: Command errored out with exit status 1: command: 'C:\Users\info\.virtualenvs\storefront-ncd4CFf2\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\info\\AppData\\Local\\Temp\\pip-install- teckkm52\\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\\setup.py'"'"'; __file__='"'"'C:\\Users\\info\\AppData\\Local\\Temp\\pip-install- teckkm52\\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\\setup.py'"'"';f = getattr(tokenized, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\info\AppData\Local\Temp\pip-wheel-x6tij91j' cwd: C:\Users\info\AppData\Local\Temp\pip-install- teckkm52\mysqlclient_916f3b56813c4e1c90eea8491caf2c2c\ Complete output (31 … -
Django generic.ListVIew: display list item's details on the same page (~ combine ListView and DetailView)
Roughly speaking, what I want is combine generic.ListView with generic.DetailView, but display the clicked ListView item's details on the same page. What I've done is: generic.ListView of Contacts: from .models import Contact from django.views import generic class ContactList(generic.ListView): model = Contact context_object_name = 'contacts' template_name = 'contacts/list.html' The contacts/list.html template includes a JS Fetch request (GET) to get the clicked item: {% block content %} {% if contacts %} <ul> {% for contact in contacts %} <li><a id="{{ contact.id }}" onClick="showDetails(this.id)">{{ contact.first_name }}</a></li> {% endfor %} </ul> {% else %} No contacts. {% endif %} <div id='contactDetail'></div> <script type="text/javascript"> function showDetails(contactId){ console.log(contactId); fetch(`http://127.0.0.1:8080/contacts/${contactId}`, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, }) .then(response => { // should 500 be processed? return response.json(); }) .then(data => { //Perform actions with the response data from the view window.onload = function() { // build html markup next document.getElementById("contactDetail").innerHTML= ...; } }) } </script> {% endblock content %} The Django view that handles this Fetch-GET request is: from django.shortcuts import get_object_or_404 from django.forms.models import model_to_dict def contact_details(request, contact_id): contact = get_object_or_404(Contact, pk=contact_id) contact = {k: v for k, v in model_to_dict(contact).items() if v} return JsonResponse(contact) Is it the correct way? -
Django returns 301 even with slash appended to URL
I'm trying to test my viewset with APIClient, but it returns HTTP 301 even when I send a request with the slash appended. This is my router for the viewset. from rest_framework.routers import SimpleRouter from .views import ( ReturnLabelTicketViewSet ) app_name = "ticket_submission" router = SimpleRouter() router.register(r'return_label_tickets/', ReturnLabelTicketViewSet) urlpatterns = router.urls This is the app urls. urlpatterns = [path("", include("ticket_submission.urls"), name="root")] And my test case. client = APIClient() response = client.post('/return_label_tickets/', ticket) # ticket data is not relevant here self.assertEqual(response.status_code, 200) -
python3 ModuleNotFoundError: No module named 'rest_framework_jwt'
i want to import from jwt but got an error line 12, in from rest_framework_jwt.settings import api_settings ModuleNotFoundError: No module named 'rest_framework_jwt' -
Return monthly sales value in Django
I've got some simple models below class Stamping(models.Model): created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Product(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_product') name = models.CharField(max_length=300, unique=True) price = models.FloatField() class GroupProductOrder(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_product_orders') product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() class Order(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') fulfilled = models.BooleanField(default=False) products = models.ManyToManyField(GroupProductOrder, blank=True) @property def total_price(self): cost = 0 for product in self.products.all(): cost += product.total_price return cost Now I want to query the database and return some details on a monthly basis. Details like total number of sales for each month and sum of sales for each month. I've tried using annotate but it seems can't pass model property in it. What is the best way to tackle this problem? Example of expected output is {'month': 'October', 'count': 5, 'total': 15} -
Exchanging data between django apps in the same project
I would like to exchange data between two django apps that are coming from a single big app that due to the increasing size and functionalities we decided to split. Specifically I need to retrive only a string in one app from the other. Litterally a 10 character string. The only thing that I found at the moment that satisfies me, since I would like to avoid import stuff from the other app (to me it seems not a clean way to do it, in the other case please change my mind), is making an http request from one app to the other. Anyway I found it overkill. Is there a clean way to achive this without using http request or imports? -
no such table: operational error in django
I run makemigrations followed by migrate but still I get the error when I try to populate DB with dummy values that no such table exists. This happens for one single table. Here is my models.py file for the table: class G(models.Model): desc = models.CharField(max_length=charLen256) points = models.IntegerField(default=0) add = models.BooleanField(default= False) complete = models.BooleanField(default=False) Here is what I try to do in my populate script: def add_goal(item): g = G.objects.get_or_create(desc=item['description'], points=item['points_earned'])[0] g.save() Can anybody spot the problem or error. I happen to have researched a lot but did not find any suggestion other than running makemigrations and migrate. Here is the error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: myapp_goal -
I want to multiple user authentication with django social oauth2 and simpleJWT(Normal register form and social auth together)
I want to use two types of user login in my django project. One of them is the form that asks for information such as email and password, which is the traditional method, and the other is the login process using social media accounts. However, in the video I watched, he first deletes the simpleJWT module he had made before, and then only uses the oauht2 module. I am very confused at this point. I want both types of user input, how can I do that? Here is the video And here is the doc. of oauth2 module -
Create a form with specific changed_data in django for testing purposes
I've overridden ModelAdmin.save_model in order to trigger a task if a certain field was changed. Basically something like: def save_model(self, request, obj, form, change): obj.save() if "field_name" in form: transaction.on_commit(lambda: trigger_task()) Now I'm trying to write a unit test that checks whether this task will be triggered in response to the field change. Only I'm having a hard time creating a form whose changed_data will contain that field. My test is currently something like: @patch(...) def test_task_should_trigger_if_field_changed(self, mocked_task): admin = MyAdmin(model=MyModel, admin_site=AdminSite()) form = MyForm({"field_name": "changed"}, initial={"field_name": "initial"}) ... admin.save_model(request=MagicMock(), obj=my_model, form=form, change=False) The test above won't create a form whose changed_data contains field_name and the task will never be triggered. At this point, I'm considering creating a mocked object that will return that famed form.changed_data["field_name"] but I'm wondering if I'm missing something or is there a simpler way of doing this. -
Channels group_send method doesn't send data until method ends
I am developing the app with private chat between 2 users. There are 2 consumers: chat consumer for receiving/sending messages and chats consumer for receiving messages from all chats of the user. When the consumer receives a message, it should broadcast data into all clients that are connected to websocket, so I use self.channel_layer.group_send method. After that, I have to do some data checks and transformation and send new data into all clients from another websocket (chats websocket). The problem is that data transformations can take some time (DB calls, services, etc), but the first group_send call won't send any data until method receive ends. For example, if I put asyncio.sleep(10) between group_send calls - the data won't be received by clients for 10 seconds. async def receive(self, text_data): await self.channel_layer.group_send(f"chat_{self.sender}_{self.receiver}", text_data) ... #some data transformation or checks await self.channel_layer.group_send(f"all_chats_{self.sender}", transformed_data) -
Connecting flutter with Django API in localhost, but CORS issue keeps blocking connection
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
Is there a way to annotate a related field in django?
Is something like this possible? m = Message.objects.annotate(room__something=Value('DOH', output_field=CharField())).select_related('room') m.room.something == 'DOH' # is true -
Request help for webscraping issues
I have been trying to webscrape two websites for data but facing issues. I will be extremely glad if anyone can help in resolving the problem 1.https://online.capitalcube.com/ The website requires one to login. I came up with the following code after watching tutorials on youtube for the last 2 days. from bs4 import BeautifulSoup import pandas as pd import requests URL = 'https://online.capitalcube.com/' LOGIN_ROUTE = '/login' import requests headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-User': '?1', 'TE': 'trailers', } s = requests.session() login_payload = { 'email': '<intentionally removed it>', 'password': '<intentionally removed it>' } login_req = s.post(URL + LOGIN_ROUTE, headers = headers, data = login_payload) print(login_req.status_code) The error i am getting is as follows *Traceback (most recent call last): File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1010, in validate_conn conn.connect() File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/connection.py", line 416, in connect self.sock = ssl_wrap_socket( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 449, in ssl_wrap_socket ssl_sock = ssl_wrap_socket_impl( File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/site-packages/urllib3/util/ssl.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "/Users/rafatsiddiqui/opt/anaconda3/envs/scientificProject/lib/python3.9/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File … -
Django models.DateTimeField, how to store the value without seconds?
I have this model class Appointments(models.Model): options = ( ('waiting', 'In Attesa'), ('confirmed', 'Confermato'), ('closed', 'Chiuso'), ) duration = ( ('15', '15 minuti'), ('20', '20 minuti'), ('30', '30 minuti'), ('40', '40 minuti'), ) date = models.DateTimeField(default=timezone.now) patient_first_name = models.CharField(max_length=250) patient_last_name = models.CharField(max_length=250) patient_email = models.EmailField(_('email address')) patient_phone = models.CharField(max_length=250) doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT) room = models.ForeignKey(Room, on_delete=models.PROTECT, default=1) status = models.CharField(max_length=10, choices=options, default='waiting') message = models.TextField(null=True, blank=True) notes = models.TextField(null=True, blank=True) appointment_date = models.DateTimeField(null=True, blank=True) duration = models.CharField(max_length=10, choices=duration, default='15') class Meta: ordering = ('-date', ) unique_together = ('appointment_date', 'room', ) How can I store appointment_date value without seconds in the DB? Right now the value is like this 2021-11-05 17:30:43 I'd like to store it as 2021-11-05 17:30 That's because otherwise unique_together is basically useless for what I need. -
Displaying rating star in Django
I am writing a small Django website and I want display rating stars but am a bit stuck. In my html file, I am doing something like below <div class="rating-star"> <span> <i class="fas fa-star{% if review.rating == 0.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 1.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 2.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 3.5 %}-half-alt {% endif %}" aria-hidden="true"></i> <i class="fas fa-star{% if review.rating == 4.5 %}-half-alt {% endif %}" aria-hidden="true"></i> </span> </div> In each <i> tag, I also want use elif to display far fa-star. Let me show an example using fontawesome v4.7. In fontawesome v4.7, it looks like below and I want to achieve the same thing with fontawesome v5.13 but I don't know to <span> <i class="fa fa-star{% if review.rating == 0.5 %}-half-o{% elif review.rating < 1 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 1.5 %}-half-o{% elif review.rating < 2 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 2.5 %}-half-o{% elif review.rating < 3 %}-o {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if review.rating == 3.5 %}-half-o{% elif review.rating < … -
Update a string in database using django? [closed]
Lets say I have an table named, Class Food: item = models.CharField(max_length=32, blank=True) And for example there is a record as follows, egg carrot Now i need to update "egg" with "egg1239812", How to update this ? For int fields we can use "F" expression to add and update. How to update a string using django without removing it ? -
Django bulk create with self reference foreign key
I have a question about Django objects creation using bulk_create() Here is a part of my model : class Group(models.Model): uid = models.IntegerField(unique=True) persons = models.ManyToManyField(User, blank=True) label = models.CharField(max_length=128) parent_group = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) And then I want to create like this : df_records = df.to_dict('records') model_instances = [Group( uid = record["uid"], label = record["label"], group_parent = Group(uid=record["parent_uid"]), ) for record in df_records] Group.objects.bulk_create(model_instances) Is it possile to self reference parent in a bulk create (of course the parent is in the same bulk) ? Or I have to set parent to null and iterrate throught all objects to find the parent django object id ? -
Django can't compare offset-naive and offset-aware datetimes
If the time has not exceeded three minutes, I want to proceed to the next actions django models: class ActivationCode(models.Model): blablabla activate_code_expiry = models.DateTimeField(default=datetime.now, blank=True,null=True) views.py: activation = ActivationCode.objects.get(user_id=request.user.id) if activation.activate_code_expiry < (datetime.now()-timedelta(minutes=3)): blablablabla -
i am unable to execute the sudo python3 manage.py setup i have .env and settings.py file in same location so please help to resolve the issue
strong text below error i am getting while executing the sudo python3 manage.py setup enter image description here django.core.exceptions.ImproperlyConfigured: Set the MEDIA_ROOT environment variable enter image description here please find the exact error which im getting -
django admin form does not work in inline
This is my form class LoginForm(ModelForm): class Meta: model = Login fields = '__all__' widgets = { 'password': PasswordInput(), } This is my inline class LoginInline(admin.StackedInline): model = Login This is my admin class AppAdmin(admin.ModelAdmin): list_display = ('name', 'link_href') inlines = [LoginInline] class LoginAdmin(admin.ModelAdmin): form = LoginForm When I try to add login from login page, the password is correctly applied But not from the app page using inline How can I fix this ? -
Replacing template with another with Django
I am trying to find a way to replace only a section of a web page with another template based on the change of a drop down. Also I don't want the rest of the page to reload. I'm using jquery to call the function when the drop down is changed so that's not an issue. The closest way I have is to use ajax replace the contents of a div with something else but when I try to pass a django tag that would refer to another html template, the string "{% include 'upgrading_template.html' %}" prints on the page rather than reading it as an include statement. I have also tried methods like replaceWith() but I get the same result. $.ajax({ type: 'GET', url: {% url 'sw_upgrade' %}, data: parameters, success: function (response) { document.getElementById('upgrade_template').innerHTML = "{% include 'upgrading_template.html' %}"; } }) -
Use of same serializer class for post and get request in Django rest framework
I have a Student model which has some fields. What I need is I want to create a student object using post API with certain fields and however needs to show some other fields while doing get request. For eg: My model: class Students(models.Model): name = models.CharField(max_length=255,blank=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=16) address = models.CharField(max_length=255,blank=True) roll = models.IntegerField() subject = models.CharField(max_length=255,blank=True) college_name = models.CharField(max_length=255,blank=True) Now my serializer will look like this. class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','email','name','phone','roll','subject','college_name', 'address'] Suppose, I have a view that handles both post and get api (probably using APIView), then what I need is, to create a student object I only need name, phone and email. So for post api call, I only need three fields whereas while calling the get api I only need to display the fields name, roll, subject, and college_name not others. In this situation, how can I handle using the same serializer class?? -
Django & Flutter How to fix CORS and broken pipe problem?
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': …