Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resume a method that sends a Django signal before the action in the signal handler terminates?
I have 3 models for Exchange, Market and Candle linked with Foreignkey relations. One of my methods do a for loop through all markets objects and creates new Candle objects. Now, as soon as a new object is created I need to check if the market is updated and do more stuff, so I decided to use Django signals. My problem is that when a post_save signal is triggered the for loop is paused until the end of the action in the signal handler is terminated. How could I bypass this? models.py class Exchange(models.Model): name = models.CharField(max_length=12, blank=True, null=True) def update_markets_price(self): for market in Market.objects.filter(exchange=self): # do stuffs Candle.objects.create(market=market, exchange=self, data=data) # Trigger post_save signal update = True class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, null=True) class Candle(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) data = JSONField(null=True) signal.py @receiver(post_save, sender=Candle) def my_handler(sender, instance, created, **kwargs): if created: while not updated: time.sleep(2) do_stuffs() # This is never executed because the for loop never ends For example here the while remains False because the for loop is in pause mode and it never terminates. I could find a solution for this very specific case but sometimes I need to let the … -
the production server does not have a file or an invalid directory django
the project has a function for generating qr code: class QrCreate(LoginRequiredMixin, View): def get (self, request, admission_id): eq = EquipmentWorker.objects.get(id=admission_id) return render(request, 'inventory/qr_detail.html',context={ 'eq': eq}) def post(self, request, admission_id): eq = EquipmentWorker.objects.get(id=admission_id) qr = False global data if request.method == 'POST': qr = True data = request.POST['data'] img = make(data) img.save("inventory/static/images/test.png") else: pass return render(request, 'inventory/qr_detail.html',context={ 'eq': eq, 'data': data}) path to qr-filetest.png -/home/user/dj/app/inventoryengine/inventory/static/images views.py path - /home/user/dj/app/inventoryengine/inventory gunicorn command = '/home/user/dj/inventory/bin/gunicorn' pythonpath = '/home/user/dj/app/inventoryengine' bind = '127.0.0.1:8001' workers = 5 user = 'user' limit_request_fields = 32000 limit_request_fields_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=inventoryengine.settings' nginx server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header Access-Control-Allow-Origin *; } on the local-manage.py server the function works, but on the production-gunicorn server it gives an error: [Errno 2] No such file or directory: 'inventory/static/images/test.png' -
Cancel Button in View leading to previous page
I tried to implement a cancel button via a mixin, but fail to get the correct URL. I want to go back to the page before the CreateView if the user presses "cancel" - if that should fail, I want the user to end up in index. views.py: class CancelButtonMixin(object): def post(self, request, *args, **kwargs): if "cancel" in request.POST: if request.META.get('HTTP_REFERER') != None: url = request.META.get('HTTP_REFERER' , '/') else: url = reverse_lazy("index/") return redirect(url) else: return super(CancelButtonMixin, self).post(request, *args, **kwargs) class SomeCreateView(CancelButtonMixin, CreateView): model = SomeModel template_name ="..." form_class = SomeFormsetName success_url = reverse_lazy('index/') forms.py: class SomeFormsetName(ModelForm): required_css_class = "required" class Meta: model = SomeModel fields = ("one", "two", "three", "four") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout(Row(Column(Field('one')), Column(Field('two', css_class='form-control')), css_class='form-row'), Submit('submit', 'Save price', css_class='btn-primary'), Submit('cancel', 'Cancel', css_class='btn-secondary', formnovalidate='formnovalidate'), Field("three", type="hidden"), Field("four", type="hidden")) my problem is that the url parameter holds exactly the url I am at, not the one from the previous page. How can I correct this behavior? url in my example will refer to http://127.0.0.1:8000/partprice_update/2 -
Google recaptcha not working on Django form framework
I am trying to follow this tutorial to load an invisible google recaptcha tag to my Django reset password form: https://medium.com/@mihfazhillah/how-to-implement-google-recaptcha-v3-on-your-django-app-3e4cc5b65013 Here's the full HTML of my attempt: {% extends 'base.html' %} {% block content %} {% load i18n static %} {% load crispy_forms_tags %} <script src="https://www.google.com/recaptcha/api.js?render=<MY SITEKEY HERE>"></script> <script> $('document').ready(function submitResetForm() { grecaptcha.ready(function () { grecaptcha.execute("<MY SITEKEY HERE>", {action: 'homepage'}).then(function (token) { $('input#id_recaptcha').val(token); }); }); }); </script> <div class="container" style="background-color:white;font-family:Roboto Condensed,Roboto,Charcoal, sans-serif" > <div class="row justify-content-center" style="margin-bottom:10; padding-bottom:10;"> <div class="col-md-4 pt-4"> <h2 class="text-center pb-1" style="font-size:large;font-weight:bold">RESET PASSWORD</h2> <div class="text-center row"> <p>Enter your email address below, and we’ll email instructions for setting a new one.</p> </div> <form id="reset-password-form" method="POST" class="form-group"> <div class="row"> {% csrf_token %} <div style="color:red;">{{ form.non_field_errors }}</div> <div class="form-group col-md-12"> {{ form.email|as_crispy_field }} </div> {{ form.recaptcha }} <div class="form-group col-md-12"> <input onclick="reCaptcha()" id="submit" type="submit" class="btn btn-primary btn-block" value="Reset password"> </div> </div> </form> </div> </div> </div> {% endblock %} Using the test codes supplied here: https://developers.google.com/recaptcha/docs/faq and below: Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe I was able to get a recaptcha tag on my webpage (with the warning message disclaimer). However I wasn't able to get any response in my form. When I replace these test keys with my real … -
Create method of Serializer class not getting called
I've viewset which has create method and my viewset is ModelViewSet. Serializer class also has create method which handles relationships manually. Ideally create from viewset should call create method of serialzier but it's not happening in my case. Using DRF from browser works like a charm for me but hitting endpoint from test fails it and from logs I can tell viewset create method is not calling create of serializer. I know perform_create has this logic serializer.save() but it's working when I try to hit via postman or browser DRF view but not working in case of tests: Here's my viewset: class MyViewSet(CacheResponseMixin, viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) filter_backends = (DjangoFilterBackend,) def get_serializer_class(self): return serializer.MySerializer def create(self, request, *args, **kwargs): data = request.data.copy() context = {} self.prepare_and_set_read_only_data(data, context) serializer = serializers.MySerializer(data=data, context=context) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # This doesn't trigger create method in case of tests but works fine in case of postman request headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Here's my serializer: class MySerializer(serializers.ModelSerializer): # all serializer fields . . . def create(self, validated_data): some_data = self.context.get('some_Data') instance = Model(**validated_data) instance.save() instance.some_data.set(some_data) instance.save() Here's my test: def test_create_using_api(self): response = self.client.post(self.list_path, self._instance_data(), format='json') program = Model.objects.last() assert response.status_code == 201 -
Django POST validated fields disappearing (NOT NULL constraint failed)
I have a Django project with some models. The one which is giving me trouble is this one: class Job(models.Model): patient = models.CharField(max_length=64, null=False, blank=False) how = MultiSelectField(choices=HOW_CHOICES, default=1) with_who = MultiSelectField(choices=WITH_WHO_CHOICES, default=1) accessories = MultiSelectField(choices=ACCESSORIES, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=False, blank=False) scheduled = models.DateTimeField(null=True, blank=True) arrived = models.DateTimeField(null=True, blank=True) started = models.DateTimeField(null=True, blank=True) completed = models.DateTimeField(null=True, blank=True) scheduled_end = models.DateTimeField(null=True, blank=True) detected_end = models.DateTimeField(null=True, blank=True) approved = models.BooleanField(default=False) area_start = models.ForeignKey(Area, on_delete=models.CASCADE, null=False, related_name='jobs_start') area_end = models.ForeignKey(Area, on_delete=models.CASCADE, null=False, related_name='jobs_end') comment = models.CharField(max_length=256, null=True, blank=True) worker = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='jobs_worker') I have this URL to GET, POST, PUT and DELETE. router.register(r'jobs', views.JobList) The view linked to inherits from ModelViewSet: class JobList(LoginRequiredMixin, viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobsSerializer For my understanding, simply by inheriting from ModelViewSet the API handles GET, POST and PUT by default. That's probably why in the web API I see the form with the data to POST (see this screenshot). The view handles the GET perfectly, but the problem comes at the POST request. As you can see in the screenshot, there are only 3 fields to be filled for the POST data. But in the model I have more fields declared … -
Django Not Applying CSS File From App on 404 Page
Django 3.0.8 Python 3.7.x I've got a django project with a few apps. I'm trying to make some 'default' error pages for like 400, 403, 404, 500 errors. I've done that and the appropriate templates display - but without any styling or JS. In the 404 error page, I'm trying to link to the CSS from one of the apps so the correct styling gets applied - but in the console I see this error: Refused to apply style from 'http://127.0.0.1:8000/static/launcher/dist/css/launcher.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The file exists there, however. That particular CSS file lives in two places: in the app directory and it also lives in the STATIC_ROOT because I ran the python manage.py collectstatic command. The STATIC_URL is set to /static/ The CSS file is located at: project_dir/launcher/static/launcher/dist/css/launcher.css project_dir/static/launcher/dist/css/launcher.css My 404 template lives at: project_dir/templates/404.html My link to the CSS looks like this: <link rel="stylesheet" type="text/css" href="{% static 'launcher/dist/css/launcher.css' %}" /> My project URL's look like this: urlpatterns = [ path("admin/", admin.site.urls), path("", include("launcher.urls")), path("app2/", include("app2.urls")), path("app3/", include("app3.urls")), path( "robots.txt", TemplateView.as_view( template_name="robots.txt", content_type="text/plain" ), ), path( "favicon.ico", RedirectView.as_view( url=staticfiles_storage.url("favicon.ico"), permanent=False ), name="favicon", ), ] … -
How to use Generic View for a child
I am starting to learn how to use the generic view. Considering that we`ve got a foreign key to parent. How can I create a child view using Generic View? Would that be the same way we are creating the parentview? views?.py class ChildCreateView(generic.CreateView): template_name = "app/create_child.html" model = Child form_class = ChildForm success_url = reverse_lazy("app:index_child") models.py class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) views1.py class ParentCreateView(generic.CreateView): template_name = "app/create_parent.html" model = Parent form_class = ParentForm success_url = reverse_lazy("app:index_parent") -
slack profile.set ignoring user in any case
I'm testing out slack integration with python, what I'm trying to do is update status of any user through api. I installed an app in my workspace & added permissions for user.profile.write & users:read & used SlackClient. The status update works fine but it is only updating the status of the person who created the app. You can find the profile.set api here which I'm using to set profile status, when I pass the user in params it is completely ignored, if I pass it in json as shown below then it throws an error saying invalid_user whereas same user is working perfectly in users.info api call. print(sc.api_call(api_method='users.info', params={'user':'U017KQ996KY'})) print(sc.api_call(api_method='users.profile.set', params={'user':'U017KQ996KY'}, json={ 'user': 'U017KQ996KY', 'profile': { "status_text": "on vacation", "status_emoji": ":airplane:" } } )) I'm at a loss here as to why this is happening, I even tried passing X-Slack-User with id in headers & that was ignored as well. It's either throwing an error or just changing status for the owner of the app. Any help or sense of direction is appreciated. -
How to hide POST form in Django REST framework?
I have a problem and I' hope someone could help me. I have Django REST framework form like this: and I would like to do a simple thing: hide POST form (in the red rectangle) when the user is not logged in. I just don't know how to do it, because all I have is model, view that inherits from ListCreateAPIView and serializer inhgeriting from ModelSerializer. -
How can I fix "bad interpreter" error after I renaming my django project in PyCharm?
I recently renamed my Django project in Pycharm and now I have many errors associated with Python. From my MAC terminal when I try and run: $ django-admin startproject mobileproject or $ pip install django I get: -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python3.7: bad interpreter: No such file or directory In Pycharm when I open most of my Django projects I now get: invalid python interpreter selected for the project Below was the original structure of my project: project ---project ---app ---models.py ...etc ---project ---settings.py ...etc ---manage.py ---venv To rename my Django project in Pycharm I right clicked on the root folder "project" and selected refactor/rename/rename project. For the rest of the folders I right clicked and selected refactor/rename and I was only given rename directory so I chose that. Below shows how I renamed my project folders. newproject ---newp ---newapp ---models.py ...etc ---newpp ---settings.py ...etc ---manage.py ---venv After doing this I have all the errors listed above. Even when trying to start a new project with django-admin startproject. I feel like the Python executable is in the wrong directory but I have no idea. Please Help! -
Data is not saved in database but primary key is created Django Fullcalendar
Currently actual data is not save in database but when ever register button is clicked after I input data, an empty data will be saved and primary key will be created. There is no error being posted anywhere but an empty data is saved. I'm using Django Framework for backend and as front-end, I mainly use Javascript and HTML. For database, I use Sqlite. I think the most important part in the data transport is in the Ajax part but since I just used Ajax and Javascript for the first time, I still don't know a lot of thing. Please help me. script.js function initializePage() { $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, navLinks: true, timeFormat: 'HH:mm', selectable: true, selectHelper: true, eventSources:[{ url: '/fullcalendar/calendar', method: 'GET', failure: function(){ alert("PROBLEM!!!"); }, } ], select: function(start, end, resource) { // 日付選択された際のイベント // ダイアログタイトル設定 $("#dialogTitle").text("スケジュール登録"); // タイトル初期化 $("#inputTitle").val(""); // 備考初期化 $("#inputDescription").val(""); // ボタン制御 $("#registButton").show(); $("#updateButton").hide(); $("#deleteButton").hide(); // ダイアログ表示 $('#inputScheduleForm').on('show.bs.modal', function (event) { setTimeout(function(){ $('#inputTitle').focus(); }, 500); }).modal("show"); // 日付ピッカーの設定 $('#inputYmdFrom').datetimepicker({locale: 'ja', format : 'YYYY年MM月DD日', useCurrent: false }); $('#inputYmdTo').datetimepicker({locale: 'ja', format : 'YYYY年MM月DD日', useCurrent: false }); $('.ymdHm').datetimepicker({ locale: 'ja', format : 'YYYY年MM月DD日 HH時mm分' }); // 開始終了が逆転しないように制御 … -
Client-Side Encryption using boto3
So i'm using "S3Boto3Storage" as my django "file storage" and i have done "server side encryption" for file upload but i want to do "client side encryption" before file uploads to aws. I have read few articles about client side encryption but those solutions are helpful when file is already uploaded to aws. Pls help -
How to pass Django choice key to template using Elasticsearch
I'm trying to implement faceted search using django-elasticsearch-dsl and python-elasticsearch-dsl, but I am having problems mapping keys to values, when displaying them in templates. Let's say I have a model like this. class Record(models.Model): # Other fields.. status = models.CharField(max_length=255, choices=( (0, 'New'), (1, 'Pending'), (2, 'Completed') )) @property def status_to_string(self): return self.get_status_display() Then I defined my Document @registry.register_document class RecordDocument(Document): status = fields.KeywordField(attr='status_to_string') class Index: name = 'records' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Record fields = ['status'] When the data get's indexed, the value of the status field is a string (New, Pending,..), but the value in the database is still an integer. I then continue adding FacetedSearch like this. class RecordSearch(FacetedSearch): index = 'records' doc_types = [RecordDocument, ] fields = ['status'] facets = { 'status': TermsFacet(field='status') } And run the actual search rs = RecordSearch() response = rs.execute() So far so good, now when I access the results in the template, I can see statuses with respective document count. My question and concern is; the search keyword in this case is a string New or Pending and not 0 or 1. As far as I can see, my search is working, but it … -
'MoneyField' object has no attribute 'serialize'
I have model Product with field MoneyField im /products/models.py class Product(SeoModel, ModelWithMetadata, PublishableModel): name = models.CharField(max_length=128) currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, default=settings.DEFAULT_CURRENCY, ) price_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, ) price = MoneyField(amount_field="price_amount", currency_field="currency") Also, i have model MoneyField(NonDatabaseFieldBase) in django_prices/models.py. My views.py is: from .models import Product from .serializers import ProductListSerializer from rest_framework import generics class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductListSerializer class ProductDetail(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductListSerializer and serializers.py: from rest_framework import serializers from .models import Product class ProductListSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['name', 'id'] and when i go to url i have error: AttributeError at /ru/products/api/ 'MoneyField' object has no attribute 'serialize' Request Method: GET Request URL: http://127.0.0.1:8000/ru/products/api/ Django Version: 2.2.6 Exception Type: AttributeError Exception Value: 'MoneyField' object has no attribute 'serialize' Can you help me? Thank you! -
Why 'select_realted()' doesn't work in django models?
I'm trying to make 'inner join' from superclass and subclass. The codes of superclass and subclass are as below: SUPERCLASS: class Group(models.Model): # [column name] = model.[column type].(conditions of column) address = models.CharField(max_length=255, blank=True, null=True) area = models.FloatField(blank=True, null=True) num_person = models.CharField(max_length=255, blank=True, null=True) severity_average = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'group' def create_group(self, address, area, num_person, severity_average): self.address = address self.area = area self.num_person = num_person self.severity_average = severity_average try: self.save() # execute query return True except: return False def retrieve_group(self, address=None, area=None, num_person=None, severity_average=None): queryset = Group.objects try: if address is not None: queryset = queryset.filter(address=address) if area is not None: queryset = queryset.filter(area=area) if num_person is not None: queryset = queryset.filter(num_person=num_person) if severity_average is not None: queryset = queryset.filter(severity_average=severity_average) return tuple(queryset.values()) except: return () def update_group(self, address=None, area=None, num_person=None, severity_average=None): if address is not None: self.address = address if area is not None: self.area = area if num_person is not None: self.num_person = num_person if severity_average is not None: self.severity_average = severity_average try: self.save() # execute query return True except: return False def delete_group(self): try: self.delete() return True except: return False SUBCLASS: class Facility(models.Model): # [column name] = model.[column type].(conditions of column) facility_type … -
Fetch ID of a model and save to other model's foreign key field in django
I have a User model using AbstractBaseUser. I have a model Employee using Model class. I want that when a user is created through sign up, the user inherits all the fields of Employee model. I have made a OnetoOne relation between User model and Employee. But after creating an user when I query employee model, I can not find any data related to the created User. User manager: class UserManager(BaseUserManager): """ Creates and saves a User with the given email and password. """ def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email,username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user User: class User(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserManager() def get_full_name(self): # The user is identified by their email address … -
Counting page views for a User uploaded PDF in Django
I have a webapp where a user can upload a pdf. I want to be able to see how many times the PDF is viewed by other user, all of which would be anonymous users. At the moment I didn't have to write a view to view the PDF, in the 'view PDF' button i Just link the uploaded PDF's URL, which directs to the PDF document. Button to view PDF <a href="{{ doc.File.url }}" class="btn btn-outline-secondary" style="margin: 2px;">View PDF</a> The issue arises, in that when a user uploads a PDF doc, i create a qr code which contains the URL of that doc. So i only want to count the views that are from the qr scan in, and not redirected from the button. How can i do this seeing as i don't actually have a view to render the PDF? One way i was thinking of is writing a return redirect view, with an incrementer for the views instance in the model? or to use the Django F() statement to pull in the views instance and then increment it. Any ideas? -
Render Folder Structure on webpage with Django
I have a root folder, containing other folders and XML-files. I would like to show the folder contents just like in windows-explorer on my webpage. For example: folder_1 txt_file_1 txt_file_2 folder_2 folder_3 txt_file_3 How can I render the directory in this way? -
trying to save django form data after submit to a thankyou page with details
If I add redirect url in form submit page, the page is redirecting but the form data is not being saved to db. If I remove the redirect url, form data is getting saved but my redirect doesn't work. I need to redirect to a page with the details of the event along with a thank you message. Please let me know where I am going wrong.. #forms.py class UserForm(forms.ModelForm): class Meta: model = webinar_user fields = ['first_name', 'last_name', 'email_id', 'contact_no', 'city', 'state','postal_code','country','company'] #views.py def post_detail(request, slug): template_name = "site/new_form.html" event = get_object_or_404(webinar_event, slug=slug) # event = get_object_or_404(webinar_event, pk=post_id) # success_url = "events:thankyou" user_data= None if request.method == "POST": user_form = UserForm(data=request.POST) print("form") if user_form.is_valid(): print("form valid") user_data= user_form.save(commit=False) user_data.event= event req= user_data.save() subject = 'Thank You for registering for the webinar' context={'first_name':user_data.first_name, 'title':event.title, 'description':event.about_event, 'event_date':event.event_date, 'event_time':event.event_time, 'event_duration':event.event_duration} message = get_template('site/emails/thank_you.html').render(context) email_from = settings.EMAIL_HOST_USER email_id = user_form.cleaned_data['email_id'] recipient_list = [email_id, ] email = EmailMessage(subject, message, email_from, recipient_list) email.content_subtype = 'html' email.send() return HttpResponseRedirect('events:thank_you', kwargs={'id':req.id}) ) else: user_form = UserForm() return render( request, template_name, { "event": event, "user_data":user_data, "user_form": user_form }, ) def thank_you(request, id): event = webinar_event.objects.get(pk=id) return render(request, 'site/thankyou.html', {'event' : event}) html code <div class="testbox"> {% if event.event_image … -
Nested serializers getting only one instance of a model
I'm working on my first project. I'm working with a headless wagtail cms. The api should print out the link i put in in the wagtail admin page. I added multiple links to every team but only the last made team prints out a link and its only the first link i made for that team. I presume i'm using the wrong foreign keys but i just can't figure it out. serializers.py class LinkChannelSerializer(serializers.ModelSerializer): class Meta: model = LinkChannel fields = ['name', 'icon'] class TeamLinkSerializer(serializers.ModelSerializer): channel = serializers.SerializerMethodField() class Meta: model = TeamLink fields = ['team', 'channel', 'url', 'title'] def get_channel(self, obj): channel = LinkChannel.objects.filter(team_links=obj) print(channel) return LinkChannelSerializer(channel, many=True).data class TeamsSerializer(serializers.ModelSerializer): value_tag_motivations = ValueTagMotivationsSerializer(many=True) hero = ImageSerializer() logo = ImageSerializer() links = serializers.SerializerMethodField() class Meta: model = TeamPage fields = [ 'id', 'title', 'tagline', 'value_tags', 'logo', 'hero', 'value_tag_motivations', 'vacation_policy', 'tech_stack', 'team_members', 'locations', 'interview_process', 'mission_statement', 'links' ] def get_links(self, obj): links = TeamLink.objects.filter(team=obj) print(links) return TeamLinkSerializer(links, many=True).data models.py class TeamPage(Page): """A team profile""" parent_page_types = [JobboardHomePage] subpage_types = ["OpenPositionPage", "OpenPositionLink"] logo = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Company logo, square", ) tagline = models.CharField(max_length=255) hero = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Hero banner for the top of the page, … -
Unable to save empty list to Django ArrayField
I have a Django model from django.db import models from django.contrib.postgres.fields import ArrayField class Website(models.Model): id = models.BigAutoField(primary_key=True, verbose_name='ID') status = models.BooleanField(default=True) meta = ArrayField(base_field=models.CharField(max_length=200, null=True), default=list) I'm using following serializer to save data to the DB: class WebsiteConfigSerializer(serializers.ModelSerializer): class Meta: model = Website fields = ('status', 'meta') When I'm trying to save the following data, I'm getting error: { "status": true, "meta": [] } #ERROR: # "meta : This list may not be empty." Is it not possible to save an empty list to an ArrayField ? When I'm not passing the field at all, the value getting stored is {NULL}. Also during initial migrations, since I had added a default value as list, all my existing entries had "meta" value as {} If the empty list value is not allowed at all, how come this got saved during initial migration ? -
Django Admin loading without css
I had created a new Django app, and I noticed it's admin page was loading without css. I set the STATIC_URL and the STATIC_ROOT in settings.py according to this solution, but it still does not work. After some digging, I found this error when I open Chrome Dev Tools on Admin Page [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/responsive.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/login.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page] Refused to apply style from 'http://[my_web_page]/static/admin/css/responsive.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page]/:1 Refused to apply style from 'http://[my_web_page]/static/admin/css/login.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. [my_web_page]/:1 Refused to apply style from 'http://[my_web_page]/static/admin/css/base.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking … -
Is there a way to filter in Django using the equal magic method?
Some background just in case there is a better way to do this other than the way I am trying: I am requesting data of a rest API. When the data is received I want to check if a model containing this data already exists. The rest API does not give an ID for data entry so I cannot use this to see if a model instance already exists. I have created an equal magic method for the model that checks several of the fields to see if they are equal and returning the appropriate boolean. This works fine when checking for example if instance == other_instance. The issue arises when I try to filter or get to check the DB. breach = Breach.objects.get(self=breach1) I could check by specifying the fields each time but this would lead to some duplicated code over time and make the code base maintainable. I am still newish to using Django so apologies if Django has a simple way of doing this. -
Django formset with queryset doesn't fill out all the fields of formset with initial values
I have the following code to get a formset: patient = Patient.objects.get(id=pk) prescription = Prescription.objects.get(patient=patient) formset = PrescriptionLineFormSet(queryset=prescription.line_prescription.all()) The form is very simple too: PrescriptionLineFormSet = modelformset_factory(PrescriptionLine, fields='__all__', extra=1, ) in the template I display the formset in a table: {{ formset.management_form }} <table class="table table-bordered"> {{formset.as_table}} </table> The problem is that not all attributes of the PrescriptionLine model are set with the initial values. Not even the default values are given. But one field is always set no matter what solution out of the internet I try (and I tried so many). Why is that happening? Why is it only working for the first field?