Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to relay user actions from the server to an external device
I have a web interface that allows the user to send remote commands to 1 or 2 robots. Currently the tasks are saved in the database (for logging as well) and the robot(s) keeps polling the django backend using GET requests every 125ms which gives acceptable response time without overly stressing the backend. In short: Action(User) -> [Remote Control UI] -> Django -> DB (based on user input) To get the actions the robot then does a GET request to Django as something like: while(ros::ok()) { response = requests.get(task_url, timeout=5) // input task(s) to state machine // execute task if possible rate.sleep(); } My question is: is there a better way? The remote control is sometimes disabled as the robot goes out of Wi-Fi so the solution needs some degree of flexibility to re-connection, IP changes and connection errors. I though about possible alternatives but not sure they are feasible: Require robots to register and save their IP (?) and send the command to the robot if registered Multicast the command to the entire Wi-Fi subnet (?) and let the robot read it Use django channels or some similar technology? I only found examples with [django or flask] + javascript. … -
Django: ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance
I am trying to automatically create a relationship between two test users in a migration in Django. My migration code looks like this: # Generated manually from django.db import migrations, transaction from django.contrib.auth import get_user_model def setup_test(apps, schema_editor): User = get_user_model() User.objects.create_superuser("admin", "admin@gm.org", "123") x = User.objects.create_user( username="x", email="a@gm.org", password="123" ) y = User.objects.create_user( username="y", email="b@gm.org", password="123" ) UserRelatinoship = apps.get_model("myapp", "UserRelatinoship") UserRelatinoship.objects.create(x=x, y=y, active=True) class Migration(migrations.Migration): dependencies = [ ("myapp", "0001_initial"), ("myapp", "0002_manual"), ] operations = [ migrations.RunPython(setup_test), ] The users are created fine, but then when I try to create the relationship I get the error ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance.. Note I modified some names from my original code. Any help is greatly appreciated! -
can't bind ForeignKey for form_valid
I am making hotel reservations but I have a problem with class OrderCreateView (generic.CreateView): I want to be linked to the hotel how can you make sure that there is a link to the hotels? My code: I think everything is fine here #models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) order = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='order' ) create_at = models.DateTimeField( auto_now_add=True ) arrival_date = models.DateTimeField( verbose_name='Дата заезда:' ) departure_date = models.DateTimeField( verbose_name='Дата отъезда:', ) name = models.CharField( max_length=50, verbose_name='Имя:' ) surname = models.CharField( max_length=50, verbose_name='Фамилия:' ) fatherland = models.CharField( max_length = 50, verbose_name='Отечество:', ) id_card = models.CharField( max_length = 50, verbose_name='Паспорт:', ) def __str__(self): return f"{self.name}" class Meta: verbose_name = 'Брони' verbose_name_plural = 'Брони' ordering = ('-create_at', ) but I think there is a problem in the form_valid, help me solve it please #views.py class OrderCreateView(generic.CreateView): model = Order form_class = OrderForm success_url = reverse_lazy('success_message') template_name = 'order/create.html' def form_valid(self, form): form.instance.user = self.request.user self.order = get_object_or_404(Hotel, kwargs={"pk": self.object.pk}) form.instance.order = self.order return super(OrderCreateView, self).form_valid(form) def successmessage(request): return render(request, 'order/success.html') Help me please -
Google Cloud - Django - OSError: [Errno 30] Read-only file system
I have deployed my django project on google cloud. One module of my app involves uploading files. When I am uploading my files on local server the files are successfully uploading but when I am trying to upload the files from the production server it is giving me the following error: OSError at /uploadrecords [Errno 30] Read-only file system: '/workspace/media/test.pdf' Following is my code for uploading files and the settings: #views.py image = request.FILES['filerecord'] fs = FileSystemStorage() filename = fs.save(image.name, image) obj.upfile = fs.url(filename) obj.save() #setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #MEDIA_ROOT = BASE_DIR / "media" Kindly suggest me a solution -
Django ORM create rows dynamically with _meta.get_fields()
I am writing a function to read xlsx and write this data to the database with Django. But I have so many fields that I cannot define statically. I want to write these fields to the database with a certain algorithm. When designing this, I get the class attributes with _meta.get_fields(). But as seen in this example, attributes always remain None. In views.py there is an example between BEGIN and END codes. How can i solve this problem? views.py # ... some codes ... @login_required(login_url='/admin/login/') def import_process(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_in_memory = request.FILES['file'].read() wb = load_workbook(filename=BytesIO(file_in_memory), data_only=True) ws = wb.worksheets[0] ws_company_name = str(ws["D9"].value) ws_company_address = str(ws["D10"].value) # ... some codes ... # Company Tower Get ID loop company_staff = CompanyStaff.objects.filter(company_id=Company.objects.filter(company_name=ws_company_name)[0].id)[0] for col in COLUMN_PARAMETER_LIST: column_cell = str(col) + str(COLUMN_PARAMETER_BEGIN) ws_tower_type = str(ws[column_cell].value) tower_type = TowerType.objects.filter(tower_type=ws_tower_type)[0] c_tower_object = CompanyTower.objects.filter(company_staff_id=company_staff,tower_type_id=tower_type)[0] tower_data = TowerData.objects.create(company_tower_id=c_tower_object) ROW_IDX = int(ROW_PARAMETER_BEGIN-1) # ****************** BEGIN ****************** # site_fields = tower_data._meta.get_fields() site_fields_names = [f.name for f in site_fields][1:] for mfield in site_fields_names: if any(word in str(mfield) for word in TOWER_DATA_EXCLUDE_FIELDS_NEW): continue else: ROW_IDX += 1 tower_data_cell = str(col)+str(ROW_IDX) tower_data_cell_value = ws[tower_data_cell].value tower_data.mfield = tower_data_cell_value if str(mfield) == 'ph': # Example Field print(tower_data.mfield) … -
['“<BoundField value=14.99 errors=None>” value must be a decimal number.']
I am creating a restaurant model and I get an error ValidationError at /api/restaurateur/create_meal/ ['“<BoundField value=14.99 errors=None>” value must be a decimal number.'] How can I fix this error? My view: @action(['POST'], detail=False, url_path='create_meal') def create_meal(self, *args, **kwargs): meal_data = self.request.data restaurant = Restaurant.objects.get(owner=self.request.user) serializer = MealSerializer(meal_data) meal_create(title=serializer["title"], description=serializer["description"], price=serializer["price"], restaurant=restaurant, slug=serializer["slug"], discount=serializer["discount"], ) serivce.py def meal_create(title, description, price, restaurant, slug, discount): meal = Meal.objects.create(title=title, description=description, price=price, restaurant=restaurant, slug=slug, discount=discount, ) meal.save() models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) discount = models.IntegerField(default=0) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField(unique=True) Why am I getting this error and how can I fix it? -
Using __range in datetime in Django
I bumped into some problem . I have this in views.py orders_completed = Order.objects.filter(customer=customer, complete=True) orders= [] for i in orders_completed : ordered_date = i.date_ordered valid_date = ordered_date + timedelta(days=5) if Order.objects.filter(id=i.id , date_ordered__range=(ordered_date ,valid_date)): orders.append(i) And I have sent orders in context for frontend. After this , even if the order places was on september 19th , its still showing when today is 28 th of September. I have specified the valid date as +5 of ordered date. -
How can I use a custom search field (model property) to search in Django Admin?
This is very similar to this question, but unfortunately, I still couldn't get it working. I have a model, with a property that combines a few fields: class Specimen(models.Model): lab_number = ... patient_name = ... specimen_type = ... @property def specimen_name(self): return f"{self.lab_number}_{self.patient_name}_{self.specimen_type}" In Django Admin, when someone does a search, I can use the search_fields attribute in the Model Admin to specify real fields, but not the specimen_name custom field: def specimen_name(inst): return inst.specimen_name specimen_name.short_description = "Specimen Name" class SpecimenModelAdmin(admin.ModelAdmin): list_display = ('specimen_name', 'patient_name', 'lab_number', 'specimen_type') search_fields = ('patient_name', 'lab_number', 'specimen_type') Doing a search using the code above, it will search the individual fields, but if I try to search for a full specimen_name in Django Admin, it won't find it, because none of the fields contain the exact, full specimen name. The SO question I linked to above pointed me in the right direction - using get_search_results. My code now looks something like this: class SpecimenModelAdmin(admin.ModelAdmin): ... search_fields = ('patient_name', 'lab_number', 'specimen_type') def get_search_results(self, request, queryset, search_term): if not search_term: return queryset, False queryset, may_have_duplicates = super().get_search_results( request, queryset, search_term, ) search_term_list = search_term.split(' ') specimen_names = [q.specimen_name for q in queryset.all()] results = [] for term in … -
how to fetch a item from model and save the same item in another model with form django
i have an ecommerce site i have tow model one name is item and other add to cart i want to fetch the model with it it id and want to the same item in another model so how i can do that this what i tried class Item(models.Model): auth = [ ('✔','✔'), ('✖','✖') ] categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default=None) swag = models.BooleanField(default=False) footwear = models.BooleanField(default=False) first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) taken_from = models.CharField(max_length=1000) color = models.CharField(max_length=30, blank=True) material = models.CharField(max_length=50, blank=False) return_policy = models.CharField(max_length=100, blank=False, default='7Days Return Policy') stock = models.CharField(max_length=50, blank=False, default='In Stock') authentic = models.CharField(max_length=1,blank=False,choices=auth, default='✔') price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) type = models.CharField(blank=True, max_length=100,) about = models.CharField(blank=True,max_length=100,) offer = models.CharField(max_length=4, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) description = models.TextField(blank=True) @staticmethod def get_items_by_id(ids): return Item.objects.filter(id__in = ids) def __str__(self): return self.name second model class Addtocart(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='cart_item') added_date = models.DateField(auto_now=True) def __str__(self): return self.user.username know what i want is to take that item id from item model and save it in add to cart model for that … -
wagtail: Adding page as the first child of the parent page on creation
Im trying to add the created list page as the first child of the parent Index page. The problem is that when I use django treebeard api django treebeard api it succeeds sometimes but other times it shows me an error: {'path': ['Page with this Path already exists.']} How can I solve this? CODE: @receiver(post_save, sender=ListPage) def move_page(sender, instance, **kwargs): instance.move(instance.get_parent(), pos='first-child') -
Get Average of three Boolean Fields
I am building a Simple Blog App and I am trying to get the average of three Boolean fields. For Example :- There are three boolean fields in model named bool_1, bool_2 and bool_3 and two of any three is True then show something. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) bool_1 = models.BooleanField(default=False) bool_2 = models.BooleanField(default=False) bool_3 = models.BooleanField(default=False) views.py def page(request): queryset = BlogPost.object.filter(user=request.user)..aggregate( avr=Avg(F('bool_1') + F( 'bool_2 ') + F('bool_3 '))).order_by('avr') context = {'queryset':queryset} return render(request, 'page.html', context) But it shows operator does not exist: character varying + character varying LINE 1: SELECT AVG((("app__blogpost"."bool_1" + "app__blogpost.. What have i tried :- I also tried by Case and then method like :- queryset = BlogPost.objects.filter( user=request.user).aggregate( boolean_value=Count(Case(When(bool_1=True, then=Value("Working"))))) but it showed {'boolean_value': 0} I have tried many times but it is still not working. Any help would be much Appreciated. Thank You. -
Django, storing PDF documents as archive belongs to objects
I have question about the django. I have many applications on my project, but i am trying to create different two app, and first one has PDF documents section. On the other hand i am trying to use other application as archive of this PDF's of the created objects. How can i do that, i could not imagine that how it will be coded. Thanks in advance. All notion are valuable! -
Django Postgres Connection Reset in Docker
I have a Django app and Postgres DB running on two separate containers. The DB connection from Django continues to be set whenever I startup the containers. I tried restarting Django, but get the same result. I'm able to go into psql from the Django container and view the tables. Error traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 76, in inner_run self.check_migrations() File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in … -
How to assign an event by passing the primary key (id) list as a parameter using javascript
I am outputting student information to table in django. The function we want to create is that the currently logged in teacher selects the checkbox of the desired student and clicks the "Add Teacher" button, then the name of the currently logged in teacher is added to the clicked student's teacher field. The name of the currently logged in teacher can be obtained as {{ request.user.name }}. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Teacher" class="addteacher"> The method I thought of is as follows, but the code does not work and seems to need improvement. Help! urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') --> It looks like the parameter needs a list. views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) --> Just like the parameter in urls.py needs to be changed to a list … -
In Django E-commerce app, how I send user wishlist (when user is not logged in) data to cart after user logged in, I used session for Wishlist
For that I used session to store product information for the wishlist and bu can't send when user is logged in/. -
Django backward foreign key query not working
hi i am working on a chat application on django with django channels and i am trying to query all the first messages of the user here when i do user.message_set.all() it is throwing AttributeError at / 'User' object has no attribute 'message_set' full traceback: Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/__neeraj__/Documents/chat/home/views.py", line 10, in index print(i.messages_set.all()) AttributeError: 'User' object has no attribute 'message_set' my models.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="receiver" ) text = models.CharField(max_length=2000) created_on = models.DateTimeField(auto_now=True) my view : def index(request): users = User.objects.all() context = {"users": users} for user in users: print(user.message_set.all()) return render(request, "index.html", context=context) is this because i have double foreign key reference of user model on message table? -
while going through api/register url the following error occurs AttributeError: 'function' object has no attribute '_meta'
urls.py file from .views import RegisterAPI , LoginAPI from knox import views as knox_views from django.urls import path from accounts import views urlpatterns = [ path('' , views.index , name='home') , path('register' , views.register , name='register') , path('login' , views.login , name='login') , path('logouts' , views.logouts , name='logouts') , path('api/register/', RegisterAPI.as_view(), name='register'), path('api/login/', LoginAPI.as_view(), name='login'), path('api/logout/', knox_views.LogoutView.as_view(), name='logout'), path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), ] above file is my urls.py file in which i am getting error when i am trying api/register -
How do you set select date in class CreateView (django.views.generic) for deadline?
I can select date for deadline if I creating gig in admin, but when user creates a new gig the datefield doesn't work in the form and I don't know how to set it. Can someone help? views.py class GigCreateView(CreateView): model = Gig template_name = 'gigs/create_gig.html' fields = ['title', 'industry', 'city', 'country', 'gigdescription', 'deadline', ] create_gig.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Gig</legend> <div class="card-body"> <h6 class="card-text">Title: &nbsp; {{form.title}}</h6> <h6 class="card-title">Profession: &nbsp; {{form.profession}}</h6> <h6 class="card-title">City: &nbsp; {{form.city}}</h6> <h6 class="card-text">Deadline: &nbsp; {{form.deadline}}</h6> <h6 class="card-text">Description: &nbsp; {{form.gigdescription}}</h6> </div> </fieldset> <div class="row justify-content-center"> <!-- Edit button --> <div class="form-group col-3 text-center"> <button class="btn btn-edit" type="submit">UPDATE</button> </div> <!-- Delete button --> <div class="form-group col-3 text-center"> <button class="btn btn-delete" type="#">DELETE</button> </div> </div> </form> -
Cannot assign "...'": "TestData.user" must be a "User" instance
Very new to the Django Rest Framework, so would appreciate some help with this one. I get the error in the title when I try and do a POST request in Postman with an appropriate auth token. I've made a table that I want to send a POST request to, but having issues with getting a user FK to be accepted as one of the columns. Plz see model/serializer/view below: Model class TestData (models.Model): TestSDG = models.DecimalField(decimal_places=0, max_digits=2, default=0) user = models.ForeignKey("auth.User", related_name="testdata", on_delete=models.CASCADE) Serializer class TestDataSerializer(serializers.ModelSerializer): class Meta: model = TestData fields = ('id', 'TestSDG') View @csrf_exempt def testDataApi(request, id=0): if request.method == 'GET': testdata = TestData.objects.all() testdata_serializer = TestDataSerializer(testdata,many=True) return JsonResponse(testdata_serializer.data,safe=False) elif request.method == 'POST': testdata_data=JSONParser().parse(request) testdata_serializer=TestDataSerializer(data=testdata_data) if testdata_serializer.is_valid(): testdata_serializer.save(user=request.user) return JsonResponse("Added Successfully", safe=False) The POST request works fine if I don't use the user as a foreign key, and I change testdata_serializer.save(user=request.user) back to testdata_serializer.save(), but I want the table to require a user's id. Appreciate any help, thank you. -
drf-yasg cover all responses to following implemented standard api response
I did implement the standard API response such as this article in my app. And I also implement drf-yasg for my API documentation. As we know the schema are using directly serializer to present the response. How I can cover all these below response examples by using drf-yasg schema? 1. Success Single { "status": 200, # int : http status, can be 201, 200, etc. "success": true, # bool: boolean to identify the response is success or failed. "message": "The success message", # str : string success message or null "result": {} # dict: a dict response data } 2. Success List { "status": 200, # int : http status "success": true, # bool: boolean to identify the response is success or failed. "message": null, # str : string message or null. "results": [], # arr : a list/array "count": 2, # int: all total result items "page_size": 5, # int: maximum items per-page "current_page": 1, # int: your current page "next": "http://127.0.0.1:8000/api/page/?page=2&search=a", # str: string link or null. "previous": null # str: string link or null. } 3. Error or Failed { "status": 400, # int : http status, can be 403,404,500,etc.. "success": false, # bool: boolean to identify … -
How to make new blog page with Wagtail in existing Django web-application project
I'm looking to add a blog page to an existing Django app that can be managed by Wagtail. Currently, using the official Wagtail documentation, Wagtail can be installed in the Django project, and the blog administration page (http://127.0.0.1:8000/cms/) is shown. However, even if I edit view.py and template.py, the Blog page (http://127.0.0.1:8000/blog/ ) remains in the initial screen("Welcome to..."), and the HTML file I created is not reflected Please,tell me how to create and show the blog page. The settings.py etc. are almost the same as in this page. index.html is a very simple one in templates\blog as a test. # blog/views.py from django.http import HttpResponse from django.views.generic.list import ListView from blog.models import TopPage class IndexView(ListView): model = TopPage template_name = 'blog/index.html' # blog/urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] # blog/models.py from django.db import models from wagtail.core.models import Page from wagtail.search.models import Query from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.images.edit_handlers import ImageChooserPanel class TopPage(Page): cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) intro = models.CharField(max_length=255) main_body = RichTextField(blank=True) side_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) side_title = models.CharField(blank=True, max_length=255) side_body = … -
Get foreign key element from a related_name on django
I have three models such as the one below and I am trying to write a query that allows me to access all the Day_Type associated to the Day objects that are pointing to a specific JobProject. I know that I can get all the Day pointing at a JobProject by querying project.jobproject_days.all() and I can get the values of the Day_Type by doing project.jobproject_days.values_list('day_type__name', flat=True) BUT how can I get the Day_Type themselves? class JobProject(models.Model): ...... class Day_Type(models.Model): name = models.CharField(max_length=30) class Day(models.Model): .... day_type = models.ForeignKey(Day_Type, blank=True, on_delete=models.CASCADE, null=True, related_name='day_type') project = models.ForeignKey(JobProject, blank=True, on_delete=models.CASCADE, related_name='jobproject_days', null=True) -
Django: select all data from a row in a html table and use them in a view
I am new to both django and web development. The task is to run a script when pressin a button using the data contained in the specific row of an html table. So if i clik on the second button "Run script" it uses all the data in that row (8888, 2020/06/21 06:00) in a separate script to performe some task. Currently my html file looks like this: There are 2 sections one for uplading the information that goes in the table one the table which displays them <h1>Approach Path KML Generator</h1> <h2>Generate the KML file here:</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button onclick="location.href='{% url 'approach_path_receptorsKML:Proejct Creator' %}'">Upload</button> </form> <h2>Projects Available:</h2> <table class="table"> <thead> <tr> <th>Project ID</th> <th>Date KML</th> <th>Time KML</th> <th>Date-Time Uploaded</th> <th>Run The Conversion</th> <th>KML File</th> </tr> </thead> <tbody> {% for project in latest_project_list %} <tr> <td>{{ project.project_ID }}</td> <td>{{ project.date_kml }}</td> <td>{{ project.time_kml }}</td> <td>{{ project.upload_time }}</td> <td> <button method="post" value="collect data" name="{{ project.project_ID }}|{{ project.date_kml }}|{{ project.time_kml }}|{{ project.upload_time }}">Run script</button> </td> <td> <a href="{{ project.download_doc }}" class="btn btn-primary btn-sm">Download KML File</a> </td> </tr> {% endfor %} </tbody> </table> And this is the view I have created: def ProjectCreator(request): form = DocumentForm() … -
How to change html background color using django code
I was doing a project and I was wondering, I wanted to make a button in HTML which would be controlled in the Django views.py. So basically when someone clicks on the button the background becomes dark and it gets saved, what I mean is if the person refreshes the page the background will still be dark. I wanted to know if it was possible to do it. Thanks. -
Run Django and GRPC same application
I'm working on the Django rest framework project and I need to work with gRPC as well. But I don't know how to manage to run both HTTP server and gRPC server same time. Like in .NET it has option to listen both HTTP1 and HTTP2. When I use command python manage.py runserver then gRPC doesn't work and when I used python manage.py grpcserver then Rest API doesn't work Is there any solution to this problem? Thanks. I used packages: djangorestframework and django-grpc