Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I upload text and file in Django Rest Framework
I am trying to upload both text data and a file to django server using angular for the front-end, here is my models in django #models.py class UploadChapter(models.Model): chapter_number = models.CharField(max_length=50, choices=chapters) chapter_file = models.FileField(upload_to="files") student = models.ForeignKey(User,on_delete=models.CASCADE) supervisor = models.ForeignKey(Supervisor, on_delete=models.CASCADE) status = models.CharField(max_length=100, choices=status, default="Pending") def __str__(self): return f'{self.student} - {self.chapter_number}' for the serializer I wrote this code #serializers.py class UploadChapterSerializer(serializers.ModelSerializer): class Meta: model = UploadChapter fields = ['chapter_number', 'chapter_file', 'student', 'supervisor', 'status'] and for the views i wrote this code #views.py @csrf_exempt def ChapterApi(request, id=0): if request.method=='GET': chapters=UploadChapter.objects.all() chaptersSerializer=UploadChapterSerializer(chapters, many=True) return JsonResponse(chaptersSerializer.data, safe=False) elif request.method=='POST': chaptersData=JSONParser().parse(request) chaptersSerializer=UploadChapterSerializer(data=chaptersData) if chaptersSerializer.is_valid(): chaptersSerializer.save() return JsonResponse('Added Successfully', safe=False) return JsonResponse('Failed', safe=False) so am getting errors from the JSONParser and I really dont know how to do this, I need help please -
Docker Image > 1GB in size from python:3.8.3-alpine
I'm pretty new to docker and, although I've read lots of articles, tutorials and watched YouTube videos, I'm still finding that my image size is in excess of 1 GB when the alpine image for Python is only about 25 MB (if I'm reading this correctly!). I'm trying to work out how to make it smaller (if in fact it needs to be). [Note: I've been following tutorials to create what I have below. Most of it makes sense .. but some of it feels like voodoo] Here is my Dockerfile: FROM python:3.8.3-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /home/app RUN addgroup -S app && adduser -S app -G app ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME RUN pip install --upgrade pip COPY requirements.txt . RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg \ && apk add --update --no-cache postgresql-client RUN pip install -r requirements.txt RUN apk del build-deps COPY entrypoint.prod.sh $APP_HOME COPY . $APP_HOME RUN chown -R app:app $APP_HOME USER app ENTRYPOINT ["/home/app/web/entrypoint.prod.sh"] Using Pillow and psycopg2-binary has caused a world of … -
Django deployment with Zappa - root URL is wrong
I have successfully set up a Django app following a Zappa tutorial I found. However, the problem is that Zappa deploys my app to the location: https://some-aws-address/devel where "devel" is the name of my particular Zappa deployment. The problem with this is that, at this position, I have pages that have links on them beginning with a '/' that map to: https://some-aws-address/ and not (as I would want): https://some-aws-address/devel For example, in one of my template files I have a link on an image: <a href="/"><img src="{% static 'images/main/ryzosens-logo-white-background.png' %}"></a> where the href="/" always maps to https://some-aws-address/ I don't want to have to do some hack to get my root URLS to map to https://some-aws-address/devel, so the question is: What must I have in my Django settings (or elsewhere) so that my URL root '/' maps to the HTTP endpoint that Zappa creates? Many thanks in advance! -
How to query records from a nested M2M field in Django?
I'm trying to understand how to get a QuerySet for a nested ManyToMany relationship in Django. Imagine models that look something like this: class Collection: ...fields... class Group: collections = ManyToMany(Collection) class Account: groups = ManyToMany(Group) I can't quite figure out how to query all of the collections for a given account. E.g. something similar to: account.groups.all().values('collections') But the above query gives me a generic QuerySet of just the PKs of the collections, and I'd like a CollectionQuerySet containing the full models. -
Django DRF: How to get a file response from a post request
I want to post an image and receive a file containing the OCR result of that image but i m not sure how to do it, i tried to follow the DRF documentations but i m not sure i got it because this is new to me and my first time using django. lass UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer @api_view(['GET', 'POST']) def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() queryset=File.objects.filter(id=str(File.objects.latest('created_at'))) file_data=queryset.values('file') serializers=Fileserializers(data=file_data) return Response(serializers.data) return HttpResponse({'message':'error'},status=400) -
Django: Cant Logout of homepage
For some reason I am unable to logout of the homepage("Auditor"), when I click on the Logout button I get the following: As you can see it redirects to Logout, but still stays in the home page. Here is the Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from .forms import createUserForm, auditForm from django.contrib.auth import authenticate, login, logout from .models import datas from django.contrib.auth.decorators import login_required from django.contrib import messages @login_required(login_url='Login') def Auditor(request): model = datas.objects.filter(qs_login=request.user) form = auditForm() if request.method == "POST": form = auditForm(request.POST) if form.is_valid(): form.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form} return render(request, "main/auditform.html", context) @login_required(login_url='Login') def auditFormPage(request, pk): model = datas.objects.filter(qs_login=request.user) form = auditForm() try: data = datas.objects.get(Task_ID=pk) form = auditForm(instance=data) if request.method == 'POST': form = auditForm(request.POST, instance=data) if form.is_valid(): form.save() # <-- Add this to get the updated data instance except datas.DoesNotExist: pass context = { "items": model, "form": form } return render(request, "main/auditform.html", context) def registerPage(request): if request.user.is_authenticated: return redirect('Auditor') else: form = createUserForm() if request.method == "POST": form = createUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account Successfully Created for: ' + user) … -
Removing brackets and quotes from list in django template?
Context I'm using Django to extract data from an API - which is then presented in a template. The data extracted is a list of genres. The list contains quotes and brackets when used via context. Question How to remove brackets and quotes from list in snippet below? Refer to objects, "genres" and "prodc", in views.py file Refer to context.genres and context.prodc in HTML Snippet Views.py class HomePageView(TemplateView): # template_name = 'home.html' def get(self,request): if 'movie' in request.GET: api_key = xxxx id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' # payload = {'q': , 'appid': 'xxxxxx'} response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # backdrop image -- tmdb for each movie backdrop_path = tmdb['results'][0]['backdrop_path'] url_backdrop = 'https://image.tmdb.org/t/p/original'+backdrop_path # poster image -- tmdb for each movie poster_path = tmdb['results'][0]['poster_path'] url_poster = 'https://image.tmdb.org/t/p/original'+poster_path # 2nd get request for info on individual movie id_1 = tmdb['results'][0]['id'] api_key_1 = xxxx url = 'https://api.themoviedb.org/3/movie/{}?api_key={}&language=en-US' tmdb_1 = requests.get(url.format(id_1,api_key_1)).json() # genres list genres = [] for i in range(len(tmdb_1['genres'])): genres.append(tmdb_1['genres'][i]['name']) eeeee = str(genres)[1:-1] # prod comps list prodc = [] for i in range(len(tmdb_1['production_companies'])): prodc.append(tmdb_1['production_companies'][i]['name']) context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': … -
Django PasswordChangeForm is giving me a alert to select a user to apply changes to. Why?
For some reason it it giving me a pop up alert when I submit this form and asking me which user I should apply this change to and I don't want it to. I just want it to submit and update the form. I'm relatively new to django views.py ''' def passwordChange(request, pk): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('home') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) context = { 'form' : form, } return render(request, 'resturant/password_change.html', context) ''' urls.py ''' urlpatterns = [ path('', views.home, name='home'), path('menu/', views.menu, name='menu'), path('order/', views.order, name='order'), path('menu/<str:pk>/details', views.menu_details, name="menu_details"), path('login/', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('logout/', views.logoutPage, name="logout"), path('<str:pk>/profile', views.userProfile, name="user_profile"), path('menu_adjustment', views.adminMenuItem, name="admin_menu_item"), path('<str:pk>/delete', views.delete_item, name="delete_item"), path('<str:pk>/password_change', views.passwordChange, name='password_change'), ] ''' template - password_change.html ''' {% extends 'resturant/main.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <br> <div class="row"> <div class="col-5" style="margin: auto;"> <div class="card"> <div class="card-title"> <h2 class='text-center mt-2'>Password Change</h2> </div> <div class="card-body"> <form class="" action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_old_password1" class='h5'>Old Password</label> {% render_field form.old_password class="form-control" %} </div> <div class="form-group"> <label for="id_new_password1" … -
Django login - "Cannot force an update in save() with no primary key"
I have implemented the standard Django login in the following manner: from django.contrib.auth import authenticate, login, logout def login_request(request): username = password = "" if request.POST: username = request.POST["username"].lower() password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect("../..") return render(request, "login.html", context={"error": "TRUE"}) return render(request, "login.html", context={"error": "FALSE"}) For most users, this has worked fine. However, for some users it has been throwing the following error: ValueError at /login/ Cannot force an update in save() with no primary key. This error is sourced back to the user.save(update_fields=['last_login']) in django/contrib/auth/models.py. I have been unable to determine why this error is occurring, and why it happens to some users and not others. I've looked closely, and been unable to find anything that differentiates between users who have had this problem and those who haven't. -
I can't seem to find a way to write into heroku's postgres from my django app
I wrote an app with Django and it has been working fine when running locally. I know deployed it with Heroku and the app run as well. However, I when I python manage.py createsuperuser it says that I successfully created the superuser but nothing is written into Heroku Postgress DB...so I can login into neither /admin nor my app. I have been trying debugging like crazy but I can't find the issue. This is my settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG=True #DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'action.apps.ActionConfig', 'django_extensions', 'bootstrap_modal_forms', 'widget_tweaks', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mywebsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mywebsite.wsgi.application' # Database # … -
How filter by date and convert datetime
I am sending some dates from the front made in vue. I am receiving these dates in my viewSet in django, I want to filter data from these received dates. I have two questions: How do I convert dates into Python Datetime? How do I filter the dates equal or greater or equal or less. => <= In other words: bring records whose date is equal to or greater than another date. date format in the front: 2021-08-03 10:12:14 date format in the back: # print(type(fechas['desde'])) fecha <class 'str'> # print(fechas['desde']) fecha 2021-08-03 10:12:14 VIEWSET: class TecnicosViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer def list(self, request): dataQ = request.GET newQ = json.dumps(dict(dataQ)) newQ1= json.loads(newQ) tecnicos = '' fechas= json.loads(newQ1['fechas'][0]) for item in newQ1['tecnicos']: itemN = json.loads(item) tecnicos = itemN['tecnicos'] print('fechas', fechas['desde'], fechas['hasta']) # fecha = datetime.strptime(fechas['desde'], '%Y-%m-%d %H:%M') print('fecha', type(fechas['desde'])) print('fecha', fechas['desde']) for id in tecnicos: ordenes = Servicio_realizados_orden_trabajo.objects.filter(date_range = [fechas['desde'], fechas['hasta']]).filter(state = 1).filter(tecnico = id) ordenS = ServicioRealizadosserializer(ordenes, many=True) return Response({'OK'}) As I fixed before: I want to convert that date into understandable python format and then use that transformed date to filter data by that date. The for loop seen in the … -
how to loop through DIV id in ajax in Django
i have Django Appp and i use Ajax request i want to loop through DIV class inside Ajax <span value="{{i.id}}" name="{{i.id}}" id="quant{{i.id}}" class="input-counter__text input-counter--text-primary-style quant-{{forloop.counter}}">{{i.quantity}}</span> <a class="cart-add" value="{{i.id}}" href="{% url 'home:cart_quantity_add' id=i.id %}"><span class="input-counter__plus fas fa-plus"></span></a> </div> so every time i click on the link the quantity should appear inside the span Here is my Ajax <script type="text/javascript"> $(".cart-add").on("click",function (e) { e.preventDefault(); const ProductId = $(this).val(); // get the selected subject ID from the HTML dropdown list $.ajax({ // initialize an AJAX request type: "POST", url: $('.cart-add').attr("href"), data: { 'add-product': ProductId, // add the country id to the POST parameters 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { // `data` is from `get_topics_ajax` view function let html_data2=""; data.forEach(function (data) { html_data2 += ` ${data.quantity} ` }); $(".quant-{{forloop.counter}}").html(html_data2); } }); }); </script> -
Why is my django application not serving .css files?
I have an issue with serving a specific css file in my django app and I can't seem to find the solution to it, hopefully someone can help. I have a website PersonalWebsite and in there I have three apps, the important one being the dashboard. I decided to separate the static files of each app and then also the static files of the base website so my folder structure is like this: PersonalWebsite | |static |PersonalWebsite | |css | style.css |fonts | font.ttf |dashboard | |static |dashboard |css | style.css When I open up the website I can see all files from the static/PersonalWebsite are being served, however the ones from static/dashboard are not. Could anyone provide some insight as to what is wrong? I have run the collectstatic command several times and that one detects the file and I see it being copied into the root folder. These are my static settings. I added boot because in that one I have bootstrap downloaded. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), os.path.join(BASE_DIR, 'boot/'), ] -
Django Simple Template Tag Questions
I'm a student who is learning how to play Django. You are about to output a p-tag using template tags in the vault. The template tag I want to use is "When option.product_code and product.product_code are the same in the Option table, print out if there are two options.option_code". How should I fill out the if statement? I'd like to add Hello by referring to the above. Please give me some advice. -
Django: How to make FIle name the same as Post Form Title
So on my app I want a user to upload an image and the title of the form will become the file name. so ex: user uploads image xyz.jpg, title = newfile after that the image will now be newfile.jpg this is my code below im really new to django so hopefully somebody can pull me in the right direction #forms class PostForm(forms.modelForm): class Meta: model = Post fields = ['title', 'cover'] #urls from django.urls import path from .views import HomePageView, CreatePostView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('post/', CreatePostView.as_view(), name='add_post') ] #views from django.shortcuts import render from django.views.generic import ListView, CreateView from django.urls import reverse_lazy from .forms import PostForm from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' class CreatePostView(CreateView): # new model = Post form_class = PostForm template_name = 'post.html' success_url = reverse_lazy('home') -
Unable to run custom decorator after post_save signal
I have a post_save signal which is run after any updates happens to a Profile, like so: # removing the `dispatch_uid` parameter doesn't change anything @receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite") def send_invitation_email(sender, instance, **kwargs): # ... do things I would like to run a custom decorator on the signal, after the post_save has been run, like so: def my_test_decorator(func): print("outside the wrapper") def wrapper(request, board_id, board_name): print("INSIDE THE DECORATOR AFTER POST_SAVE") try: return func(request, board_id, board_name) except Exception: return Http404("Board not found") return wrapper @my_test_decorator @receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite") def send_invitation_email(sender, instance, **kwargs): # ... do things However, my method my_test_decorator doesn't run at all. However, if I switch places on the decorators then it will run but it will run before the @receiver decorator, not after. What am I missing? Found this 5 year old question, but it was left unanswered so I'm trying again. TYIA -
How to create Models without an app in django?
Is there a way I can create a Models.py file without creating an app and make the models work with migrations that django provides? -
How to fiend one nearest date in HTML Calendar django
i want to implement an event calendar. i am faced with the problem of displaying the closest event to today's date. to find the nearest date, i use __gte in queryset, after queryset finds all the nearest dates, I want to highlight the first one with a different color here is my solution could you tell me what i'm doing wrong? This is my Model class Events(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() start_time = models.DateTimeField() end_time = models.DateTimeField() def __str__(self): return self.title @property def get_html_url(self): url = reverse('cal:events', args=(self.slug,)) return f'<a href="{url}">' And my HTMLCalendar from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Events class Calendar(HTMLCalendar): def __init__(self, year=None, month=datetime.now().month): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' if Events.objects.filter(start_time__day=day, start_time__month=self.month).exists(): for event in events_per_day: d += f'{event.get_html_url}' if day != 0: ev = Events.objects.filter(start_time__gt=datetime.now()).first() if ev: return f"<td>{d}<span style='color:red;' class='date'>{day}</span></a></td>" else: return f"<td>{d}<span style='color:aliceblue;' class='date'>{day}</span></a></td>" return '<td></td>' else: if day != 0: return f"<td><b><span class='date'>{day}</span> </b></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' … -
python turn these print values into dictionary with keys being first column and the buttom being dictionary values
I am working with django and got back a response that looks like this Name,surname AVA,AAJ DAA2,ASA EAA23,VVD GAA43,DDA AAA42,AAS MAA21,JJ produced by this code @api_view(["POST"]) def testfunc(request): if request.method == 'POST': x = request.body.decode('utf-8') print(x) return JsonResponse(x,safe=False) i want to place this into a dictionary with the first row being the key and the remaining rows being the values, so they can be further processed. -
Django - How to reach relational field
I have Patient model which has many to many relation with ICF model. ICF model has many to one field to Unite model. In Unite model I have Unite names. I want to reach Unite names that are assigned to Patient with relations. I try to reach Unite names for each Patient. If it is more than one I cannot list them for that person. Here are my codes. This is my patient model. class Patient (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255, default="doe") data = models.JSONField() Intensivecare_form = models.ManyToManyField(Intensivecare_Form) isDeleted = models.BooleanField(default=False) This is my ICF model. class Intensivecare_Form (models.Model): id = models.AutoField(primary_key=True) hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE) formname = models.CharField(max_length=128) data = models.JSONField() unites_id = models.ForeignKey(Unite, on_delete=models.CASCADE) At last, This is my Unite model class Unite (models.Model): id = models.AutoField(primary_key=True) unitename = models.CharField(max_length=128) In my views.py file I have a function as below def listPatients(request): Patients = Patient.objects.all() output = [] for patient in Patients: unitename = [] icfinfo = serializers.serialize('json', patient.Intensivecare_form.all()) jsonicfinfo = json.loads(icfinfo) unitename.append(jsonicfinfo) output.append({'id': patient.id, 'fname': patient.name, 'lname': patient.lastname, 'data': patient.data, 'unitename': unitename, }) return JsonResponse(output, safe=False) -
Create superuser programmatically inside dockerized Django app
I have the following code in my Django apps.py file: from django.apps import AppConfig import logging from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as gettext class SemanticSearchConfig(AppConfig): name = "semantic_search_demo" label: str = "policy" verbose_name: str = gettext("Policies") @classmethod def ready(cls): user_model = get_user_model() log = logging.getLogger(cls.label) try: if not user_model.objects.filter(username="admin").first(): log.info("Creating default superuser with user and password: admin") user_model.objects.create_superuser('admin', 'admin@admin.admin', 'admin') except Exception: log.warning( "Found an error trying to create the superuser, if you aren't " "running the user model migration yet, ignore this message" ) The code is executed beautifully when I run in the debugger. However, when I deploy this inside a docker I get the exception. How do I avoid this? How do I automate the migration? I have no other dat models/migrations. -
Django annotate value based on another model field
I have these two models, Cases and Specialties, just like this: class Case(models.Model): ... judge = models.CharField() .... class Specialty(models.Model): name = models.CharField() sys_num = models.IntegerField() I know this sounds like a really weird structure but try to bare with me: The field judge in the Case model refer to a Specialty instance sys_num value (judge is a charfield but it will always carries an integer) (each Specialty instance has a unique sys_num). So I can get the Specialty name related to a specific Case instance using something like this: my_pk = #some number here... my_case_judge = Case.objects.get(pk=my_pk).judge my_specialty_name = Specialty.objects.get(sys_num=my_case_judge) I know this sounds really weird but I can't change the underlying schemma of the tables, just work around it with sql and Django's orm. My problem is: I want to annotate the Specialty names in a queryset of Cases that have already called values(). I only managed to get it working using Case and When but it's not dynamic. If I add more Specialty instances I'll have to manually alter the code. cases.annotate( specialty=Case( When(judge=0, then=Value('name 0 goes here')), When(judge=1, then=Value('name 1 goes here')), When(judge=2, then=Value('name 2 goes here')), When(judge=3, then=Value('name 3 goes here')), ... Can this be … -
How to submit with radio button selected item?
I am new to django. I tried to submit the radio button selected value. by click submit button. <div class="row mx-auto"> {% for item in object_list %} <div class="containermac mt-sm-5 my-1"> <div class="question ml-sm-5 pl-sm-5 pt-2"> <div class="py-2 h5"><b>Q. {{item.title}}</b></div> <div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options"> <label class="options">{{item.option1}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option1}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option2}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option3}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> </div> </div> <div class="d-flex align-items-center pt-3"> <div class="ml-auto mr-sm-5"> <button class="btn btn-success">Submit</button> </div> </div> </div> {% endfor %} </div> -
Mutate and query multiple apps having same database schema in GraphQL Django app
I am new to django and graphQL. Am working with 2 databases which have exact same schema. Problem is - My query and mutations are executing only on one database. Am trying to code an backend where: My news article (Id,FullDescription) resides in TestDb. So, I need to mutate and query TestDb. I process them (lower case conversion + remove punctuations) and store them in OutDb. Similarly, I need to mutate and query OutDb. I have correctly configured ops with 2 database using dbrouters. My driver App is NewsArticle and I implemented 2 Django Apps for handling 2 db TestReadDb and TestWriteDb ## `TestReadDb/models.py`## ------------ from djongo import models # Create your models here. class TestDb(models.Model): _id = models.CharField(max_length=300, primary_key=True) FullDescription = models.TextField(blank=False) class Meta: db_table = 'input_triples_collection' indexes = [models.Index(fields=['_id', 'FullDescription']),] And ## `TestWriteDb/models.py`## ------------ from djongo import models # Create your models here. class OutDb(models.Model): _id = models.CharField(max_length=300, primary_key=True) FullDescription = models.TextField(blank=False) class Meta: db_table = 'output_triples_collection' indexes = [models.Index(fields=['_id', 'FullDescription']),] As can be seen, schema for both databases is exactly same. I defined individual GrahpQL types, queries, mutations for both apps. For e.g. queries look like: ## `TestReadDb/queries.py`## ------------ import graphene from test_read_db.types import FullDescriptionTestDbType from test_read_db.models … -
Django tests failing after unique_together error catch
Writing my tests for a certain part of my Django application I am trying to test if a unique_together error message pops up on my API. This is the test I am running: re = self.c.patch('/api/me/dashboards/' + str(default_id) + '/', {'widgets': [{ 'name': 'Testwidget 2', 'type': 1, 'coord_x': 1, 'coord_y': 1 }]}, content_type='application/json') self.assertEqual(500, re.status_code) self.assertEqual( re.content, b'{"message":"UNIQUE constraint failed: dashboard_widget.coord_x, dashboard_widget.coord_y, dashboard_widget.dashboard_id","status":500,"error":true,"detail":""}') It works fine, but after that no matter whicht test I am running it states django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. If I remove all tests after this, there is no error message or similar. The API endpoint works otherwise, it is just the test that messes up. Also I did this with a similar test, which should raise a Validationerror and this test behaves the same: Everything is fine but the subsequent test is failing with the error.