Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating sub-categories in Django Admin without creating a new app
I was wandering wether it is possible to create sub-categories for models in the Django administration panel. Let's assume I have an app called "MyApp" which contains 2 model classes called "foo" and "bar". In my admin panel I will see the name of the the app and my two models listed under it (once registered in admin.py). What I want is to create a sub-category in the admin panel which would look like this: MyApp first model name --> new sub category foo second model name --> new sub cateogry bar Thank you for your time, Cheers -
Using RequestFactory in testing views that are not in urls.py
I would like to test my custom decorator (just a custom protection, similar to @login_required). For this purpose, I am creating two dummy views: def foo(request): return JsonResponse('ok', safe=False) @my_custom_decorator def protected_foo(request): return JsonResponse('ok', safe=False) Obviously, they are not mentioned in urls.py - they are just a simple views to be used in the unit test. What I will try to do, is to just: request = RequestFactory().get() <== this is wrong response = foo(request) assert response.status_code == 200 # check if decorator works when no value is provided failed_response = protected_foo(request) assert failed_response.status_code == 403 # check if decorator works when the value is provided in GET request = RequestFactory().get(f'?SECRET_VALUE={the_secret_value}') <== this is wrong response = protected_foo(request) assert response.status_code == 200 # check if decorator works when the value is provided in GET request = RequestFactory().post('', {'SECRET_VALUE': the_secret_value}) <== this is wrong response = protected_foo(request) assert response.status_code == 200 My question is - how to pass data to RequestFactory craft a GET or POST request containing values, when the views are not connected to the urls.py? In other words - what should be in lieu of the lines containing this is wrong? -
How to connect Postgres Database with Django and show the result on HTML?
I'm new to Django. Currently, I'd like to make a simple web app using Django and Postgre SQL (localhost). Currently, I want to show the connection result ("success/not") on an HTML page and retrieve the data from DB using rest API (next task). This is my project structure: C:. ├───DBD │ └───__pycache__ ├───demopage │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───restapi │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ └───src └───__pycache__ I create a DB connection module DbLoader.py in src folder. import psycopg2 import json class DbLoader: def __init__(self, host, port, dbname, user, password): # postgres self.host = host self.port = port self.dbname = dbname self.user = user self.password = password def connectDB(self): # connection information conn = 'host = {host} port = {port} dbname = {dbname} user = {user} password = {password}'.format( host = self.host, port = self.port, dbname = self.dbname, user = self.user, password = self.password ) # establish connection print(conn) self.db = psycopg2.connect(conn) self.cur = self.db.cursor() def view_connDB(self): sql = 'SELECT VERSION()' self.cur.execute(sql) result = self.cur.fetchone() self.db.close() # return connection result and show in HTML ! return result def view_table(self): sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""" self.cur.execute(sql) result = self.cur.fetchall() cols = … -
Use regular class with Django
I want to make a post request where I request an object containing free text, process it, and respond with another object containing a collection with the corrections per word. In Django, every model.Models class gets a DB table, but I do not want to store either the request or the response. I just want to use the server to compute the spell checker. I cannot seem to figure out how to build a serializer from a regular class. -
Calculate monthwise data in django/python
I am getting input as start_date and end_date, now I want to fetch data based on months between start_date and end_date. How that can be done in python/django? I am getting date in format as - start_date = '2021-5-5' #YYYY-MM-DD format end_date = '2021-6-5' Required results - result = [{ 'month' : 'may' 'data' : data_for_may # from date 5th of may to 31st of may }, { 'month' : 'june' 'data' : data_for_june # from date 1st of june to 5th of june } ] -
HOW TO CREATE FOLLOW AND UNFLLOW SYSTEM WITH DJANGO 3
I AM GOING TO CREATE TWITTER CLONE WITH DJANGO AND FIRST PROBLEM THAT I FACED IS THAT HOW CAN I CREATE A FOLLWING SYSTEM -
Django - Deleting dynamic input form
I want to learn django. I created a simple dynamic input form with react native. I use fetch to post data as json. The json type is like this. 0: {'input': 'hehe', 'label': 'laugh'} 1: {'input': 'haha', 'label': 'laugh'} 2: {'input': 'huehue', 'label': 'laugh'} In react native I use splice method to delete operation. It splices the id selected row then posting to django as this 0: {'input': 'hehe'} 1: {'input': 'haha'} However, I couldn't figure out the proper algorithm to make this fetched json with django queryset because the length of json type it doesn't mather. In react native, I can still post the 3 items json to django with one deleted, one new added. In that case comparison the length of fetched json type and queryset will not work. I have algorithm for new inputs but not deleted inputs right now. My code as below: for form in getJson: formId = form['Id'] if User.objects.filter(id=formId).exists(): formData = User.objects.filter(id=formId).update(val=form['Input'].title(), key=form['Label'].title()) elif formId == 0: formData = User(val=form['Input'].title(), key=form['Label'].title() ) try: formData.full_clean() formData.save() output.append({'Dynamic Form: new created! ': str(formData)}) except ValidationError as e: output.append({'Error': e}) return HttpResponse(e) What approach should I make to build an algorithm for delete operation without corrupting … -
adding csrf tag before include tag breaks the form
The include tag doesn't work with csrf tag. The form works fine if it is removed. form1 and form2 only have fields. <form novalidate action="{% url 'action' %}" method="post" class="form xl:ml-10 owl-carousel" id="form"> {% csrf_token %} {% include 'form1.html' %} {% include 'form2.html' %} {% include 'submit.html' %} </form> -
How to use multiple return values in HTML
I'm need to use multiple return values from a function in HTML Thats short version of the code. All imports are correct and if I return single value it works. Just don't know how to call both values in the HTML. In the view: def get_title_and_text(): title = 'Some title' text = 'Some text' return title, text def page(): return render(request, 'page.html', {'get_title_and_text': get_title_and_text()} In the HTML <h3>{{ get_title_and_text.title }}</h3> <h3>{{ get_title_and_text.text }}</h3> I guess it's simple solution but I just could not find information about that matter -
How to get all model objects related to the initial one even if they are further than directly related?
Maybe the title is a little confusing, but I believe the explanation will be much clearer. I have two models class AgrParameterUnits(models.Model): Name = models.CharField(max_length=50, verbose_name=_("Name")) ShortName = models.CharField(max_length=50, verbose_name=_("ShortName")) class AgrParameterUnitConversions(models.Model): ParrentParameterUnitId = models.ForeignKey(AgrParameterUnits, on_delete=models.DO_NOTHING, null=False, blank=False, db_column='ParrentParameterUnitId', related_name='ParrentParameterUnitId', primary_key=True, verbose_name=_("Parrent Parameter Unit Id")) ChildParameterUnitId = models.ForeignKey(AgrParameterUnits, on_delete=models.DO_NOTHING, null=False, blank=False, db_column='ChildParameterUnitId', related_name='ChildParameterUnitId', verbose_name=_("Child Parameter Unit Id")) ConversionCoefficent = models.DecimalField(max_digits=18, decimal_places=7, null=False, blank=False, db_column='ConversionCoefficent', verbose_name=_("Conversion Coefficent")) It is about conversions between units. The scenario is as follows. I get one unit and I need all that are somehow related to the initial one. Example: there are 3 AgrParameterUnits records and 2 AgrParameterUnitConversions records in the db AgrParameterUnits records: Hz, Kilohertz, Megahertz. AgrParameterUnitConversions records: 1 KiloHertz = 1000 Hz 1 Megahertz = 1000 KiloHertz How would the query look like if I wanted to, given Hertz, find both Kilohertz and Megahertz? It very much sounds like a recursion task which so far I struggle with. This is what I have so far. def _get_units(base_unit): try: """Try to filter unit conversions where this the received unit is the parent unit""" unit_choices = AgrParameterUnitConversions.objects.filter(ParrentParameterUnitId=base_unit).annotate( unit_name=F('ParrentParameterUnitId__Name'), unit_id=F('ParrentParameterUnitId'), ).values("unit_id", "unit_name") related_units = AgrParameterUnitConversions.objects.filter( ChildParameterUnitId=unit_choices[0]["unit_id"]).annotate( unit_name=F('ParrentParameterUnitId__Name'), unit_id=F('ParrentParameterUnitId'), ).values("unit_id", "unit_name") units_this_round = (unit_choices | related_units).distinct() except IndexError … -
Adding connect wallet button to HTML - Solana blockchain
I am trying to create a Django/Python app on Solana blockchain. I have been trying to figure out how I can add "Connect Wallet" button on HTML just like on this website. https://saber.so/ I would appreciate if anyone can guide me on this. Thanks in advance, Best regards, Shashank -
Django error: column does not exist but I have no control over that table?
I have made a few changes in the code, but nothing that changes the model or adds new things to the database. When I run on my computer it works fine, but when I try to build the docker image and run it gives me this error: Traceback (most recent call last): File "/home/go/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedColumn: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 35, in <module> main() File "/app/manage.py", line 31, in main execute_from_command_line(sys.argv) File "/home/go/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/go/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/go/.local/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/go/.local/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/go/.local/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/go/.local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/go/.local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/go/.local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/go/.local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 223, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/go/.local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/home/go/.local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) … -
Get All Changes of Any registered model of a single user django-simple-history
# settings.py INSTALLED_APPS = [ # ... 'simple_history', # ... ] MIDDLEWARE = [ # ... 'simple_history.middleware.HistoryRequestMiddleware', # ... ] Models: from django.db import models from apps.companies.models import Company from simple_history.models import HistoricalRecords # Create your models here. class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) history = HistoricalRecords() class Contact(TimeStamp): name = models.CharField(max_length=100, verbose_name='Person Name') user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) phone_number = models.CharField(max_length=100, verbose_name='Personal Number', null=True, blank=True) email = models.EmailField(null=True, blank=True, verbose_name='Personal Email') designation = models.CharField(max_length=100) history = HistoricalRecords() def __str__(self): return self.name user = User.objects.first() is there anyway to get all changes any model by the user -
How to integrate djoser to other apps in django rest framework
I have a project in Django-rest-framework using a react spa based on the youtube tutorial of Bryan Dunn - Web Development Videos here. I am stuck on how to extend this like if I want this to be a blog app. I am getting a csrf token validation error. This is what I've tried so far. #blog/view.py class BlogListAPIView(ListCreateAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() class BlogDetailAPIView(RetrieveUpdateDestroyAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() lookup_field = "id" is this a problem on frontend request? perhaps a header that have been missing or something or in the backend? Please help me! -
<Django> MySQL database to calculate over three values in the front end
I need to create a map to front end and there are some values that need to show on the map. The question is how to calculate the values in the database. There are two tables in the mySQL database One is the port table. Its column name are port_code, port name, … The other is cargo table. Its column name are port_code, cargo_measure, cargo_van1, cargo_van2, cargo_van3. The port code is AEDXB and how to calculate the value of the cargo in the port ,AEDXB? (there are also many ports but when people click the map in AEDXB, it need to show the cargo condition in AEDXB.) the value of the cargo= cargo_van1+cargo_van2+cargo_van3 if I use from django.db.models import Count MyModel.objects.filter( port_code in=(‘Cargo_measure’)).\ Values(‘port_code’).annotate(Count(‘Cargo_measure’)) Then I could not calculate the cargo value in the port of AEDXB. from django.db.models import Count MyModel.objects.filter( port_in=(‘Cargo_measure’)).\ Values(‘port’).annotate(Count(‘cargo_van1+cargo_van2+cargo_van3’)) This seems has errors. -
psycopg2.errors.InvalidTextRepresentation: malformed array literal ... DETAIL: Unexpected array element
I'm newbie with python django. And I try to create a Multi choices Test website. I'm a Vietnamese so my questions is in Vietnamese. I got an issues when I try to insert an object Answers into database. My error: django.db.utils.DataError: malformed array literal: "{"A": "C\u01a1m", "B": "ch\u00e1o"}" LINE 1: ...answer", "level") VALUES ('Hôm nay ăn gì', '', 1, '{"A": "C\... ^ DETAIL: Unexpected array element. My POST request: { "title": "Hôm năy ăn gì", "category": 3, "choices": { "A": "Cơm", "B": "cháo" }, "answer": "A" } Here is my code in models.py: from django.db import models from django.contrib.postgres.fields import ArrayField # Create your models here. class Category(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=False) class Question(models.Model): title = models.TextField(null=False, blank=False) description = models.TextField(null=False, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) # choices = ArrayField(ArrayField(models.TextField(blank=True))) choices = models.JSONField(null=False, blank=False) answer = models.TextField(null=False,blank=False) level = models.IntegerField(null=True, blank=True) In views.py: from django.db.models import query from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics from rest_framework import viewsets from app.models import User, Category, Question from app.serializers import UserSerializer, QuestionSerializer, CategorySerializer from django.shortcuts import get_object_or_404 # Create your views here. class CategoryViewSet(viewsets.ModelViewSet): serializer_class = … -
Django Filter __in multiple fields and in multple models
I'm trying to filter multiple fields in models and get the exact matching. models.py class Machine(models.Model): name = models.CharField(max_length=1330) code = models.CharField(max_length=1500,null=True, blank=True block = models.CharField(max_length=1500,null=True, blank=True) compatable = models.CharField(max_length=1500,null=True, blank=True) . . def __str__(self): return str(self.id) class Motor(models.Model): name = models.CharField(max_length=1330) code = models.CharField(max_length=1500,null=True, blank=True) code1 = models.CharField(max_length=1500,null=True, blank=True) code2 = models.CharField(max_length=1500,null=True, blank=True) . . def __str__(self): return str(self.id) class Tube(models.Model): name = models.CharField(max_length=1330) block = models.CharField(max_length=1500,null=True, blank=True) block1 = models.CharField(max_length=1500,null=True, blank=True) block2 = models.CharField(max_length=1500,null=True, blank=True) . . def __str__(self): return str(self.id) class Drum(models.Model): name = models.CharField(max_length=1330) compatable = models.CharField(max_length=1500,null=True, blank=True) compatable1 = models.CharField(max_length=1500,null=True, blank=True) compatable2 = models.CharField(max_length=1500,null=True, blank=True) . . def __str__(self): return str(self.id) If we choose one product from each model "Motor, Tube & Drum" and all the data goes to the CART model, then the query should filter the 3 fields and match and show the Exact Machine Products and vice versa. I Have done something like this in views.py def machine(request): combine = CartMotor.objects.values_list('motor__code', flat = True) combine1 = CartMotor.objects.values_list('motor__code1', flat = True) combine2 = CartMotor.objects.values_list('motor__code2', flat = True) combine3 = CartTube.objects.values_list('tube__block', flat = True) combine4 = CartTube.objects.values_list('tube__block1', flat = True) combine5 = CartTube.objects.values_list('tube__block2', flat = True) combine6 = CartDrum.objects.values_list('drum__compatable', flat = True) combine7 = … -
Unable to save Embedded field data in django admin
When I try to save an embedded field through django admin, it gives me an error AttributeError at /admin/myapp/post/add/ 'NoneType' object has no attribute 'attname' I'm using djongomapper as db connector to django and MongoDB. from djongo import models from django import forms # Create your models here. class Book(models.Model): title=models.CharField(max_length=200) author=models.CharField(max_length=200) class Meta: abstract = True class BookForm(forms.ModelForm): class Meta: model=Book fields = ('title','author') class Post(models.Model): heading = models.CharField(max_length=200) content = models.EmbeddedField( model_container = Book, model_form_class = BookForm ) objects = models.DjongoManager() #admin.py from django.contrib import admin from .models import * admin.site.register(Post) -
PostUpdateView is missing a QuerySet. Define PostUpdateView.model, PostUpdateView.queryset, or override PostUpdateView.get_queryset()
i am trying to edit a reply(message) done by a user on the website but when pressing the edit button instead of taking me to the page to edit it, it gives me this error: PostUpdateView is missing a QuerySet. Define PostUpdateView.model, PostUpdateView.queryset, or override PostUpdateView.get_queryset(). urls.py: path('boards/<int:board_id>/topics/<int:topic_id>/posts/<int:post_id>/edit/', views.PostUpdateView.as_view(), name='edit_post'), views.py: my application is called firstapp from os import name from django.db.models.base import Model from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse, response from firstapp.models import Board from django.contrib.auth.models import User from firstapp.models import Topic,Post from django.views.generic import UpdateView from django.utils import timezone class PostUpdateView(UpdateView): Model = Post fields = ('message',) template_name = 'edit_post.html' pk_url_kwarg = 'post_id' context_object_name = 'post' def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_dt = timezone.now() post.save() return redirect ('topic_posts',board_id=post.topic.board.pk,topic_id=post.topic.pk) models.py: class Board(models.Model): name = models.CharField(max_length=50,unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(Topic__board=self).count() def get_last_post(self): return Post.objects.filter(Topic__board=self).order_by('-created_dt').first() class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): return self.subject class Post(models.Model): message = models.TextField(max_length=4000) Topic = models.ForeignKey(Topic,related_name='posts',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): truncated_message= Truncator(self.message) return truncated_message.chars(30) … -
Django - ATFinfo() missing 1 required positional argument: 'test_case_ID'
I'm trying to add comments to my project and I've got this error: ATFinfo() missing 1 required positional argument: 'test_case_ID'. Here is my code. views.py def ATFinfo(Request,test_case_ID): if Request.method == 'POST': pi = APIDetails.objects.get(pk=test_case_ID) atfParam= list(APIParameter.objects.all('id','parameterName','parameterValue').filter(TC_ID=pi)) atf = APIDetails.objects.all() return render(Request, 'hello/ATF_Dashboard.html',{'ATF': atf, 'Param': atfParam}) here's my url: from django.urls import path from hello import views urlpatterns = [ path('api/taf_callback/', views.ATFinfo, name = 'ATFinfo'), ] Please help me to solve this issue not able to get the issue. -
Django send notification based on interaction with object
I've a post, where I need to send a notification when it is liked the 1st,5th,10th,25th,50th time. I was looking for an optimal way to this. What I've in mind right now is to store in the model something like first_interaction Boolean fifth_interaction Boolean So on.. Could there be a better way for this? -
duplicate .py files created for html and txt files in project after running compilemessages in django
I wanted to create .po and .mo files in my LOCALE folder therefore run makemessages and compilemessages commands. However, this also created .py duplicates of all files in the project that did not have .py extension. So now I have requirements.txt.py which content looks like this: XXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXX XXXXXXXXXXXXXX X XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX and many more files like that. Can anyone help me to solve this issue? -
JavaScript & Django -run the time continuously without refreshing the page
I have developed an Django application where it will take the time based on the timezone and it's working properly how could I make the time runnining continuously without refreshing the page. Even i have no idea to implement it in js or ajax. If anyknow how could be possible to implement django code with the js or ajax. P.S.I just tried writing js for the particular label which is "mytime" that holds the time which is supposed to be running continuously without refreshing the page. Thanks in advance single.html {% extends 'base.html' %} {% block content %} #js script <script type = 'text/JavaScript'> build() function build(){ var wrapper = document.getElementById('mydate') var url = 'http://localhost:1700/api/ben/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) var detail = data for (var i in detail){ // var item = '<td id ="td-row-${i}" class="table table-striped table-hover"> // <span class='currenttime'> ${detail[i].currenttime}</span> // </td>' } // var detail = data // var item = '<td id ='mydate'> {$(my_date)}</td>' } ) } <div class="container-md" id='firstcontainer'> <form action="" method="POST" autocomplete="off"> {% csrf_token %} <div class="container-md"> <h3 id ='user'>Search</h3> <div class="row"> <div class="input-group" > <div class="col-md" > <input class="form-control" type="search" placeholder="Search" id='btnsearch' name="finder" > <br> </div> <div class="pull-left"> <button class="btn … -
Run Selenium tests via Jenkins on Docker Django app
I would like to run Selenium integration tests on a Development server. Our App is Django app and it is deployed via Jenkins and Docker. We know how to write and run Selenium tests localy We know how to run tests with Jenkins and present Cobertura and Junit reports The problem we have is: In order for Selenium tests (apart from unit tests) the server needs to run So we can't run tests before we build docker image How to run tests inside docker images (this could be potentially achieved via script called inside Dockerfile...) BUT even more important: How can Jenkins get the reports from inside docker containers Whats are the best practice here. The Deployment structure: Jenkins get code from GIT Jenkins Builds docker images pass this image to the Docker registry (a private one) log in to the remote server on remote server pull the image from the registry run image on a remote server -
How to deal with .errors for Django API framework
I have the following codes: models.py class Device(models.Model): hostname = models.CharField(max_length=50, unique = True) ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['POST']) def create_device(request): device = Device() devicedetail = DeviceDetail() deviceserializer = DeviceSerializers(device, data = request.data) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if deviceserializer.is_valid() and devdserializer.is_valid(): device_instance = deviceserializer.save() devdserializer.save(DD2DKEY=device_instance) results = { "device":deviceserializer.data, "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) else: errors = { "device":deviceserializer.errors, "device_details" : devdserializer.errors, } return Response(errors, status=status.HTTP_400_BAD_REQUEST) I am facing the …