Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL Parameters to CreateView and automatic select value in a dropdown
I need, from a listview table, with an js button, open the createview and pass with parameter the id about an specific row that, in the createview form, select automatically the value in a dropdown. I imagine that, it would be with a parameter in the url of the createview and, in the createview, select in the post def the dropdown's row with the value of the parameter. Sorry if my explication it's very complicated. Examples. I have one model, Projects and I have a second model, Phases of these Projects. When I have listed the projects, from a button in one Project's row, I would need that to open the phases's createview and in the form, to select automatically the value of the dropdown's row. Projects form (the icons are bad): projects form When I click on the button with the url path('phases/add/', phasesCreateView.as_view(), name='phases_create'),, I need that in the destiny form phases form, the first dropdown would be completed automatically. -
When to run tests in dockerized django application?
I'm building a CI/CD for a django application. We dockerized the application and now our goal is to automate the building process triggered by push on a github repository. We are now building the GitHub Actions side. The project requires all containers to be running. I'm wondering where I should be running tests. Running them in the docker file seems useless as there are several tests that would fail if the other containers are not running (postgres container for example, or rabbitmq ). The approach I was thinking was to maybe setup a job in GitHub actions, build and start all containers with compose and then run the tests ? What is the recommended approach ? -
how to create celery periodic task in django rest framework Views?
I use django rest framework. I want the celery task to execute an operation once on the date that the user enters... this is my celery conf: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Bimsanj.settings') celery_app = Celery('Bimsanj') celery_app.conf.task_queues = ( Queue('default', routing_key='default'), Queue('reminder', routing_key='reminder'), ) celery_app.conf.task_default_queue = 'default' celery_app.conf.task_routes = { 'send_reminder_message_task' : {'queue' : 'reminder'}, } # Load task modules from all registered Django apps. celery_app.autodiscover_tasks() celery_app.conf.broker_url = BROKER_URL celery_app.conf.result_backend = RESULT_BACKEND and this is my View: class InsuranceReminderView(GenericViewSet, CreateModelMixin): serializer_class = InsuranceReminderSerializer model = InsuranceReminder def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) clocked = ClockedSchedule.objects.create(serializer.validated_data['due_date']) PeriodicTask.objects.create( clocked=clocked, name=str(uuid4()), one_off=True, task="apps.insurance.tasks.send_message_insurance_reminder", args=([serializer.validated_data['title'], serializer.validated_data['mobile'], serializer.validated_data['due_date']]) ) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) and this is my task: logger = get_task_logger(__name__) @celery_app.task(name="apps.insurance.tasks.send_message_insurance_reminder") def send_message_insurance_reminder(title, mobile, due_date): logger.info('send message insurance reminder') # return send_reminder_message(title, mobile, due_date) return f'{title} _ {mobile} _ {due_date}' What is the correct way to create a periodic task and execute the task at the date that the user enters? Thanks. -
ERROR: Encountered errors while bringing up the project. DJANGO Docker
Successfully built 112f09badeb6 Successfully tagged be-django-nw_nginx:latest be-django-nw_db_1 is up-to-date Recreating cb0d468ab8a2_be-django-nw_web_1 ... error ERROR: for cb0d468ab8a2_be-django-nw_web_1 Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: for web Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: Encountered errors while bringing up the project. i try docker image prune, docker system prune and i remove .env and i make it again but doesnt work. what should i do?? -
Int object is not callable in the code ${{order.get_cart_total}}
I have the following code in the model, while calling the get_cart_total int not callable or unsupported operand type(s) for +: 'int' and 'method'appaers I am expecting to get total from get_cart_total class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total @property def get_cart_total(self): items = self.get_cart_items() for item in items: total += item.get_total() return total class OrderItem(models.Model): ORDER_ITEM_TYPE = ( ('type1', 'Collection1'), ('type2', 'Collection2'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) collection_type = models.CharField(max_length=255, choices=ORDER_ITEM_TYPE) collection1 = models.ForeignKey(Collection1, on_delete=models.SET_NULL, null=True, blank=True) collection2 = models.ForeignKey(Collection2, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() def get_total(self): if self.collection_type == "type1": return self.collection1.price * self.quantity elif self.collection_type == "type2": return self.collection2.price * self.quantity -
Is there a way to isolate a foreign key from its related model using django?
I am building a django website that displays the prices of items in a shop. Each item belongs to a category so I mande category a foreign key that can have one or more items. `class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class ShopItem(models.Model): itemName = models.CharField(max_length=64) price = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.itemName` However, in the html, I am unable to obtain both the category and the shop item I tried the following... `---snip--- {% used_category = [] %} {% for item in shopitem_list %} {% if item.category not in used_category %} <tr> <td>item.category</td> <td></td> <td></td> </tr> <tr> {% for rel_item in shopitem_list %} {% if rel_item.category == item.category %} <td></td> <td>rel_item.itemName</td> <td>rel_item.category</td> {% endif %} {% enfor %} </tr> {% endif %} {% endfor %}` I was hoping this would help me create a table where all the items are sorted below their respective categories but I got an error instead: TemplateSyntaxError at / Invalid block tag on line 18: 'used_category', expected 'endblock'. Did you forget to register or load this tag? -
Upload file into a model that contains foreignkeys
I have successfully created a template, view and path that allows users to upload data from a csv file directly into a model. I'm experiencing issues however with a model that contains a foreignkey. I was expecting this to be a problem but am sure there's a workaround. So I have a model called VendorItem: class VendorItem(models.Model): sku = models.CharField("SKU", max_length=32, blank=True, null=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name="Vendor name", related_name="vendor") vendor_sku = models.CharField("Vendor's SKU", max_length=32) model = models.CharField("Model number", max_length=32, blank=True, null=True) description = models.CharField("Description", max_length=64, blank=True, null=True) pq = models.DecimalField('Pack quantity', max_digits=7, decimal_places=2, default=1) price = models.DecimalField("Price", max_digits=10, decimal_places=2) upc = models.IntegerField("UPC", blank=True, null=True) # 12-digit numeric barcode ian = models.CharField("IAN", max_length=13, blank=True, null=True) # 13-digit alphanumeric international barcode status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=1) # Model metadata class Meta: unique_together = ["sku", "vendor"] unique_together = ["sku", "vendor_sku"] verbose_name_plural = "Vendor items" # Display below in admin def __str__(self): return f"{self.vendor_sku}" The vendor field is retrieved from the Vendor model (which is from another app might I add): class Vendor(models.Model): number = models.IntegerField("Vendor number", unique=True, blank=True, null=True) name = models.CharField("Vendor name", max_length=64, unique=True) region = models.CharField("Vendor region", max_length=64, blank=True, null=True) status = models.CharField(max_length=20, choices=VENDORSTATUS_CHOICES, default=1) # Display below in admin … -
Django reset password error from django.auth 'TypeError at /password_reset/'
I override default django reset password html and i want to send instruction to user email When im trying to send instruction to registered user email i have an error "path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType" setting.py EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_HOST = 'tech.unica-eng.ru' <- thats my company smtp server but i tried mail.ru smtp server and still not working EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_mail@tech.unica-eng.ru' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False SERVER_EMAIL = 'tech.unica-eng.ru' -
how to add new language in django 3
I want to add new language. it is turkmen (tm) I spent a lot of time but I can't resolve it please help me to resolve it PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) gettext = lambda s:s LANGUAGES = ( ('ru', gettext('Russia')), ('tm', gettext('Turkmen')), ) EXTRA_LANG_INFO = { 'tm': { 'bidi': False, 'code': 'tm', 'name': 'Turkmen', 'name_local': u"Turkmence", }, } import django.conf.locale from django.conf import global_settings import django.conf.locale LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO global_settings.LANGUAGES = global_settings.LANGUAGES + [("tm", 'Turkmenche')] -
why would you separate a celery worker and django container?
I am building a django app with celery. I tried composing a docker-compose without a container for the worker. In my Dockerfile for django, an entrypoint running the celery worker and django app: ... python manage.py migrate celery -A api worker -l INFO --detach python manage.py runserver 0.0.0.0:8000 The celery will run using this order but not django runserver. I have seen in tutorials that they separated the django container from woker container or vice-versa. I do not see the explanation for this separation. I also observed that the two python container (django, worker) has the same volume. How can celery add tasks if it has a different environment with django? In my mind there would be two django apps (the same volume) for two containers only 1 running the runserver, and the other one running the celery worker. I do not understand the separation. -
How to raise 404 as a status code in Serializer Validate function in DRF?
I have written a validate() function inside my serializer. By default, Serializer Errors return 400 as a status code. But I want to return 404. I tried this: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): current_user = self.context.get("request").user user = data.get("user") if user!=current_user: raise ValidationError({'detail': 'Not found.'}, code=404) return data But it still returns 400 as a response in status code. How to do it? -
Keep getting 404 on some URLs
Having followed the guide to setup django, postgres and nginx in digitalocean, am get different results for different urls. Am using ubuntu 20 and python 3.10 <IP>:8000 => is working perfectly well <IP> => 404 Not Found <https://DomainName> => Showing the html page but Not showing the static files <https://www.DomainName> => 404 Not Found Where am I messing up?? -
The 'image' attribute has no file associated with it django
I am doing an ecommerce project for deployment in pythonanywhere.com, some error is coming I would really appreciate if any one could help me to find out the problem as I am a basic learner TIA I have two MySQL tables and i tried to add more records error -
Send data from list application to create new customer django
I have a problem, I would like to transfer the appropriate field parameters from one list to the form for creating something else. The names of the fields match but they are not the same in both and I would like to send only those that are the same. Example - I have a list of requests and on this list I have a button next to each request to be able to immediately add a customer from this request and send the appropriate fields to this form. How i need to do that? I tried to work in templates and forms and views but I couldn't do it anywhere -
what is the most efficient way of running PLaywright on Azure App Service
I am hosting Django application on Azure that contains 4 Docker images: Django, React, Celery beats and Celery worker. I have celery task where use can set up python file and run Playwright. Question What is the best way to run Playwright. Ascan see in my Dockerfile below I am installing chromium usuing playwright install but I am not sure if it is the best approach for this solution: FROM python:3.9 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update && apt-get -y install netcat && apt-get -y install gettext RUN mkdir /code COPY . /code/ WORKDIR /code RUN pip install --no-cache-dir git+https://github.com/ByteInternet/pip-install-privates.git@master#egg=pip-install-privates RUN pip install --upgrade pip RUN pip_install_privates --token ${GITHUB_TOKEN} /code/requirements.txt RUN playwright install --with-deps chromium RUN playwright install-deps RUN touch /code/logs/celery.log RUN chmod +x /code/logs/celery.log EXPOSE 80 -
why the signals don't work = create profile when user register
why the signals don't work = create profile when user register i wannt to know the is ----- settings INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -----model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): return self.user def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) why code dont work why code dont work -
Very slow database query migrating from django 1.8 to django 3.2
I migrated a project from django1.8 to django3.2. I'm using the same database but the function I use to build a report is four times slower (8 seconds on Django1.8 and 30/40 seconds with django3.2). The database is MySQL version 5.7 (I also tried version 8.0.32 but nothing changed). This is the query: qs = PartitaDanno.objects.filter(incarico__cliente_intestatario_fattura_id=8006 ).select_related('incarico', 'anagrafica_assctp', 'incarico__naturaincarico' ).prefetch_related('rate' ).order_by('-incarico__anno', '-incarico__numero', 'pk') PartitaDanno is a table with 16000 rows and the model has 215 fields (I know..I didn't write it). The result of this query are just 1700 rows..a very small result. The unusual thing is that even if I use a simple query on this model like qs = PartitaDanno.objects.filter(incarico__cliente_intestatario_fattura_id=8006) It takes 20 seconds to iterate through result of this basic query..I don't understand. The raw sql query is the same in both versions of Django. This is the first queryset raw query: SELECT `sinistri_partitadanno`.`id`, `sinistri_partitadanno`.`created`, `sinistri_partitadanno`.`modified`, `sinistri_partitadanno`.`incarico_id`, `sinistri_partitadanno`.`tipo`, `sinistri_partitadanno`.`tipologia_controparte`, `sinistri_partitadanno`.`fase`, `sinistri_partitadanno`.`competenza_giurisdizionale`, `sinistri_partitadanno`.`soggetto`, `sinistri_partitadanno`.`anagrafica_assctp_id`, `sinistri_partitadanno`.`luogo`, `sinistri_partitadanno`.`compagnia_id`, `sinistri_partitadanno`.`riferimento_compagnia`, `sinistri_partitadanno`.`tipo_di_danno`, `sinistri_partitadanno`.`tipo_lesioni`, `sinistri_partitadanno`.`tipologia_vittima`, `sinistri_partitadanno`.`modello_veicolo`, `sinistri_partitadanno`.`targa_veicolo`, `sinistri_partitadanno`.`riserva_iniziale`, `sinistri_partitadanno`.`riserva_parziale`, `sinistri_partitadanno`.`data_richiesta_danni_ctp`, `sinistri_partitadanno`.`reiezione_cautelativa`, `sinistri_partitadanno`.`data_reiezione_cautelativa`, `sinistri_partitadanno`.`importo_richiesto_da_ctp`, `sinistri_partitadanno`.`data_incarico_nostro_perito`, `sinistri_partitadanno`.`tipologia_perizia`, `sinistri_partitadanno`.`nominativo_perito`, `sinistri_partitadanno`.`data_perizia_negativa`, `sinistri_partitadanno`.`motivazioni_perizia_negativa`, `sinistri_partitadanno`.`data_interlocutoria_inviata_dal_perito`, `sinistri_partitadanno`.`importo_stimato_dal_perito`, `sinistri_partitadanno`.`data_ricezione_perizia_dal_nostro_perito`, `sinistri_partitadanno`.`riparazione_antieconomica`, `sinistri_partitadanno`.`data_incarico_medico_legale`, `sinistri_partitadanno`.`data_ricezione_perizia_dal_nostro_medico_legale`, `sinistri_partitadanno`.`data_invio_offerta_tramite_transazione_quietanza`, `sinistri_partitadanno`.`data_reiezione_indennizzo_risarcimento`, `sinistri_partitadanno`.`pagamento_parziale`, `sinistri_partitadanno`.`capitale`, `sinistri_partitadanno`.`data_pagamento_capitale`, `sinistri_partitadanno`.`anagrafica_patrocinatore_id`, `sinistri_partitadanno`.`tipo_patrocinatore`, `sinistri_partitadanno`.`cf_piva_patrocinatore`, `sinistri_partitadanno`.`numero_rif_patrocinatore`, `sinistri_partitadanno`.`spese_legali`, `sinistri_partitadanno`.`data_pagamento_spese_legali`, `sinistri_partitadanno`.`integrazione_capitale`, `sinistri_partitadanno`.`data_pag_integraz_capitale`, `sinistri_partitadanno`.`integrazione_spese_legali`, `sinistri_partitadanno`.`data_pag_integraz_spese_legali`, `sinistri_partitadanno`.`note_generali`, `sinistri_partitadanno`.`note_pagamenti`, `sinistri_partitadanno`.`cessione_del_credito`, `sinistri_partitadanno`.`veicolo_sostitutivo`, … -
Model not detected by Django, even with `app_label` referencing to an existing app
I have a Django project with an application called data. The app is installed in the INSTALLED_APPS as follows: 'base.apps.MyAppConfig' with the AppConfig: class MyAppConfig(AppConfig): name = 'application' verbose_name = 'My App' label = 'application' path = f"{os.environ.get('APP_DIR')}/application" default = True I have the models defined like this: ### data/models/base/basemodel.py class MyBaseModel(models.Model): # ... fields ... Meta: app_label: `application` However, Django is not finding the models, and if I run makemigrations Django responds No changes detected, and on migrate, the app application does not appear on the Operations to perform. The Model should be detected so the Django detects migrations to apply === Context: Django Application reference: doc Django Models reference: doc -
djagno rest error: Cannot use the @action decorator on the following methods, as they are existing routes
I need to write a viewset for user's profile, in which methods like retrieve do not recieve pk as parameter but get user's id from authentication token. but by writing a new action for this methods: class ProfileViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): serializer_class = ProfileSerializer def get_object(self): return self.request.user @action(detail=False) def retrieve(self, request, *args, **kwargs): pass this error is raised: Cannot use the @action decorator on the following methods, as they are existing routes ... one way to do this is by writing custom methods: class ProfileViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericViewSet, ): serializer_class = ProfileSerializer def get_object(self): return self.request.user @action(detail=False) def retrieve_profile(self, request, *args, **kwargs): pass but is there a way to avoid this error and still using default methods? -
How to display a docstring in UI with flask?
I am importing a python script into my flask web app as such def register_tasks_in_db(): from haz import tasks as hz tasks = {f'{modname}': importlib.import_module( f'haz.tasks.{modname}') for importer, modname, ispkg in pkgutil.iter_modules(hz.__path__)} with app.app_context(): stored_tasks = Task.query.all() for stored_task in stored_tasks: if stored_task.name in tasks.keys(): _ = tasks.pop(stored_task.name) current_app.logger.info(f'{stored_task.name} already exists in db') for name, obj in tasks.items(): tasks = Task(name=name) tasks.save() app = create_app() app.secret_key = app.config['SECRET_KEY'] worker = create_celery_app(app) # a Celery object register_tasks_in_db() @app.shell_context_processor def make_shell_context(): return {'db': db, 'User': User, 'Institution': Institution, 'Image': Image, 'Series': Series, 'Study': Study, 'Device': Device, 'Task': Task, 'Report': Report} if __name__ == "__main__": app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5001))) Each of this tasks contains a docstring. How do I access and display the dosctring in the UI? -
has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
enter image description here has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response django-restframework -
Django template - global template namespace as parameter value for inclusion tag
I have a Django template for rendering tables which I can successfully include in my other templates. I takes a prefix and a namespace parameter, where the namespace is a key within the rendering context: {% include "table.html" with prefix=name|add:"_" namespace=rubric1 %} and in the template I use e.g.: {% for object in namespace.object_list %} ... {% endfor %} My rendering context looks like this: context = { 'some_var': ..., 'rubric1': { 'object_list': ..., 'direction': ..., 'orderby': ..., 'total': ..., 'page': ..., ... }, 'rubric2': { 'object_list': ..., ... }, } Now I want to use this template in a ListView, where those keys live at the root of the context namespace: context = { 'some_var': ..., 'object_list': ..., 'direction': ..., 'orderby': ..., 'total': ..., 'page': ..., ... } How do I tell the inclusion tag to use the root of the rendering context as namespace? Is there a special variable for this? E.g.: {% include "table.html" with prefix=name|add:"_" namespace=global_template_namespace %} Or can i somehow use a with context? E.g.: {% with global_template_namespace as ns %} {% include "table.html" with prefix=name|add:"_" namespace=ns%} {% endwith%} I have also thought about simple_tag that directly returns the context, but couldn't manage to use … -
How to return form values and upload file at the same time in Django?
I am a beginner at Django. I want to let users fill in Form and upload a file to the specific folder at the same time, and get the form value they filled in. Here is my forms.py from django import forms class UserForm(forms.Form): first_name= forms.CharField(max_length=100) last_name= forms.CharField(max_length=100) email= forms.EmailField() #file = forms.FileField() # for creating file input My functions.py (this function is to let users upload a file to the path 'mysite/upload/'.) def handle_uploaded_file(f): with open('mysite/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) My index.html <head> <meta charset="UTF-8"> <title>User Information Form</title> </head> <body> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="Submit" name="submit" value="Submit"/> </form> {% if submitbutton == "Submit" %} <h1> Your first name is {{firstname}}</h1> <h1> Your last name is {{lastname}}</h1> <h1> Your email is {{emailvalue}} </h1> {% endif %} </body> <script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'dcenter':'p3'},{'cp_id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html> My views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserForm from mysite.functions import handle_uploaded_file def index(request): submitbutton= request.POST.get("submit") firstname='' lastname='' emailvalue='' student = UserForm(request.POST, request.FILES) form= UserForm(request.POST or None) … -
Null value error, I am using Django rest framework and when I want to get enrolled data inside login response it gives me null instate of the values
I want to get enrolled courses for individual student with login I put enrolled model inside the login response put it will give me null instate of courses here is me output and code output: { "token": "4b6d75942dbbbcc484fb6c556b1ce6ebf2c73142", "user": { "id": 14, "username": "enrolltestt", "mobile_no": "07746505150", "is_student": true, "device_id": "" }, "is_student": true, "enrolled": [ { "course": null, "student": null, "is_active": false } ] here is my views.py class CustomAuthToken(ObtainAuthToken): def post(self,request,*args,**kwargs): serializer=self.serializer_class(data=request.data, context={'request':request}) serializer.is_valid(raise_exception=True) user=serializer.validated_data['user'] token,created=Token.objects.get_or_create(user=user) enrolled=StudentCourseEnrollSerializer(context=self.get_serializer_context()).data, return Response({ 'token':token.key, 'user':UserSerializer(user, context=self.get_serializer_context()).data, 'is_student':user.is_student, 'enrolled':enrolled }) can someone help me -
Problem serving Django "polls" tutorial under lighttpd: 404 page not found
I am following the Django polls tutorial, which is working 100% with the built-in development server (python3 manage.py runserver). I have set up lighttpd to serve django through UWSGI and that seems to be working fine but for one glitch: the URL passed to django seems to have been modified. My lighttpd configuration is basically this: ... server.modules += ("mod_scgi","mod_rewrite") scgi.protocol = "uwsgi" scgi.server = ( "/polls" => (( "host" => "localhost", "port" => 7000, "check-local" => "disable", )) ) The Django tutorial mapping looks like: # tutorial1/urls.py urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] # polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] However when I hit http://localhost:8080/polls/ in the address bar, it produces an 404 error. If I add an extra /polls to the URL then it works just fine. My goal with this exercise is to be able to serve this app switching from and to both servers without needing to modify configuration files each time. What do I need to do on the lighttpd.conf side to make lighttpd interchangeable with Django's own internal dev server? I have tried to add the following url.rewrite …