Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Spider in Django views
I want to use scrapy spider in Django views and I tried using CrawlRunner and CrawlProcess but there are problems, views are synced and further crawler does not return a response directly I tried a few ways: # Core imports. from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings # Third-party imports. from rest_framework.views import APIView from rest_framework.response import Response # Local imports. from lrn_scrap.spiders.google import GoogleSpider class ForFunAPIView(APIView): def get(self, \*args, \*\*kwargs): process = CrawlerProcess(get_project_settings()) process.crawl(GoogleSpider) process.start() return Response('ok') is there any solution to handle that and run spider directly in other scripts or projects without using DjangoItem pipeline? -
How can I do authentication on the site and the built-in Users model and my own Employer Django
Happy New Year! I ran into a problem I am making a job search site on Django, I have the following logic: Authorization and authentication of ordinary job seekers using Django's built-in model - User Also separate authorization and authentication for users who provide work, i.e. employers, which are placed in my own model Employer Here is my Employer model class Employer(AbstractUser): full_name = models.CharField(max_length=150, verbose_name="Ім'я") main_office_city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Місто головного офісу') phone_number = models.ForeignKey(Phone, on_delete=models.CASCADE) email = models.CharField(max_length=50, unique=True, verbose_name='Email') hashed_password = models.CharField(max_length=120, default='') date_joined = models.DateTimeField(verbose_name='Дата реєстрації', default=timezone.now) def __str__(self): return self.full_name class Meta: verbose_name = 'Роботодавець' verbose_name_plural = 'Роботодавці' I read in the documentation that to create your own authentication system you can use the imitation from the AbstractUser class But in my case this is not the best choice, because AbstractModel adds its own fields by default. That is, I think that I need to either somehow make it so that the AbstractUser class does not add its fields, or think of some other authentication logic using another technology Maybe someone has some ideas how it can be done? -
in a django pass a value from a function to the get_context_data method in a view
I am trying to pass a value from a function to the get_context_data method in a view if i just try simple pass value from def to another def in python it works def function_1(): color = "red" size ="xxl" return color,size def function_2(): color,size = function_1() print(f"{color} {size} ") function_2() but when i try to apply it in django from custom def to get_context data it doesn't work def customDef(): color = "red" size ="xxl" return color,size def get_context_data(self,*arg,**kwargs): context = super(Myview,self).get_context_data(*arg,**kwargs) query = self.request.GET.get('item') color,size = customDef() context['posts'] = Mymodels.objects.filter(Q(name__startswith=query) ) if i try to add a parameter to get_context_data like this def get_context_data(self,customDef,*arg,**kwargs): I have an error message "missing 1 required positional argument" thank for help and happy new year -
I'm trying to reset the admin password I'm the admin panel
I'm using the django admin panel with jazzmin theme, I have created a link to reset the admin password after the reset is complete and trying to login in again. I got redirect to this path /account/profile/ There is no current url with this path I,m expecting to be redirect to the admin panel -
How do I get all candidate in a position
Am trying to query every candidate that belong to a specific position and loop through it using the django template in my html. If I have just one position/poll all candidate will display in my frontend, but once i add another position/poll then the list of the candidate will not display again def index(request): context = {} instruction = "" positions = Position.objects.order_by('priority').all() for position in positions: candidates = Candidate.objects.filter(position=position) for candidate in candidates: votes = Votes.objects.filter(candidate=candidate).count() if position.max_vote > 1: instruction = "You may select up to " + str(position.max_vote) + " candidates" else: instruction = "Select only one candidate" context = { 'positions': positions, 'candidates': candidates, 'votes': votes, 'instruction': instruction } return render(request, 'poll/index.html', context) {% block content %} <div class="row"> <div class="mt-5"> {% for p in positions %} {{ instruction }} <h1>{{ p.name }}</h1> <p>{{ p.description }}</p> {% for c in candidates %} <h1>{{ candidate.fullname }}</h1> {% endfor %} {% endfor %} </div> </div> {% endblock %} -
File upload not working, nothing is uploaded to media root
Here's the model class Document(models.Model): file = models.FileField() The template {% extends 'another-form.html' %} {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% bootstrap_field form.files %} <button class="btn btn-success col">Upload</button> </form> {% endblock %} Form class and view: from django import forms from django.urls import reverse_lazy from django.views.generic import FormView class UploadDocumentForm(forms.Form): files = forms.FileField(widget=forms.FileInput(attrs={'multiple': True}), label='') class UploadDocumentView(FormView): template_name = 'upload-document.html' form_class = UploadDocumentForm success_url = reverse_lazy('index') def form_valid(self, form): Document.objects.bulk_create([Document(file=f) for f in self.request.FILES]) return super().form_valid(form) when the form is submitted, I get these responses: [02/Jan/2023 14:43:13] "POST /upload-document/ HTTP/1.1" 302 0 [02/Jan/2023 14:43:14] "GET /upload-document/ HTTP/1.1" 200 70636 [02/Jan/2023 14:43:17] "GET /upload-document/ HTTP/1.1" 200 70635 and nothing is uploaded to settings.MEDIA_ROOT which is specified in settings.py and works for models.ImageField. I also tried file = models.FileField(upload_to=settings.MEDIA_ROOT) which is useless, included for confirmation, also: class UploadDocumentForm(forms.Form): files = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), label='' ) -
Creating a django form dynamically from a database model
I am trying do dynamically build a Questionnaire with its Questions and answers based on the information stored in a database. Database model: class Questionnaire(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) sequence = models.PositiveSmallIntegerField() text = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.text class QuestionAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=200) points = models.PositiveSmallIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.text I am trying to get a Form, that - based on a Questionnaire id passed to a view would render all Questions with their Questionanswers (as radio buttons). I started to design a Form that displays all the answers for a specific Question, if the question_id gets handed to a form: class QAForm(forms.Form): answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=QuestionAnswer.objects.none()) def __init__(self, *args, question_id=None, **kwargs): super().__init__(*args, **kwargs) if question_id is not None: print(question_id) self.fields['answer'].queryset = QuestionAnswer.objects.filter(question=question_id) This works, but I struggle to build a formset of QAForms that would cycle through the question_ids and show their answers for the user. I found https://forum.djangoproject.com/t/pass-different-parameters-to-each-form-in-formset/4040/2 - which seems to handle dynamic parameters to the formset forms. At this time though, i am starting to think that such solution is … -
getting error: subprocess-exited-with-error when dockerizing my project for the package reportlab, but this is not added in my requirements.txt
getting the following error when dockerizing my project this is the error message Collecting reportlab>=3.3.0 Downloading reportlab-3.6.12.tar.gz (4.5 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 3.1 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] ##### setup-python-3.10.6-linux-x86_64: ================================================ ##### setup-python-3.10.6-linux-x86_64: Attempting build of _rl_accel ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/rl_accel' ##### setup-python-3.10.6-linux-x86_64: ================================================ ##### setup-python-3.10.6-linux-x86_64: =================================================== ##### setup-python-3.10.6-linux-x86_64: Attempting build of _renderPM ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/renderPM' ##### setup-python-3.10.6-linux-x86_64: =================================================== ##### setup-python-3.10.6-linux-x86_64: will use package libart 2.3.21 !!!!! cannot find ft2build.h [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ERROR: Service 'demo_project' failed to build : Build failed this is my requirements.txt file' celery==5.2.7 channels==3.0.4 Django==3.2.11 django-celery-beat==2.2.1 django-celery-results==2.3.1 django-environ==0.9.0 django-filter==21.1 Pillow==9.0.1 psycopg2-binary==2.9.3 pyotp==2.6.0 razorpay==1.3.0 redis==4.4.0 xhtml2pdf==0.2.5 and this is my dockerfile FROM python:3.10.6-alpine ENV PYTHONUNBUFFERED 1 … -
How to capture Django CSFR Cookie in Postman?
I am trying to send my first POST request that isn't handled inside Django to my Django server. I read in several tutorials from 3 years ago that I should somehow see the CSFR token value in the cookie, eg.: https://hackernoon.com/automatically-set-csrf-token-in-postman-django-tips-c9ec8eb9eb5b I cannot achieve that and I have problems finding tutorials on how to capture that cookie to use it later. Please help. -
Does't work django-admin startproject mfdw_site
I installed Python,and then Django.I checked that Django is installed with --version command.I installed VENV. Now I want to start a Project,but django-admin startproject my_site does't work. I'm working with VScode. What can I do? -
Appropriate Framework or Library in python for agent based or actor model algorithm service
Which Framework or Library in python suitable for agent based or actor model algorithm service? I've worked on develop new algorithmic trading platform which tend to active 24/7 for multiple crypto markets. I use django as a platform's framework but I don't know which framework or library are suitable for design agent-based or actor-based services. I used to django framework as a my framework to develop my algorithmic trading platform. But for scale up project I faced some problems to choose right framework -
selected option is not unselected while clicking on the element twice
select2 ajax select elements clicking once and unselect element clicking twice. This is by default .but in my case element is selecting by one click but not unselecting clicking twice. what is the problem here views.py def search(request): query=request.GET.get("q") print(query) vid=Video.objects.filter(tags__name__icontains=query).order_by("name").distinct() print(vid) vid_list=\[{'id':k.id,"name":k.name,"tags":','.join(k.tags.names())} for k in vid\] print(type(vid_list)) return JsonResponse(vid_list,safe=False) home.html <div class="form-group"> <label>Example of multiple select</label> <select class="form-control" multiple placeholder="Choose skills" id="some" required> </select> </div> scripts <script> $("p").click(function(){ $.ajax({ url:"{%url 'home' %}", success:function(data){ alert("this is a ajax alert") } }) }) $("#some").select2({ ajax:{ url:"{% url 'search'%}", data: function(params){ return{ "q":params.term } }, processResults:function(data){ console.log(data) return{ results:data.map(function(item){ return{id:item.id,name:item.name,tags:item.tags} }) } }, delay:250, cache:true, }, minimumInputLength:1, closeOnSelect: false, allowClear:true, multiple:true, placeholder: "Search Video", templateResult:function(repo){ console.log(repo) if (repo.loading) return repo.name; if (repo && !repo.selected){ return` <span> ${repo.name}(${repo.tags}) </span> ` } }, templateSelection:function(data){ return` <span > ${data.name} </span> ` }, escapeMarkup: function (markup) { return markup; }, }) </script> Now i want to know what is the reason behind this .i mean why option is not unselecting when i click second time on the option -
How to include a select2 multiselect box in a OpenStreetMap widget for Django Admin?
I have the following model, which contains a MultiPolygonField: class MyArea(models.Model): polygon = models.MultiPolygonField( _("Polygon"), null=False, blank=False, ) I have this model registered in Django Admin: @admin.register(MyArea) class MyAreaAdmin(admin.GISModelAdmin): # --> GISModelAdmin to render an OSM map for `polygon` pass Which renders the map, as desired: But now, I would like to include a select2 multiselect box on top of this map, where the user would be able to search another model in our database that contains polygons for administrative regions. class Locality(models.Model): polygon = models.MultiPolygonField( _("Locality Polygon"), null=False, blank=False, ) So the user would still be able to draw manual polygons if he wants too. But he could also search and select Locality objects that already contain complex administrative regions (polygons). Once a Locality object is selected the map should be refreshed to include the new region. How should I go about this? I have tried to create custom templates and custom forms, but did not got anywhere close to the solution -
Chart in javascript doesn't change color
I have a problem in javascript with building financial candlestick charts. I made a chart with apex.js and it displays the correct data where it should be but the color of the chart doesn't change, when the stock price is going up candlestick should be green when it goes down it should be red but on some stocks candlestick in always red and on some stocks it works fine. Here are the images, both charts use the same code but different data because it's different stock but that doesn't mean it should be displayed like this. Here is code for chart: <div id="chart"> </div> <script> var options = { series: [{ name: 'OHLC', data: [ {% for stock in stocks %} { x: new Date("{{stock.date}}"), y: [Number("{{stock.open}}"), Number("{{stock.high}}"), Number("{{stock.low}}"), Number("{{stock.price}}")], }, {% endfor %} ] }, ], chart: { type: 'candlestick', }, title: { text: '{{ticker}} Stock ', align: 'center' }, yaxis: { tooltip: { enabled: true } } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> I am using Django in the backend so here is a function that returns chart data: @login_required(login_url='stock:login') def chart(request, ticker): stocks = Stock.objects.filter(ticker = ticker).order_by('date') context = {'stocks':stocks, 'ticker':ticker} return render(request, 'stock_app/chart.html', … -
2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form
I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning. Views.py def Client_Update(request, Client_id): ClientUpdate = TestModel.objects.get(pk=Client_id) ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate) if request.method == 'POST': if ClientUpdates.is_valid(): ClientUpdates.save() return redirect('/Client_Details') return render(request, 'GymApp/ClientUpdate.html', {'ClientUpdate':ClientUpdate, 'ClientUpdates':ClientUpdates}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Home, name='Home'), path('ClientList/', views.Client_list, name='Client_list'), path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'), path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'), path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'), path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'), path('Search/', views.Search, name='Search'), ] HTML Page {% extends 'GymApp/Layout.html' %} {% block content %} <h1>Updating status</h1> <form action="" method="POST"> {% csrf_token %} <div class="mb-3"> <input type="text" class="form-control" name="Name" placeholder="Client's Name"><br> <input type="text" class="form-control" name="Surname"placeholder="Client's Surname"><br> <select name="Gender" class="form-control"> <option selected disabled> Open this select menu </option> <option value="Male">Male</option><br> <option value="Female">Female</option> </select> </div> <div class="mb-3"> <input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br> <input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br> <button type="button" onclick="calculation()">Calculation update</button> <br> </div> <br> <div class="mb-3"> <input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br> <select name="Activity_log" class="form-control"><br> <option selected disabled>Open this select menu</option> <option value="Not Active">Not Active</option><br> <option value="Active">Active</option> </select> <br> <button type="submit">Finalising update!</button> </div> </form> <script> function calculation(){ … -
Django-kafka. Distributed requests to an endpoint to handle millions of requests
Can anyone share some source to read. I have an api (django app), lots of people use it, i want this api handle millions requests. How can i make it distributed so this api can handle many requests. Should i make producer and consumer in one file? -
usage of require_POST in django
I wanna know is there a usage or security tip to use required-post or require-get decorators in django? from django.views.decorators.http import require_GET, require_POST -
Django: Webp conversion fails and creates empty picture element while all debugging efforts fail
I'm trying to create an upload form to upload multiple images that need to be converted to webp. Everything worked fine until i added the webp conversion bits. I tried adding exceptions and print statements to track down the issue but it just doesn't print any exceptions. Instead it shows all signs of success and creates an empty "picture" element in the database. I`m using the django cookiecutter project with pillow. models.py def upload_gallery_image(instance, filename): # Print a message to indicate that the function was called print(instance, filename) return f'galleries/{instance.facility.id}/{filename}' class Picture(models.Model): picture = models.ImageField(upload_to=upload_gallery_image) class Gallery(models.Model): facility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='tourphotos') pictures = models.ManyToManyField(Picture, related_name='galleries') views.py class GalleryView(APIView): parser_class = (FileUploadParser,) def post(self, request): # Extract the facility ID and list of pictures from the request print('post method called') facility_id = request.data.get('facility') pictures = request.data.getlist('pictures') print(facility_id, pictures) facility = get_object_or_404(Facility, id=facility_id) try: gallery = Gallery.objects.get(facility=facility) except Gallery.DoesNotExist: gallery = Gallery.objects.create(facility=facility) for picture in pictures: print('for loop executing') try: webp_image = BytesIO() image = Image.open(picture) image.save(webp_image, format='webp', quality=75) print(webp_image) file_object = ContentFile(webp_image.getvalue()) print(file_object) picture_obj = Picture.objects.create(picture=file_object) print(picture_obj) gallery.pictures.add(picture_obj) print(gallery) except Exception as e: print(type(e)) continue webp_image.close() serializer = GallerySerializer(gallery) return Response(serializer.data, status=201) serializers.py class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture … -
DRF .as_viewset on {'post': 'list'} return attribute error?
I am trying to send some text: example: "Hello World" to DRF end-point. This endpoint on receiving this text is to send me a e-mail with the text. When I hit the end-point with Postman, I get the error: Internal Server Error: /api/errors Traceback (most recent call last): File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/viewsets.py", line 117, in view handler = getattr(self, action) AttributeError: 'ErrorMsgViewSet' object has no attribute 'list' To test this out: urls.py from django.urls import path from .api import * urlpatterns = [ path('api/errors', ErrorMsgViewSet.as_view({'post': 'list'}), name='errors'), ] # I tried .as_view(), which gave me an error to change to the above format # i tried using router.register() and got errors on using generic.GenericAPIview api.py from rest_framework import viewsets from email_alerts.serializers import ErrorsSerializer class ErrorMsgViewSet(viewsets.GenericViewSet): serializer_class = ErrorsSerializer permission_classes = [ ] def post(self, request, *args, **kwargs): print(request.data) models.py from django.db import models # Create your models here. class ErrorsModel(models.Model): error_msg = models.CharField(max_length=5000, blank=True, null=True) serializers.py from rest_framework import serializers from email_alerts.models import ErrorsModel class ErrorsSerializer(serializers.ModelSerializer): error_msg = serializers.CharField( required=False, allow_null=True, allow_blank=True) class … -
Django: How to show a message in a custom admin action with a download?
I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen. I tried this way: @admin.action(description=gettext_lazy("Download CSV")) def download_csv(self, request, queryset): self.message_user(request=request, message=gettext_lazy("Downloaded")) return self.create_csv() @staticmethod def create_csv() -> HttpResponse: headers = {'Content-Disposition': f'attachment; filename="download.csv"'} response = HttpResponse(content_type='text/csv', headers=headers) response.write(codecs.BOM_UTF8) csv.writer(response).writerows([['example']]) return response actions = [download_csv] Does anyone know how to do it correctly? Thanks. -
My celery-beat works locally but not in production?
my task: @shared_task def my_test(): # Executes every 2 minutes UserStatisticStatus.objects.filter(id=1).update(loot_boxes=+234) print('Hello from celery') app.conf.beat_schedule = { 'my-task-every-1-minutes': { 'task': 'user_statistic_status.tasks.my_test', 'schedule': crontab(minute='*/1'), }, } my settings: if 'RDS_DB_NAME' in os.environ: CELERY_BROKER_URL = 'redis://<myurl>/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-central-1', 'polling_interval': 20, } CELERY_RESULT_BACKEND = 'redis://<myurl>/1' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_TASK_ROUTES = { 'my_test': {'queue': 'default'}, } my celery.py : import os from celery import Celery from project import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('celery_app') app.conf.task_routes = { 'my_test': {'queue': 'default'}, } app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The worker connects and shows the tasks correctly and the beat starts too but nothing happening. I've tested it with the local redis server and everything works fine. Any help will be much appreciated Thank you -
Reverse for 'profile' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile/(?P<user_id>[0-9]+)\\Z']
I'm getting the above error and I've tweaked my code based on answers I saw online but still getting the same error VIEWS.PY ` def profile(request, user_id): profile_user = User.objects.get(pk = user_id) # user_profile = Profile.objects.get(user=user_object) profile_post = NewTweet.objects.filter(user = user_id) post_count = len(profile_post) follower = request.user.id user = user_id if Followers.objects.filter(follower=follower, user=user).first(): button_text = "Unfollow" else: button_text = "Follow" context = { "profile_user": profile_user, "post_count": post_count, "profile_post": profile_post, "button_text": button_text, } return render(request, "network/profile.html", context) ` URL.PY path("profile/<int:user_id>", views.profile, name="profile"), LAYOUT.HTML ` <li class="nav-item"> <a class="nav-link" href="{% url 'profile' user.id %}"> <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon"> Profile </a> <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon"> Profile </li> ` MODELS.PY class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) def __str__(self): return self.user.username class Followers(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) # follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') # target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') def __str__(self): return self.user In Layout.html, I try '{{ user.id }}' to see what is reflecting and it shows 'None'. Please advise In Layout.html, I try '{{ user.id }}' to see what is reflecting and it shows 'None'. I also adjusted this as adviced in a different thread but same … -
django unknown column after migrations
I have a weird problem. I've added the below to the model. I have run migrations, but I still still get the error no such column: Linked_OKR linked_OKR = models.ForeignKey(okrtasks, on_delete=models.CASCADE,db_column='okrid', blank=True, null=True) Weirdly in the admin view, it also shows up not in bold, unlike all other columns Any idea what's going on? -
Django - Linking Models
I am using django and I want to link two models. The first model is comment and the second model is image. I want to have multiple images for one comment and an image should be linked with only one comment. Comment model has its fields and image model looks like this: class Image(models.Model): image = models.ImageField(upload_to=f'{hash(id)}/', null=True, blank=True) def __str__(self): return self.image.name And this is the model that I used to link comment and image: class CommentImage(models.Model): comment = models.OneToOneField(Comment, models.CASCADE, null=True) image = models.ForeignKey(Image, models.CASCADE, null=True) class Meta: ordering = ["-id"] verbose_name = _("Image") verbose_name_plural = _("Images") def __str__(self): return self.image.image.name Here is the admin panel of django: enter image description here As you can see I could be able add only one image and there is no button as well to add multiple image. What should I change to be able to add multiple images? I have tried using ManytoManyField and removing comment field from CommentImage but it did not work. -
How to communicate django api with frontend react native?
I have a django application and I have a react native app. I am running the android emulator from android studio. And now I try to connect the backend with the frontend. I studied the example from: https://reactnative.dev/docs/network And the example url: https://reactnative.dev/movies.json' works. But now I try to connect with my own localhost data. So this is my component: import { ActivityIndicator, FlatList, Text, View } from "react-native"; import React, { Component } from "react"; export default class App extends Component { constructor(props) { super(props); this.state = { data: [], isLoading: true, }; } async getMovies() { try { const response = await fetch("http://127.0.0.1:8000/api/movies/"); const json = await response.json(); this.setState({ data: json.movies }); } catch (error) { console.log(error); } finally { this.setState({ isLoading: false }); } } componentDidMount() { this.getMovies(); } render() { const { data, isLoading } = this.state; return ( <View style={{ flex: 1, padding: 24 }}> {isLoading ? ( <ActivityIndicator /> ) : ( <FlatList data={data} keyExtractor={({ id }, index) => id} renderItem={({ item }) => <Text>{item.title}</Text>} /> )} </View> ); } } But if I try to run this example. I get this error: Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 …