Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the information of a specific object that is retrived from a django model using for loop
I have a boostrap slider which is populating using for loop and django model objects now I want that if I click on any of the slider object then it show me the information related to that specific object which I clicked the Information must be retrived from the django model. Thanks In Advance please help me to get out of this situation .. Here is my code which is populating the slider. I want when I clicked on any object in the loop it should only show me the information related to that object. {% for product in products %} <div class="services-block-two"> <div class="inner-box"> <div class="image"> <a href="building-construction.html"><img src="/{{ product.prd_logo }}" alt="" /></a> </div> <div class="lower-content"> <h3><a href="building-construction.html">{{ product.prd_name }}</a></h3> <div class="text">{{ product.prd_des }}</div> <a href="building-construction.html" class="read-more">Read More <span class="arrow flaticon-next"></span></a> </div> </div> </div> {% endfor %} -
why am getting error by running python manage.py runserver command?
when am trying to run python manage.py runserver am getting this error why ? its when i done cd haddygirl and the command python manage.py runserver plese help me !!!? DLL load failed means ? C:\Users\Lazxy\haddygirl>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lazxy\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Lazxy\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Lazxy\Anaconda3\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 47, in class AbstractBaseUser(models.Model): File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\base.py", line 117, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\utils.py", … -
Django logs colors depending on error level, without module
I use the standard Django logging based on Python’s builtin logging module. My logging configuration in settings.py in is close to the following: import logging logger = logging.getLogger(__name__) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '\x1b[33;21m{levelname} {asctime} {module} {process:d} {thread:d}\x1b[0m: {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'sentry': { 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, }, 'loggers': { '': { 'handlers': ['console', 'sentry'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': True, }, }, } I would like to know if it is possible to have ansi color (in this example, \x1b[33;21m) depending on levelname in the format, without installing additional modules like colorlog. -
Django - can't start server
I am getting the following error when I try to start the server locally (./manage.py runserver). Posting the question after spending 5 hours of searching solution. Attached the error stack. I am using Django 2.2.2. Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "./manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 585, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 570, in start_django reloader.run(django_main_thread) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 288, in run self.run_loop() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 294, in run_loop next(ticker) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 334, in tick for filepath, mtime in self.snapshot_files(): File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 350, in snapshot_files for file in self.watched_files(): File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in watched_files yield from iter_all_python_module_files() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 116, in iter_modules_and_files if module.__name__ == '__main__': File "/usr/lib/python3/dist-packages/py/_apipkg.py", line 171, in __getattribute__ return getattr(getmod(), name) … -
How to store user files in django that are internally downloaded
So i am making a website where people can download and visualize some data that is downloaded from another website, and I can't figure out how to store this data in Django .Also the data should be stored separately for every user. And is in a folder format. Maybe i may have to make a model for it or something else. Pls help me I havent tried to use the file system because i dont know how to store data that is internally downloaded from another website(isnt uploaded by the user). from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UserManager from django.db import models from django.contrib.auth import get_user_model User_auth = get_user_model() ............ class GoogleFile(models.Model): user = models.ForeignKey(User_auth, on_delete=models.CASCADE, null=True) data = models.FileField(upload_to='user_google_data') class FacebookFile(models.Model): user = models.ForeignKey(User_auth, on_delete=models.CASCADE, null=True) data = models.FileField(upload_to='user_facebook_data') -
how to deploy Web server & API server in 1 heroku app? Heroku + Docker (deployed with heroku.yml)
I want to deploy Vue app whose script has a couple of ajax request to django API server like follows: getRecordList: function(){ this.records = []; this.$axios .get('http://[ip address for API server]') .then(response => {}) .catch(err => {}) }) I am thinking to deploy this app to heroku with the following heroku.yml. But both web and api container has to accept http request. The container with the name: 'web' only accepts Http request. (According to heroku website) Should I create multiple heroku app? Or is there any workaround? Any suggestions are appreciated. Thank you for your time. what I do for deploying git add heroku.yml git push heroku master and this will push the whole images to the heroku repository, in running process, CMD lines will be executed. heroku.yml build: docker: web: bootstrapdebug/Dockerfile api: apis/Dockerfile apis/Dockerfile FROM python:3.6 ENV PYTHONBUFFERED 1 WORKDIR /app COPY . /app/apis WORKDIR /app/apis RUN python3 -m pip install -r requirements.txt --no-cache-dir CMD ["python", "manage.py", "runserver", "0.0.0.0"] bootstrapdebug/Dockerfile FROM node:12.10.0-alpine WORKDIR /app COPY . /app/bootstrapdebug WORKDIR /app/bootstrapdebug RUN apk update && \ npm install && \ CMD ["npm", "run", "serve", "--", "--port", "$PORT"] -
Error: Cannot resolve keyword 'id' into field
class Profile(models.Model): name=models.CharField(max_length=20, primary_key=True ) age=models.IntegerField() def __str__(self): return self.name class Like(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) like=models.IntegerField(default=0) def __str__(self): return self.choice_text in python manage.py shell command: from database.models import Profile, Like p=Profile(name='test', age=66) p.save() p.id AttributeError Traceback (most recent call last) <ipython-input-35-25ec00f2e4bf> in <module> ----> 1 p.id But if you follow the example on www.djangoproject.com , you will get to see result of p.id is 1. Any help will be appreciated to understand the databases as I never worked on the databases. -
Django: pre-fetch custom model field (django-simple-history)--performance optimization
I am trying to optimize my querysets. I extensively make use of django-simple-history I have models as follows wherein I have a method with which I want to track changes to the fields: class TrackHistoryMixin(models.Model): history = HistoricalRecords(inherit=True, cascade_delete_history=True) has_history = models.BooleanField(blank=True, default=False) class Meta: abstract = True @property def changed_fields(self): first_record = self.history.last() latest_record = self.history.latest() delta = first_record.diff_against(latest_record).changed_fields no_history_fields = ['from_portal', 'has_history', 'document'] for field in no_history_fields: try: delta.remove(field) except ValueError: pass return delta @property def old_portal_values(self): if self.changed_fields: old_object = self.history.last().__dict__ old_portal_values = dict() for field in self.changed_fields: old_portal_values.update({field: old_object[field]}) return old_portal_values The problem with performance is that I cannot use select_related, or prefetch_related with the history field above. Thus, when I load an instance of a model which inherits from the TrackHistoryMixin, and I need to interact with the history field, it hits the database. The best thing I could do so farin my templates is that for each record I put the history field in a variable with {% with variable=object.history %}. But given that I have numerous records, performance still suffers. How can I prefetch such field such that when I get a queryset, all the history related data are loaded as well? I … -
Docker- django throws error while connecting to postgres: psycopg2.OperationalError: could not connect to server: Connection refused
I am trying to dockerize my Django-postgres app. My Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My docker-compose.yml is: version: '3' services: web: build: . command: python vessel_locator/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres ports: - "5432:5432" environment: POSTGRES_PASSWORD: password and my settings .py has the following database code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '0.0.0.0', 'PORT': '5432', } } My db and web containers are up but when I run: docker-compose run web python manage.py migrate I am getting the error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? How can I make my containers communicate? -
Django rest framework : need to map two different functionalities on same view
I want a common view(class),that returns just a json sort of response on POST and on GET it should return the json response but to a page(html template) because I have a single url upon which get and post requests have this kind of behaviour. If I use "APIView" I cannot return a new page and if I use a "TemplateView" the api response doesn't work as expected. Any help? I do not want to use function based views. -
Django change to class based view
I would like to add a function based view to a class based view but always get error TabError: inconsistent use of tabs and spaces in indentation. Function based view: def search_index(request): results = [] search_term = "" if request.GET.get('query'): search_term = request.GET['query'] results = esearch(query=search_term) print(results) context = {'results': results, 'count': len(results), 'search_term': search_term} return render(request, 'esearch/base.html', context) base.html <form class="form-inline"> <input class="form-control mr-sm-2" type="query" placeholder="query" aria-label="query" name = 'query' value = ""> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Class based view that is not working class TemplateFormView(FormView): template_name = 'esearch/base.html' form_class = CateChainedSelect2WidgetForm def search_index(self, request,*args,**kwargs): search_term = request.GET.get('query') results = esearch(query=search_term) //this is where the taberror shows. print(results) context = {'results': results, 'count': len(results), 'search_term': search_term} return context What's missing here? -
ImageField upload_to doesn't work with django update statements
models.py class Movies_list(models.Model): movies_thumbnail=models.ImageField(default='thumbnail.jpg',upload_to='movies_pics') def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.movies_thumbnail.path) if img.height > 100 or img.width > 100: output_size = (200,300) image_movies=img.resize(output_size,resample=Image.ANTIALIAS) image_movies.save(self.movies_thumbnail.path) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' views.py form=Update_Movies_form( data=(request.POST or None), files=(request.FILES or None), # instance=obj ) form.fields["movies_thumbnail"].initial = obj.movies_thumbnail movies_detail=Movies_list.objects.filter(movies_id=movies_id) print(movies_detail) url=url_filter(request,movies_id) if form.is_valid(): if request.user.is_staff: obj_movies_update=Movies_list.objects.filter(movies_id=movies_id).update( movies_thumbnail=request.FILES["movies_thumbnail"], forms.py class Create_Movies_form(forms.Form): movies_thumbnail=forms.ImageField(widget=forms.ClearableFileInput(attrs={'placeholder': 'thumbnail'})) on update form submition it save movies_thumbnail in media folder not in media/movies_pics so i try to forcefully save it in movies_pics by replacing movies_thumbnail=request.FILES["movies_thumbnail"], to movies_thumbnail="movies_pics/"+str(request.FILES["movies_thumbnail"]), It save image in movies_pic and work just fine but didn't crop image as specified in models.py def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.movies_thumbnail.path) if img.height > 100 or img.width > 100: output_size = (200,300) image_movies=img.resize(output_size,resample=Image.ANTIALIAS) image_movies.save(self.movies_thumbnail.path) -
Django: Update Page Information Without Redirecting
I have this code: html <form method="post" id="idForm" name="frm1" action = "/myproject/save/" enctype="multipart/form-data"> {% csrf_token %} .... <input type="submit" name="save" id="save" value="Save"> </form> <span class="status">Value: &nbsp;{{ request.mylist}} </span> js code $(document).on('submit', '#idForm',function(e){ $.ajax({ type: 'POST', url: '{% url "myproject:save_form" %}', data: {}, success:function(json){ $('.status').contents()[0].textContent = data.mylist }, error : function(xhr,errmsg,err) { alert("ajax error") } }); }); views if request.method == 'POST' and 'save' in request.POST: print("runs save form") mylist= [5] return JsonResponse({'mylist':mylist}) Question: When I click on Save button, It is redirected to a page with {"mylist": [5]} How can I make it update only the status part, Value? -
Django urls with UUID issue
I am trying to redirect to the view based on the CustomerID but its not working for UUIDs. It was previously working fine with integers. Please suggest. url.py: from django.urls import path, include from . import views urlpatterns = [ path('create/', views.create, name='create'), path('<uuid:customer_id>', views.detail, name='detail'), path('search/customers/<uuid:customer_id>', views.detail, name='detail'), path('customers/<uuid:customer_id>', views.detail, name='detail'), path('edit/<uuid:customer_id>', views.edit, name='edit'), path('modify/<uuid:customer_id>', views.modify, name='modify'), ] views.py @login_required def detail(request, customer_id): customer = get_object_or_404(CustomerMaster, pk=customer_id) return render(request, 'customers/detail.html',{'customer':customer}) -
Is there a way that to "docker-compose build" utilize existing dependencies wheels?
To make a change in the dependencies of a docker container, i'm runing docker-compose build. I want to update a dependency listed on requirements.txt to be more specific. But everytime that I execute this, it redownload all the requirements again instead of use existing wheels. Am I missing something or is this the behavior by default? Is there a way change this behavior to make use of wheels created before? The project was created with Django-Cookiecutter: docker=yes This is my local.yml: version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: cctest_local_django depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: cctest_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres Dockerfile: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add postgresql-client # Requirements are installed here to … -
How I can compare the entered input value with the value of API in Django
Nowadays, I am trying to make a Post-Office Assistant web-site using Django. The things I have to do are: Creating homepage with a search input and submit button Getting the entered input value (namely, order ID) and compare it with the values (order IDs) in my API. If the value (order ID) is the same with any value (order ID) show the details of value (order ID) in my API. Otherwise show "There is no any profile with this order ID". Can anyone help me to create this website? Can anyone create and share source code as zip format with me? Thanks in advance. -
How could I add a helper function in Django to match a topic with its user and show Http404 if not the case?
thank you beforehand. This is my first post, I´ll try to be brief. I´m going through exercise 19-3 Refactoring in Python Crash Course. However I'm a bit stuck in it. I should make a function to check the owner of a topic, and if not the case raise a Http404 error. I tried to create a "utils" folder and house my function there, but had a Name Error, so I deleted it. Then tried to store the function in the same file, but I raised a Http404 error even when the user was the owner of the topic. I left it as before trying this exercise with the function in place commented out: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) # check_topic_owner(request) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def edit_entry(request, entry_id): """Edit an existing entry""" entry = Entry.objects.get(id=entry_id) topic = entry.topic # check_topic_owner(request) if topic.owner != request.user: raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) #The function to … -
Django Displaying images uploaded by ImageField properly
I'm building my own porfolio using Django, and I just had a question regarding uploading images using the ImageField. I uploaded an image through the admin page using ImageField, and after a long search session, finally got my page to display the image successfully. urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('pages.urls')), # main landing page path('admin/', admin.site.urls), path('project/',include("projects.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) projects.html <img src="{{project.image.url}}"> However, the official django docs say that this is not a good way to deploy a django site. Why is that, and what is the best/proper way to display images? -
Blocked by CORS policy : No 'Access-Control-Allow-Origin' header is present on the requested resource
Hi I am using django rest framework as API service and React as frontend.I can call the api from react when developing and when i deploy to iis.I got this error No 'Access-Control-Allow-Origin' header is present on the requested resource. I already do like this say=>CORS Error but I still got this error. My Django runs on localhost:81 My react app run on : 192.168.1.32:81 I can run this on local server which both installed but when I try on another computer I got this error. I used the fiddler 4 for override the port in the hostname. -
How to set initial value of primary key in django
I made this django model: class Car(models.Model): car_id = models.AutoField(primary_key=True) engine_size = models.FloatField() fuel_consumption = models.FloatField() def __str__(self): return(str(self.car_id)) The automatic field generator in django always starts from 1. How do I make it generate id from initial value=100. For example, 100,101,102... -
Django template ajax call to api - invalid literal for int() with base 10: '[object Object]'
Hi i'm trying to call to my django api from with an ajax call from my django template The API receive a POST request with the value of an id in the url My api view: @api_view(['POST']) def add_favorite(request, property_id): if request.method == 'POST': try: favorite_property = Property.objects.get(pk=property_id) if request.user.is_authenticated: login_user = request.user if not login_user.properties.filter(pk=property_id).exists(): login_user.properties.add(favorite_property) return JsonResponse({'code':'200','data': favorite_property.id}, status=200) else: return JsonResponse({'code':'404','errors': "Property already exists in favorite"}, status=404) except Property.DoesNotExist: return JsonResponse({'code':'404','errors': "Property not found"}, status=404) My html with the anchor link to ajax call: <a id="mylink" href="javascript:onclickFunction('{{ property.id }}')"> <i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i> </a> And this is how i call to API in my django view to try and get response: <script> $(document).ready(function () { $('#mylink').on('click', function (property_id) { property_id.preventDefault(); $.ajax({ type: "POST", url: "http://localhost:9999/api/add_favorite/" + property_id.toString() + "/", beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}'); }, success: function (data) { var obj = jQuery.parseJSON(data); alert(obj); } }); return false; }); }); </script> When i try to press the link it return the following error: ValueError: invalid literal for int() with base 10: '[object Object]' web_1 | [24/Sep/2019 03:13:14] "POST /api/add_favorite/[object%20Object]/ HTTP/1.1" 500 17473 I tried to turn the property_id … -
How do I get the specific ID of my survey question in question set filtered by department in URL Template Django
How do I get the specific ID of my survey question in question set filtered by department in URL Template Django? def survey_select(request, id): try: department = Department.objects.get(id=id) except Department.DoesNotExist: raise Http404("No MyModel matches the given query.") department = Department.objects.get(id=id) questionset_list = QuestionSet.objects.filter(department=department) context = {'questionset_list': questionset_list} return render(request, 'question_set.html', context) def test_survey(request, id): try: department = Department.objects.get(id=id) except Department.DoesNotExist: raise Http404("No MyModel matches the given query.") department = Department.objects.get(id=id) question_set_items = QuestionSet.objects.filter(department=department) question_set = (c.name for c in question_set_items) print("Question for this department") print(question_set_items) if request.method == 'POST': form = ResponseForm(request.POST, department=department) if form.is_valid(): response = form.save() form = ResponseForm(department=department) # return HttpResponseRedirect("/survey/%s" % response.customer_uuid) messages.success(request, 'Thank you!', extra_tags='alert') else: form = ResponseForm(department=department) print(form) # TODO sort by question_set return render(request, 'survey.html', {'response_form': form, 'department': department, 'question_set': question_set}) -
How can I update a field in two tables in django with a query?
I'm trying to update two fields in two tables using Django's orm. model like this: class User(models.Model): name = models.CharField(...) age = models.CharField(...) class Blog(models.Model): user = models.ForeignKey(User, ...) user_name = models.CharField(...) text = models.TextField(...) How to implement MySQL statement: update user a, blog b set a.name = 'new name', b.user_name = 'new name' where a.id = b.user_id and a.id = 1; -
Need help accounting for latency in simple multiplayer game
At the moment, to account for latency, in my game (it is essentially tron lightcycles, but to move, one must solve a math problem), I send out the game state to both players every time one of the players turns. On the frontend, I have a function that draws and a function that undraws (to account for when there is latency). Currently, the setup is not performing the desired behavior: the players are not in sync with each other (neither movements nor positions at which users turn are the same for both players). Can someone help me out? This is my first time making a game. Here is the backend code: def send_answer(answer, game_object, player_type, current_position, current_direction): creator_directions = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_directions = ['p2up', 'p2right', 'p2down', 'p2left'] with transaction.atomic(): # d for direction if player_type == 'creator': for d in creator_directions: if is_correct_answer(getattr(game_object, d), int(answer)): context['move_direction'] = d print(context) new_problem = generate_problem_game( game_object.level, game_object.operation, game_object, player_type) setattr(game_object, d, new_problem) game_object.save() context['new_problem'] = [d, new_problem] # calculate draw and undraw positions p1_last_pos = game_object.p1lastposupdate p1_lp_timestamp = game_object.p1lpuTimestamp time_inbetween = timezone.now() - p1_lp_timestamp ti_milliseconds = time_inbetween.seconds * 1000 p1_lp_split = p1_last_pos.split(',') p1_lp_x = int(p1_lp_split[0]) p1_lp_y = int(p1_lp_split[1]) draw_positions = [] … -
Saving a JSON Array list of values to MySQL
I have been stuck with this code in the Python views. What I'm doing is, I'm trying to get the JSON array list that came from the local storage, and individually transfer it, using self.request.POST[]. Also the values came from modal. I'm still new to Python, so I still don't know how some functions work. I've tried the for range(len()), and it works in accessing the values of each array list. the problem is I can't save this using the POST method. is there a way I can store this to the database. itemdata = self.request.POST['itemdata'] jobject = json.loads(itemdata) for i in range(len(jobject)): print(jobject[i]['invitem_id']) invitem_id = jobject[i]['invitem_id'] invitem = Inventoryitem.objects.get(pk=self.request.POST['invitem']) self.object.invitem = invitem.id[invitem_id] Here are the array list values, I want to be stored. [{"invitem_id":"85","invitem_code":"01086","invitem_desc":"1/2 PROGRAMMING FOR PONGRASS PONENTRY","charging_type":"P","unitofmeasure_id":"2","unitofmeasure_code":"BX","quantity":"123","discountamount":"123","discountrate":"%","unitcost":"123","grossamount":"123","netamount":"123","vatable":"123","vatexempt":"123","vatzerorated":"123","vatamount":"123","branch_id":"5","branch_code":"HO","department":"24","department_code":"AM","employee_id":"784","employee_code":"012068506","employee_name":"RAMONA ABAD","remarks":"123124"}] The output gives an error invalid literal for int() with base 10: ''