Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting get method when running post method
I created class based view where In get method I am calling html page activate.html. and created post method where I posting some json data. I want to redirect same page and want to post data. When I am running activate.html page I get it but when I click on button for activate user Its printing same which I print in get method views.py class ActivationView(View): def get (self, request, uid, token): print('get called in activate_user') return render(request, 'activate.html') def post(self, request, uid, token): print('UID : ', uid) print('Token : ', token) payload = json.dumps({'uid': uid, 'token': token}) print("payload : " , payload) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() djoser_url = getattr(settings, 'DJOSER.ACTIVATION_URL') post_url = web_url + djoser_url print('post_url : ' + post_url) response = request.post(post_url, data = payload) return HttpResponse(response.text) I want to print uid and token in json format when I click on post button from html. activate.html <form action="" method="post"> {% csrf_token %} <td input type="submit"><a href="" target="_blank" >Click Here For Activate Account</a></td> </form> -
Daphne + Channel v3 Deployment, RuntimeError: no running event loop
When I run systemctl start daphne I get the following error Traceback (most recent call last): File "/srv/www/portal/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/srv/www/portal/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "/srv/www/portal/lib/python3.8/site-packages/daphne/cli.py", line 232, in run application = import_by_path(args.application) File "/srv/www/portal/lib/python3.8/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/www/portal/portal/./portal/asgi.py", line 3, in <module> from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter File "/srv/www/portal/lib/python3.8/site-packages/channels/routing.py", line 10, in <module> from channels.http import AsgiHandler File "/srv/www/portal/lib/python3.8/site-packages/channels/http.py", line 9, in <module> from asgiref.sync import async_to_sync, sync_to_async File "/srv/www/portal/lib/python3.8/site-packages/asgiref/sync.py", line 304, in <module> class SyncToAsync: File "/srv/www/portal/lib/python3.8/site-packages/asgiref/sync.py", line 328, in SyncToAsync loop = get_running_loop() RuntimeError: no running event loop The service definition: [Unit] Description=daphne service PartOf=postgresql.service After=postgresql.service [Service] WorkingDirectory=/srv/www/portal/portal/ Environment=JSON_SETTINGS=/srv/www/portal/settings.json Environment=ASGI_THREADS=10 ExecStart=/srv/www/portal/bin/daphne -b 0.0.0.0 -p 8000 portal.asgi:application Restart=always KillSignal=SIGTERM NotifyAccess=all [Install] WantedBy=multi-user.target This is my asgi.py import os import django from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter os.environ.setdefault("DJANGO_SETTINGS_MODULE", "portal.settings") django.setup() from … -
Randomizing logic in python
Need to write a program using Randomizing logic(Python). It can be like a generic function which takes versions and probability as input and returns a version. Probability can be anything like 1/2,1/3,1/4,1/5 and versions should be equally distributed accordingly -
How to use 2 different keys of facebook (Social Auth) in one django API project?
I have to implement two different keys for 2 apps using facebook login in one single project and the keys facebook social auth 2 library is using only one and the keywords are similar in settings file how do i use both keys as i am not able to override the keys because i cant find from where it is using those keys. -
django .update() a foreign key
im having problems updating a fk. Views.py estandares = EstandarProducto.objects.select_related('recinto','producto','proveedor').prefetch_related (Prefetch('carreras')).filter(recinto=id_recinto) for proveedor in estandares: if proveedor.proveedor_id == None or proveedor == "": EstandarProducto.objects.filter(id=proveedor.id).update(proveedor_id=1) x=EstandarProducto.objects.get(id=proveedor.id) print("ID proveedor : ", x.proveedor.id ) Models.py class EstandarProducto(models.Model): '''''' costo_unitario_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) cantidad = models.IntegerField(default=0) total_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) recinto = models.ForeignKey(Recinto, related_name='estandares_producto', on_delete=models.CASCADE) producto = models.ForeignKey( Producto, related_name='estandares_producto', on_delete=models.PROTECT) proveedor = models.ForeignKey( Proveedor, related_name='estandares_producto', on_delete=models.CASCADE, blank=True, null=True) carreras = models.ManyToManyField(Carrera, related_name="estandares_productos", blank=True) class Proveedor(models.Model): '''Datos de contacto de un proveedor de cotizaciones o de estandar.''' nombre = models.CharField(max_length=500) direccion = models.CharField(max_length=1000, blank=True, null=True) correo = models.EmailField(blank=True, null=True) telefono = models.CharField(max_length=12, blank=True, null=True) def __str__(self): return f"{self.nombre} - {self.direccion}" The problem is the print return 1 as expected, but when i look at the database there is no changes. -
How to redirect from one view to another view in django?
I have created app in django. There is login page and corresponding admin.py. I have another page default.html and controlled by index.py. my template directory myappname --- AdminUsers --- login.html --- Layouts default.html admin.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password # if password is correct return render(request,'Layouts/home.html',context={"User":user}) return render(request,'AdminUsers/login.html') def default(request,user): return render(request,'Layouts/default.html',context={"User":user}) my login page link is localhost/8000/adminusers/login and I want to redirect to localhost/8000 after login. By this method, I am able to load the default.html but my link is not changing. Is there other way to do this? -
Problems with running Python in Virtual environments after Python update
I used Python 3.7 for many Django projects using virtual environments (venv) under Windows. The Python path was C:\Program Files\Python37\python.exe now I upgrated python to 3.9 and the current path is C:\Program Files\Python39\python.exe Now when I want to run Python in any of my past projects, for example python manage.py runserver I get the error No Python at 'C:\Program Files\Python37\python.exe' Which is quite normal. How could I update each project in order to accept the new path? Is there a way to do this or should I better downgrade to Python 3.7 and use it forever? Renaming the folder where Python is installed doesn't seem a good idea. It must surely be a configuration file to change, a variable to set or whatever. I'm relatively new with Python and I never faced this problem before. Could you help? -
Too many SQL queries with Django Admin many-to-many inline view
I have a 'diamond' relationship between four models. AlignedScan is basically a pay-load carrying model facilitating a many-to-many relationship between Scan and Alignment. Both Scan and Alignment have a to-one relationship to Scan Project. When trying to display a inline-list of AlignedScans in an Alignment detail window (in Django Admin), it works but is very slow due to two extra SQL queries being executed for each record. What am I doing wrong? These are my models: from django.contrib.gis.db import models from django.db.models import Count, Q class ScanProject_Manager(models.Manager): def get_queryset(self): return (super().get_queryset() .annotate(number_of_alignments=Count('alignments', distinct=True)) .annotate(number_of_usedscans=Count('scans', distinct=True, filter=Q(scans__used=True))) ) class ScanProject(models.Model): objects = ScanProject_Manager() slug = models.CharField(max_length=30,primary_key=True,) label = models.CharField(max_length=100,) #... class Scan(models.Model): name = models.CharField(max_length=24,) #... scanproject = models.ForeignKey( ScanProject, related_name='scans', on_delete=models.CASCADE, ) class Alignment(models.Model): aligned_when = models.CharField(max_length=13,) #... scanproject = models.ForeignKey( ScanProject, related_name='alignments', on_delete=models.CASCADE, ) class AlignedScan(models.Model): registered = models.BooleanField() x = models.FloatField(blank=True, null=True,) y = models.FloatField(blank=True, null=True,) z = models.FloatField(blank=True, null=True,) #... alignment = models.ForeignKey( Alignment, related_name='alignedscans', on_delete=models.CASCADE, \ ) scan = models.ForeignKey( Scan, related_name='alignedscans', on_delete=models.CASCADE, ) class AlignedScan_Manager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('scan') I've tried with and without the AlignedScan_Manager, I've tried using a plain-vanilla straight out of the box InlineModel: class AlignedScan_Inline(admin.TabularInline): model = AlignedScan and i've tried … -
Why my table value is not showing up in django template?
I retrieve my table in views and when i tried to use it in template is is not showing anything. This is my views file def index(request): attendances = attendance.objects.all() return render(request, "salary/index.html", {'attendance': attendances}) and this is my template code {% for attendances in attendance %} <th>{{attedances.id}}</th> {% endfor %} and this is my model class attendance(models.Model): id = models.AutoField staff_id = models.CharField(max_length=250, null=True) attendance = models.CharField(max_length=250, null=True) date = models.CharField(max_length=250) -
Django - How to implement DetailView, CreateView, and Updateview together in one View?
TrimType's CreateView and UpdateView will be implemented together by modal in Car's DetailView. Car's DetailView TrimType's CreateView Modal TrimType's UpdateView Modal models.py : class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): id = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True) typeName = models.CharField(max_length=50, blank=False, null=False) urls.py : app_name = 'brand' urlpatterns = [ ... url(r'^car/(?P<car_id>\d+)/$', car_views.CarDetailView.as_view(), name='car_detail'), # TrimType_id is transmitted by GET method. ... ] forms.py : class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='TrimType' ) car_detail.html : <div class="col-8"> <div class="text-right mt-3 mb-3"> <select class="form-control" id="slct_trim_type"> <option value="0">*TrimType*</option> {% for trimType in trimType_list %} <option value="{{ trimType.id }}" data-car-idx="{{ car.id }}" {% if trimTypeID == trimType.id %}selected{% endif %}>{{ trimType.typeName }}</option> {% endfor %} </select> </div> </div> <div class="col-4"> <div class="text-right mt-3 mb-3"> <a id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="add"></a> <a id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="modify"></a> <a id="btn_trimtype_delete" class="btn btn-danger btn-icon waves-effect waves-themed" data-toggle="tooltip" title="" data-original-title="delete"></a> </div> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">*TrimType* UpdateView</h3> <form method="post" class="form-horizontal" … -
Django admin page is looking for a template that does not exist
I had made a template for one of my project apps (not the admin page) and then deleted it. Now the admin page is looking for that template and giving a "Missing template error". Is there some sort of caching or internal method that admin routes are stored that remembers old settings somehow? -
DRF Django: Serializer: HOw to get list of other properties in many to many relations
I have the following class Foo(models.Model): something = models.TextField() bars = models.ManyToMany("app.Bar") class Bar(models.Model): example = models.TextField() class BarSerializer(serializers.ModelSerializer): class Meta: model = Bar fields = ["example"] class FooSerializer(serializers.ModelSerializer): testing = BarSerializer(many=True,source=bars) class Meta: model = Foo fields = "__all__" { "something": "Testing", "children": [ { "example": "Something else" } { "example": "Something else2" } ], "bars":[ "Something else", "Something else2", ] } What I see is "children": [ { "example": "Something else" } { "example": "Something else2" } ], What i want is "children": [ "example": "Something else", "example": "Something else2" ], -
How to use Post-save Signal when uploading document, and saving before and after altering document?
I want save document when uploaded and run pandas script and save that script but also to forward to user do download it. How to do it simple way? This is how I tried to do it, upload and save upload works, but pandas script is not working. def my_view(request): message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') ooutput = data.eval('e = column1 / d') ooutput.to_excel(writer, sheet_name=name) output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') newdoc.to_excel(writer, index=False) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) def results(request): documents = Document.objects.all() context = {'documents': documents} return render(request, 'results.html', context) -
Systemd service logging gets stuck by Enabling django logging
I am using systemd service to run my django project, I have also configured logging in my project settings as below: # Logging settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '{levelname} - [{server_time}] : {message}', 'style': '{', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'mode': 'a+', 'maxBytes': 1024 ** 2 * 2, 'filename': f'{BASE_DIR}/logs/debug_{datetime.date.today().strftime("%Y-%m-%d")}.log', 'formatter': 'django.server', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'mail_admins'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server', 'file'], 'level': 'INFO', 'propagate': False, }, } } It works fine when its run manually. But a problem occurs when I run its systemd service with systemctl, It gets stuck and neither does the systemctl start myservice print anything nor does it stop running. It does start my service though. Also when I run journalctl -xefu myservice the same thing happens, it does not print anything, also does not stop running until I hit Ctrl+C. This … -
DRF updating data using AJAX call
When I try to send data via the frontend to the serializer I get a HTTP 400 error. If I do it directly via the DRF browsable API it works though: model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class Product(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializer: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["id", "name",] class ProductSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() def update(self, instance, request): product = Product.objects.get(serial = instance) product.shipment = Shipment.objects.get(id = request["shipment"]["id"]) product.save() return instance class Meta: model = Product fields = ["serial", "shipment",] lookup_field = "serial" read_only_fields = ["serial",] ViewSet: class ProductViewSet(ModelViewSet): serializer_class = ProductSerializer lookup_field = "serial" http_method_names = ["get", "patch", "put"] def get_queryset(self): return Product.objects.all() AJAX call: $.ajax({url: `api/products/${serial}/`, dataType: "json", contentType: "application/json", type: "PUT", data: {"shipment": shipment[0]}, headers: {"X-CSRFTOKEN": csrf_token }, success: function () {window.location = "?msg=ok";}, error: function () {window.location = "?msg=error";} }); Browser output: PUT http://127.0.0.1:8000/api/products/d39f281f/ Status400 Bad Request VersionHTTP/1.1 Transferred400 B (111 B size) Referrer Policysame-origin Request payload: shipment=4 Response: {"shipment":["This field is required."]} or after some playing: JSON parse error - Expecting value: line 1 column 1 … -
Filter Django-Function-View Queryset for User.Request
Models.py class Experience(models.Model): user = models.ForeignKey(User, null=True, on_delete = models.CASCADE) company_name = models.CharField(max_length=100) company_address = models.CharField(max_length=200) post_held = models.CharField(max_length=30) year_from = models.CharField(max_length=20) year_to = models.CharField(max_length=20) info = models.TextField() def get_absolute_url(self): return reverse('resume') def __str__ (self): return self.company_name Views.py def Resume(request): experience = Experience.objects.filter(user = request.user) return render(request, 'resume.html', {'experience': experience}) Template <ul> {% for an_experience in experience %} <a href="{% url 'edit_experience' an_experience.pk %}"><li ><h5>{{ an_experience }},</h5></a> {{ an_experience.company_address }} - {{ an_experience.post_held }}</li> <small>{{ an_experience.year_from }} - {{ an_experience.year_to }}</small> <div> {{ an_experience.info }} </div> {% endfor %} </ul> if I use .all(), it is working perfectly but while trying to filter it using request.user nothing is displaying in the template file. -
Why can I run django Manage.py using Python3 manage.py run server
I tried running Python3 manage.py run server to run my django application but couldn't due to error. Error:Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. Note:python is running my pc and I have environment variable set too -
Django form submission Redirecting to wrong url
I am trying to take help from this tutorial and my own thing. It's supposed to be a marketplace. I have an app called Creator (vendors) I am trying to let the users add new products by themselves using views.add_product, add_product.html, and forms.py when I try to submit the add_product form, it gives this error Error Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/creator/ (I am not trying to redirect it to this page but rather 'url 'creator_overview'' Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('creator/', include('creator.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) creator/urls.py urlpatterns = [ path('sell_on_cosloo', sell_great_things, name='creator_signup'), path('creator_overview',creator_overview , name='creator_overview'), path('add_product',add_product , name='add_product'), ... ] creator/views.py @login_required def add_product(request): if request.method == 'GET': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.vendor = request.user.vendor product.slug = slugify(product.title) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request, 'creator/add_product.html', {'form': form}) creator/forms.py <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is-uppercase">Submit</button> </div> </div> </form> add_product.html {% extends 'core/base.html' %} {% block title %}Add product | {% endblock %} {% block content %} <h1 class="title">Add product</h1> <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div … -
Factory_boy not creating RelatedFactory in Trait
I've got a Purchase model and a PurchaseInfo model. PurchaseInfo has a foreign key to Purchase. I'm trying to modify an existing Factory for Purchase that will create PurchaseInfo at the same time using RelatedFactory since it's a reverse foreign key relationship. The only thing is that I wanted to use a Taint so that I could control the value of fields within PurchaseInfo. Normally when I create a Purchase like p = PurchaseFactory() the PurchaseInfo is created with null fields inside of it. If I create a Purchase like p = PurchaseFactory(info=True), so I can get the field modifications via the Taint, the PurchaseInfo is not created at all. I have a feeling that putting the RelatedFactory in a Taint is not the way to go. What is the correct way to do this? Models: class Purchase(Model): ... class PurchaseInfo(Model): purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE, unique=True, db_index=True) lock = DateTimeField(null=True) lock_by = ForeignKey(... class PurchaseInfoFactory(DjangoModelFactory): class Meta: model = PurchaseOrderInternalField lock = None lock_by = None class PurchaseFactory(DjangoModelFactory): class Meta: model = Purchase info = RelatedFactory(PurchaseInfoFactory, factory_related_name='purchase') class Params: info = Trait(internalfield=RelatedFactory(PurchaseInfoFactory, factory_related_name='purchase', lock=timezone.now() - relativedelta(months=1), lock_by=SubFactory(UserFactory, user_id=1))) -
How can I get information about the logged-in user in a Django application?
How can I get information about the logged-in user in a Django application? What I want to do is get the user information from Logged-in user and put additional information and store in a database(models.py). -
docker compose failing on gitlab-ci build stage
I am trying to build gitlab-ci but one of the stages is failing the build. I get stuck on build stage. it does not recognise python and i am trying to install it so i can build the image and get it tested with robot framework gitlab-ci.yaml image: python:latest services: - name: docker:dind entrypoint: ["env", "-u", "DOCKER_HOST"] command: ["dockerd-entrypoint.sh"] stages: - compile - build - test - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 DOCKER_TLS_CERTDIR: "" MOUNT_POINT: /builds/$CI_PROJECT_PATH/mnt REPOSITORY_URL: $AWS_ACCOUNT_ID.dkr.ecr.eu-west-2.amazonaws.com/apps_web TASK_DEFINITION_NAME: apps_8000 CLUSTER_NAME: QA-2 SERVICE_NAME: apps_demo ARTIFACT_REPORT_PATH: "app/reports/" before_script: - docker info - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE:web - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY unittests: stage: test before_script: - python -m venv env - source env/bin/activate - python -m pip install --upgrade pip - pip install -r app/app-requirements.txt variables: DOCKER_IMAGE_TAG: ${CI_REGISTRY_IMAGE}:${CI_COMMIT_TAG} image: ${DOCKER_IMAGE_TAG} script: - source env/bin/activate - python app/manage.py jenkins --enable-coverage artifacts: reports: junit: app/reports/junit.xml paths: - $ARTIFACT_REPORT_PATH expire_in: 30 days when: on_success only: refs: - merge_requests variables: - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "qa" migrations: stage: compile before_script: - python -m venv env - source env/bin/activate - pip install -r app/app-requirements.txt script: - python app/manage.py makemigrations artifacts: … -
Django rest: accessing all related objects using ForeignKey
I'm stuck and I don't know what's wrong... to me it's identical to the "Nested relationships" example in the DRF API guide but something is not right... MODEL class PlayerSquadra(models.Model): player = models.ForeignKey( 'app_player.Player', on_delete=models.CASCADE, verbose_name=_('giocatore'), related_name='player_squadraplayer', ) squadra = models.ForeignKey( 'app_stagione.Squadra', on_delete=models.CASCADE, verbose_name=_('squadra'), related_name='squadra_squadraplayer' ) def __str__(self): return '%s' % (self.player) URL router.register(r'squadraJSON/(?P<squadra>.*)', views.SquadraViewSet) VIEW class SquadraViewSet(viewsets.ReadOnlyModelViewSet): queryset = Squadra.objects.all() serializer_class = SquadraSerializer def get_queryset(self): laSquadra = self.kwargs['squadra'] queryset = Squadra.objects.filter(id=int(laSquadra)) return queryset SERIALIZER class PlayerSquadraSerializer(serializers.ModelSerializer): class Meta: model = PlayerSquadra fields = '__all__' class SquadraSerializer(serializers.ModelSerializer): playersquadra = PlayerSquadraSerializer(many=True, read_only=True) class Meta: model = Squadra fields = ['nomeSquadra','id','playersquadra'] What I get when I call http://192.168.0.102:8000/squadraJSON/26/ is: GET /squadraJSON/26/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "nomeSquadra": "prova2", "id": 26 } ] And no errors... While I expect something like this: GET /squadraJSON/26/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "nomeSquadra": "prova2", "id": 26 "playersquadra": [ {'id': 1, 'firstName': 'Michael', 'lastName': 'Jordan',...}, {'id': 2, 'firstName': 'Larry', 'lastName': 'Bird',...}, ... ], } ] Could you give me some hint why I'm not getting all the players belonging to Squadra with id=26? Thanks for helping -
how to know which url is hit in django graphql?
I am working on a django project, where graphql is used, I am not able to trace which function hit and from where error is coming, Please help -
Page not found (404) like button
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default='awesome') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) -
Django tests pass individually but fail when running together
I have a number of tests that all pass if I just run the file individually in Pycharm. But if run them as using the DiscoverRunner some of them fail. I know it must have something to do with the tests setup, so I am looking for input on how to debug this. Things I already tried based on other stackoverflow answers: Make sure all the testscases are django.test.TestCase. Most test load data from fixtures in the class definition. Make sure to call the super method where I define the tearDown method. I had two tests files that used mail.outbox when run together. But if I put them together in a package inside the test folder they suddenly passed. Any idea what could be causing this? Any tips on how to debug this?