Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PositiveBigIntegerField
So, im trying to work on my apps and I have PositiveBigIntegerField's in some of my models. I thought for sure it was already included with Django but now i'm starting to think otherwise. Whenever I run my server, im getting an error stating that AttributeError: module 'django.db.models' has no attribute 'PositiveBigIntegerField' Has anyone run into this problem before? -
Cannot assign requested address when connecting to Redis through Docker
Creating containers from my Django+Redis+React project and getting the error: Error 99 connecting to localhost:49157. Cannot assign requested address. When I visit the url localhost:8000 This is my docker-compose file: version: "3.8" services: redis: restart: always image: redis:latest ports: - "6379:6379" pairprogramming_be: restart: always depends_on: - redis command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - ./signup/.env - ./payments/.env - ./.env build: context: ./ dockerfile: Dockerfile ports: - "8000:8000" container_name: "pairprogramming_be" ... #Error 99 connecting to localhost:49153. Cannot assign requested address. This my .env file: DEBUG=1 DJANGO_ALLOWED_HOSTS=0.0.0.0 my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR django-project/peerplatform COPY requirements.txt ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . ./ EXPOSE 8000 CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000", "--settings=signup.settings"] Here is my settings.py incase the issue is here: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis:6379", # "TIMEOUT": 5 * 60, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "pairprogramming" } } ... CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "LOCATION": "redis://redis:6379", }, } ... REDIS_HOST = 'redis://redis:6379' REDIS_PORT = 6379 REDIS_PASSWORD = 'redispw' -
css is not working after deploying django application on aws with gunicorn nginx
I have deployed my django project on EC2 but the css is not working after deployement. I also ran collcectstatic command but still got unlucky, when I checked in nginx error.log it showing in front of css files that permission denied like this: 2022/07/18 17:38:01 [error] 2262#2262: *4 open() "/home/ubuntu/theoj/online_judge_project/staticindex.css" failed (13: Permission denied), client: 49.38.225.106, server: 13.126.144.76, request: "GET /static/index.css HTTP/1.1", host: "13.126.144.76", my project directory structure: online_judge_project/ account/ homesrc/ language/ media/ oj/ /*name of my project*/ settings.py problempg/ static/ /* folder containing css files*/ staticfiles/ /* folder made after running command collectstatics*/ template/ manage.py **settings.py: ** """ Django settings for oj project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from importlib.resources import path from pathlib import Path import os from .info import * EMAIL_USE_TLS = EMAIL_USE_TLS EMAIL_HOST = EMAIL_HOST EMAIL_HOST_USER = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD EMAIL_PORT = EMAIL_PORT # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR=os.path.join(BASE_DIR,'template') FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = … -
Redirect url is 127.0.0.1 even on server
I set the google login with allauth. SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } }, } It works in local(127.0.0.1) Now I deploy this program and try to use. When I clicked the login button, this url is published. https://accounts.google.com/o/oauth2/auth/oauthchooseaccount?client_id=89292334XXXX-kb8nu044m3p6t9njaeatptlptmibovag.apps.googleusercontent.com&redirect_uri=https%3A%2F%2F127.0.0.1%3A8011%2Fauth%2Fcomplete%2Fgoogle-oauth2%2F&state=GEPhIROU6BQKHIGx3jvAZ1kBboq3x35h&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20openid%20email%20profile&flowName=GeneralOAuthFlow However there still exists redirect_uri=https://127.0.0.1,so consequently, it redirect to 127.0.0.1 and fails(because the browser try to open local address.) how can I fix? -
Getting selected value from dropdown menu to remain when page refreshes
I am trying to figure out a way in Django to maintain the selected value in a dropdown menu, after the page refreshes. Here is the current code I have. Whenever I make a selection the page refreshes, showing the correct data associated with the selection, but defaults to the name of the top selection in the dropdown menu. Thanks for the help. <html> <form method="GET" action="."> <select name="option-menu" id="option-menu"> <option value="" disabled selected>Choose a Name</option> {% for d in database %} <option value="{{d.name}}">{{d.name}}</option> {% endfor %} </select> <button type="submit" class="btn-filter">Filter</button> </form> </html> --views.py-- option_menu = request.GET.get("option-menu") qs = Database.objects.filter(database_id=id) if option_menu != '' and option_menu is not None: qs = qs.filter(name__icontains=option_menu) return render(request, template_name='main/database.html', context={"queryset": qs }) -
How to generate URLS from slugs in Django?
Is there a way to automatically generate a url the same way you generate a slug with prepopulated_fields? What I'm trying to achieve--essentially, is a WordPress style page creator with a permalink automatically generating for the menu. What would be the best approach to achieve this? Thanks in advance. -
everytime i do some activity on my website i get this error :- Wallpaper.models.Wallpaper.DoesNotExist: Wallpaper matching query does not exist
Views.py Models.py error ....... -
Is there a way to solve this issue? "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"
I am trying to send data to django backend using javascript in order to update cart item every time a user add item to the cart and when adding more product multiple time. I want the order number to update anytime that happen. I followed every procedures as seen in the tutorial but every time I sent the data I saw that it throw "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" error, which I can not resolve. Thanks for any help. I have include the following in the head tags <script> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); </script> And this is in my cart.js file: var updateBtns = document.getElementsByClassName('update-cart') for(i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ console.log('Not logged in') … -
How to remove null values from appended table
I am trying to append a table and am having an issues with null values displaying as null. How can I keep the row and leave the status blank if the value is null? function putTableData(response) { let row; $("#table_body").html(""); if (response["data"].length > 0) { $.each(response["data"], function (a, b) { row = `<tr> <td>${b["first_name"]} ${b["last_name"]}</td <td>${b["phone"]}</td> <td>${b["status"]}</td> </tr>`; $("#table_body").append(row) -
Django dropdown doesn't get list data from database
I want to do a dropdown in my html with a table of database, but there is no way it works. views.py def listIndexes(request): results = IndexShort.objects.all() print(listIndexes) return render(request, 'manageAccount.html', {'show': results}) select from .html <select name="listIndexes"> {% for results in show %} <option>{{ results.symbol }}</option> {% endfor %} </select> urls.py from rbdx.views import loadIndexes urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('rbdx.urls')), path('manageAccount/', manageAccount), path('listIndexes/', listIndexes, name='listIndexes'), ] models.py class IndexShort(models.Model): symbol = models.CharField(max_length=5, default=None) def __str__(self): return self.symbol And this doesn't works. Can someone help me? -
Populate one field in django Admin depending on a previous field value
I built the following code in my application models.py class AnoLetivo(models.Model): # regex for name validation name_message = 'Formato "aaaa/aaaa". Exemplo: 2020/2021' name_regex = RegexValidator( regex=r'^\d{4}\/\d{4}$', message=name_message, ) name = models.CharField( 'Designação', validators=[name_regex], max_length=12, unique=False, blank=False, help_text='Insira um ano letivo com o formato "aaaa/aaaa". Exemplo: 2020/2021' ) class Periodo(models.Model): ano_letivo = models.ForeignKey( 'AulasPrevistas.AnoLetivo', verbose_name='Ano Letivo', on_delete=models.CASCADE, ) name = models.CharField( 'Designação', max_length=12, unique=False, blank=False, ) class Feriado(models.Model): """ Um modelo para os feriados """ ano_letivo = models.ForeignKey( 'AulasPrevistas.AnoLetivo', verbose_name='Ano Letivo', on_delete=models.CASCADE, ) periodo = models.ForeignKey( 'AulasPrevistas.Periodo', blank=True, null=True, verbose_name='periodo', on_delete=models.CASCADE, ) name = models.CharField( 'Designação', max_length=200, unique=False, blank=False, ) admin.py class FeriadoForm(forms.ModelForm): ano_letivo = forms.CharField(widget=forms.Select(attrs={'onchange': "action_change(this.value);"})) def __init__(self, *args, **kwargs): super(FeriadoForm, self).__init__(*args, **kwargs) self.fields['periodo'].queryset = Periodo.objects.filter( ano_letivo= ??????? ) class FeriadoAdmin(admin.ModelAdmin): """ Criação da Tabela do Feriado no admin """ form = FeriadoForm list_display = [ 'name', 'date', 'tipo', "slug", 'created', 'modified' ] search_fields = [ 'name', 'date', 'tipo', "slug", 'created', 'modified' ] list_filter = [ 'name', 'date', 'tipo', "slug", 'created', 'modified' ] class Media: js = ("static/action_change.js",) admin.site.register(Feriado, FeriadoAdmin) static/action_change.js django.jQuery( document ).ready(function() { console.log( "ready!" ); django.jQuery('#id_ano_letivo').change(function() { var value = ('#id_ano_letivo').val() }); }); The Django Admin dashboard shows the following: DjangoAdmin I want to be able to … -
Generate PDF Report In Django Rest Framework
I already have a view that responds with the data, i want to generate PDF of the same data, will it be possible to render the template with serializer.data any other solution to generate PDF at backend are welcome.. Serializer . class UsersAuditTrailSerializer(serializers.ModelSerializer): """ User Audit Trail """ changes = serializers.SerializerMethodField() operation = serializers.SerializerMethodField() owner = serializers.StringRelatedField(source='history_user.displayname',read_only=True) id = serializers.IntegerField(source='history_id') user_id = serializers.IntegerField(source='id') def get_operation(self,obj): operation_type = {'+': 'Created', '~': 'Updated', '-': 'Deleted'} return operation_type[obj.history_type] def get_changes(self, obj): change_log = "" current = obj previous = obj.prev_record if previous: delta = current.diff_against(previous) for cng in delta.changes: if cng.field == 'password': change_log+="User Password Changed" continue if cng.field == 'name': continue change_log+="Field : '{}' Changed from {} to {} ,".format(cng.field, cng.old, cng.new) elif current.history_type == "+": change_log ="User created" else: pass return change_log class Meta: model = User.history.model fields = ['id', 'user_id', 'displayname', 'owner','history_date', 'operation','changes'] Views.py: class UsersAuditTrailPDFView(generics.ListAPIView): """ Users Audit Trail and their change log report""" serializer_class = serializers.UsersAuditTrailSerializer permission_classes = (permissions.IsAuthenticated,) filter_backends = (filters.DjangoFilterBackend,OrderingFilter) filter_class = UsersAuditTrailFilterSet queryset = User.history.all() def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) template_path = '../login/rpt/templates/user_report.html' serializer = self.get_serializer(queryset, many=True) context = serializer.data # # find the template and render it. template = get_template(template_path) html … -
SQLAlchemy disconnecting from SQLite DB on Django site
On my site built with Django, I have a dashboard page that I need to display statistics about campaigns running on the site. When running the following code locally, the dashboard page loads correctly, but when running it on the live server served through Nginx and Gunicorn I run into an error. The dashboard view: def sysDashboard(request): template = loader.get_template('AccessReview/sysdashboard.html') context = {} disk_engine = create_engine('sqlite:///db.sqlite3') pio.renderers.default="svg" print(disk_engine.table_names()) sqlQueries.info(disk_engine.table_names()) df = pd.read_sql_query('SELECT emp.pid, COUNT(*) as `num_reviews` ' 'FROM AccessReview_review rev ' 'JOIN AccessReview_employee emp ON rev.manager_id=emp.id ' 'GROUP BY emp.pid ' 'ORDER BY -num_reviews ', disk_engine) print(df) fig = go.Figure( data=[go.Bar(x=df['pid'], y=df['num_reviews'])], layout_title_text='AccessReview/Reviews per Manager').update_layout( {'plot_bgcolor': 'rgba(102,78,98,0.5)', 'paper_bgcolor': 'rgba(102,78,98,0.5)', 'font_color': 'rgba(255,255,255,1)' }) overview_df = pd.read_sql_query('SELECT sys.name, ' 'COUNT(*) as `num_reviews`, ' 'COUNT(1) FILTER (WHERE reviewComplete=1) as `Completed`, ' 'COUNT(1) FILTER (WHERE reviewComplete=0) as `Incomplete` ' 'FROM AccessReview_review ' 'JOIN AccessReview_System sys ON system_id=sys.id ' 'GROUP BY sys.name ' 'ORDER BY -num_reviews', disk_engine) print(overview_df) overview_fig = go.Figure( data=[go.Bar (x=overview_df['name'], y=overview_df['num_reviews'])], layout_title_text='Campaign Overview').update_layout( {'plot_bgcolor': 'rgba(102,78,98,0.5)', 'paper_bgcolor': 'rgba(102,78,98,0.5)', 'font_color': 'rgba(255,255,255,1)' }, xaxis={'title':'System', 'fixedrange':True}, yaxis={'title':'Review Count', 'fixedrange':True}) context['overviewGraph'] = overview_fig.to_html() return HttpResponse(template.render(context, request)) Like I said, this works when running the server locally using py manage.py runserver but not when accessing the site through … -
modify django model field on serializer
i have a model definition Class Book(): name = textfield() edition = textfield() i want the the name of the book as "edition name" if there is a edition data on the book object. otherwith i want to return only the book. how can i acheive that? can i use a serializermethod on the book serializer as class BookSerializer( ): name = serializers.SerializerMethodField() def get_name(self,book): if book.edition: return f"{book.edition}{book.name}" return book.name -
how to call function in django template using conditionals
I have a model for Group: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) size = models.BooleanField(default=False) max_size = models.IntegerField(default=10) closed = models.BooleanField(default=False, blank=True) The idea is that Users can join groups (thus adding to the total joined for that Group) and leave groups. They do that through this view: def join_group(request, pk): id_user = request.user.id group = Group.objects.get(id=request.POST.get('group_id')) account = Account.objects.get(user_id=id_user) if group.joined.filter(id=request.user.id).exists(): group.joined.remove(request.user) account.joined_groups.remove(group) else: group.joined.add(request.user) account.joined_groups.add(group) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) And template: {% if user.is_authenticated %} <form action="{% url 'join_group' group.pk %}" method="POST"> {% if group.closed == True %} <div>Sorry, this group is closed</div> {% else %} {% csrf_token %} {% if joined %} <button type="submit" name="group_id" value="{{group.id}}">LEAVE</button> {% else %} <button type="submit" name="group_id" value="{{group.id}}">JOIN</button> {% endif %} {% endif %} </form> {% endif %} Users joining and leaving groups works fine, the thing I'm trying to implement is when the total_joined == group.max_size a function would be called to close the group. Since, as of now the only way too close a Group is for the User who created it to go and update the Group to change closed=True. What I'm trying to do is call a function within … -
{'field': [ErrorDetail(string='This field is required.', code='required')] - DJANGO REST FRAMEWORK
I'm trying to parse the JSON data nad import it to the database through API. I think I almost got it but still getting this message: {'field': [ErrorDetail(string='This field is required.', code='required')] from my HttpResponse and I don't really know what to do with it. Here is my code: models.py from django.db import models` class Data(models.Model): name = models.CharField(max_length=255, blank=False) eid = models.DecimalField(max_digits=10, decimal_places=0, blank=False) data = models.TextField(max_length=800, blank=True) def __str__(self): return "ID: {} -- Name: {}".format(self.eid, self.name) serializers.py I honestly think that the problem is in the serializers but can't figure it out what to add here. from .models import Data from rest_framework import serializers class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ['name', 'eid', 'data'] class DetailSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' views.py Here I must have 3 views. First for Import. Second for show basic data like name, id, etc. which are given from the JSON file I provide to import/ API. And third for full details of the data given from the JSON file. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.exceptions import ParseError from … -
How to solve "field must be unique" in django?
I am creating an app with vue and django but struggle with getting information from serializer. my models look like this: models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Order(models.Model): name = models.CharField(max_length=255) posted_by = models.ForeignKey(Profile, on_delete=models.CASCADE) class Offer(models.Model): order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers') author = models.ForeignKey(Profile, on_delete=models.CASCADE) serializers.py: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ("user",) class OfferSerializer(serializers.ModelSerializer): author = ProfileSerializer() class Meta: model = Offer fields = ("id", "order_related", "author", ) class OrderSerializer(serializers.ModelSerializer): posted_by = ProfileSerializer() class Meta: model = Order fields = ("id", "posted_by", "name") views.py: class OfferView(ListModelMixin, GenericAPIView, CreateModelMixin): queryset = Offer.objects.all() serializer_class = OfferSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) when i send info to this view: const formData = { order_related: this.$route.params.order_id, author: {user: localStorage.getItem("user")}, } axios .post("api/v1/offers/", formData) i get error: {"user":["Values of field must be unique."]} Is there any way to override this? P.S. To write AbstactUser model etc. - not a way -
Django Pytest gives Kombu Connection refused[111] using rabbitmq and celery
Presently I am using pytest, django and rabbitmq-server with celery for background tasks I do notice however that when I run pytest without running the server on my local machine it causes a long exception thread notably showing E: Kombu Connection refused[111] I am running a test for save() model method which in turn triggers a background celery task I wish to ask if there is a way to start rabbitmq-server in pytest without actually starting it on the local machine so my testcases will passes This also affects my github CI/CD since I have no idea on how to run the rabbitmq image service in github-actions.yml file Your help is appreciated If you wish you can peruse the logs below self = <promise: 0x7fd0819d9d80> def __call__(self): try: > return self.__value__ E AttributeError: 'ChannelPromise' object has no attribute '__value__' ../../../.local/lib/python3.10/site-packages/kombu/utils/functional.py:30: AttributeError During handling of the above exception, another exception occurred: self = <Connection: amqp://guest:**@127.0.0.1:5672// at 0x7fd082053010> ConnectionError = <class 'kombu.exceptions.OperationalError'> ChannelError = <class 'kombu.exceptions.OperationalError'> @contextmanager def _reraise_as_library_errors( self, ConnectionError=exceptions.OperationalError, ChannelError=exceptions.OperationalError): try: > yield ../../../.local/lib/python3.10/site-packages/kombu/connection.py:446: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Specify an exception class to catch or reraise the exception - how to catch exceptions in proper way?
In Sonar lint I see this message: Specify an exception class to catch or reraise the exception My class: class GetCountryByIPApiView(APIView): def get(self, request, *args, **kwargs): ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get( 'REMOTE_ADDR', '')).split(',')[-1].strip() try: ip_country = DbIpCity.get(ip_address, api_key='free').country except: ip_country = 'US' return Response({'country_code': ip_country.lower()}, status=status.HTTP_200_OK) DbIpCity class: https://github.com/tomas-net/ip2geotools/blob/master/ip2geotools/databases/noncommercial.py#L25 How should I improve this? -
Tips to better manage the creation of a non-nullable object through signals
I find myself in this situation: In models: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # other... signals.py: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Client.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.client.save() There are specific fields of the Client class that cannot be null and therefore I get errors like: NOT NULL constraint failed: accounts_client.dob What is the best solution in this case? -
How to customize the in_active user error message for rest_framework_simplejwt in Django
I have set my multiple user model in Django rest framework and I am using dj_rest_auth, allauth and djangosimplejwt for my user Authentication and Authorisation workflow my serialisers.py look like this class LoginSerializer(Serializer): email = EmailField(required=False, allow_blank=True) password = CharField(style={'input_type': 'password'}) class Meta: model = Users fields = ['email', 'password'] extra_kwargs = { 'password': {'write_only': True}, 'style': {'input_type': 'password'}, } def authenticate(self, **kwargs): return authenticate(self.context['request'], **kwargs) def _validate_email(self, email, password): if email and password: user = self.authenticate(email=email, password=password) else: msg = {'error': _('Did you forget to include an email or password?')} raise ValidationError(msg) return user def get_auth_user_using_allauth(self, email, password): from allauth.account import app_settings # Authentication through email if ( app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL ): return self._validate_email(email, password) def get_auth_user(self, email, password): """ Retrieve the auth user from given POST payload by using either `allauth` auth scheme or bare Django auth scheme. Returns the authenticated user instance if credentials are correct, else `None` will be returned """ if 'allauth' in settings.INSTALLED_APPS: # When `is_active` of a user is set to False, allauth tries to return template html # which does not exist. This is the solution for it. See issue #264. try: return self.get_auth_user_using_allauth(email, password) except url_exceptions.NoReverseMatch: msg = {'error': _('Unable to … -
How to access a website deployed on heroku from an iframe?
I created a website in Django that I deployed on heroku. It contains the following line in its settings.py file: ALLOWED_HOSTS = ['*'] This means that it allows connection with any domain name. But when I try to access a site from an iframe on an html page from my localhost, I get the following error when loading my webpage: gkwhelps.herokuapp.com refused the connection. here is the code of my iframe: <Iframe src="https://gkwhelps.herokuapp.com" width="450px" height="450px" /> I don't know why this happens because I authorized access to all hosts before deploying on heroku, I don't know if heroku has a policy about this which conditions the access to other hosts or the error comes from elsewhere. Thanks ! -
How to add new row into a table in Django Python?
The workflow of the current work is user add forms and has a selection of visit status containing approved and canceled. For example , user select visit status as approved and fill in other fields and save the form. A new row will be added in the table ClinicVisitStatusRecord() and ClinicVisitStatusHistory.Then when the user edit the form and want to change the visit status to canceled, it does not add a new row in the table ClinicVisitStatusRecord() and ClinicVisitStatusHistory and it also does not overwrite the data. Is there any to create a new row again? serializers.py class ClinicVisitSerializer(serializers.ModelSerializer): clinic_detail = ClinicSerializer(read_only=True, source='clinic') staff_relationship_detail = StaffRelationshipSerializer(read_only=True, source='staff_relationship') staff_detail = StaffSerializer(read_only=True, source='staff') person_visit_name = serializers.CharField(max_length=100, min_length=None, allow_blank=True, help_text='The name of person visiting the clinic') bill_amount = serializers.DecimalField(max_digits=None, decimal_places=2, help_text='The clinic visit cost') class Meta: model = ClinicVisit exclude = clinicvisit_exclude extra_kwargs = { "staff_relationship": {"required": True}, "visit_type": {"required": True}, "visit_status": {"required": True}, } def create(self, validated_data): obj = ClinicVisit.objects.create(**validated_data) if obj.visit_status == "canceled" : obj.create_new_clinic_visit_statuses_history(action_by=obj.staff) obj.create_visit_status_history(action_by=obj.staff) print('OK 1') if obj.visit_status == 'approved': obj.create_new_clinic_visit_statuses_history(action_by=obj.staff) obj.create_visit_status_history(action_by=obj.staff) print('OK 2') models.py class ClinicVisit(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) staff_relationship = models.ForeignKey( StaffRelationship, on_delete=models.SET_NULL, blank=True, null=True,) clinic = models.ForeignKey( Clinic, on_delete=models.SET_NULL, blank=True, null=True,) … -
Django ManyToMany with quantity
I'm having a bit of a problem trying to model something in Django that I've conceptualized. I know that it is a many to many relationship... however it is sort of self referential and has a quantity involved. I imagine this requires a bridge model of some sort, which I have, but now how do I edit them in the admin page? What I have is a Component class. For example, a 'screw' is a component, and it requires no further components to create it. But so is a 'housing', which requires 4 screws to hold it together. That housing could then go into a manifold and the manifold could go into a vehicle and so forth. Each thing could potentially be a component of another thing if that makes sense. I've put all of the screws and bolts and such into the database through the admin edit page. But now I want to start putting in more complex assemblies. I could just create an Assembly class which has a list of one or more components. But I'm still left with the problem that this assembly could go into a larger assembly zero or more times. How do I represent … -
Django submit two forms within one view
I'm trying to submit two forms within one view. First, a user shares a URL through the first form. My program then renders some graphs and will ask the user at the end of the page to fill out a form and submit it. Here's how I'm trying to solve it: views.py: if request == "POST": if 'first-input-name' in request.POST: # or in request.POST.get('name') # do something elseif 'second-input-name' in request.POST: # or in request.POST.get('name') # do something else template: <input type="submit" name="first-input-name"/> <input type="submit" name="second-input-name"/> This is the approach I found in answers to similar questions. However, in my requests.POST I don't find the name of my input, and therefore I don't get the expected behavior. Any ideas on how to solve this?