Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save image captured from webcam to folder
I am working on a Django web application. In this application a user can trigger their webcam and capture a photo with a press of a button. This photo should then be saved to the server. The problem I am facing is, I am not able to save the photo. This is my code so far html <video id="video" width="640" height="480" autoplay></video> <button id="snap">Snap Photo</button> <canvas id="canvas" width="640" height="480"></canvas> javascript // Grab elements, create settings, etc. var video = document.getElementById('video'); // Get access to the camera! if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { //video.src = window.URL.createObjectURL(stream); video.srcObject = stream; video.play(); }); } // Elements for taking the snapshot var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var video = document.getElementById('video'); // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 640, 480); }); With this code I am able to snap a picture into a canvas but I am stuck trying to save this to the server folder. on some research, I figured this is not possible only with javascript and that I will be requiring a scripting lauguage like python or php. Since I am using django, python seems like a better option here. But I … -
How do I send column values that I received with Request.Get.get consecutively?
I do order by with request.GET.get('order_by',None) but Now I want to trade with more columns. Ex: https://www.example.com/?oby=col1&oby=-col2 and I want get values. columns = request.GET.getlist('order_by') Then, References.objects.order_by(*columns) How do I create the above url? I tried to add the values I received with Request.GET.get to the list, but it was unreasonable. Because the same columns were added again. -
How to filter foreign key objects in django queries?
I have two models, one related to other by foreign key like this class CapturedPrescriptionModel(ColModel): p_id = models.IntegerField() p_age = models.IntegerField() p_gender = models.CharField(max_length=10) p_care_type = models.CharField(max_length=100) bacteria_id = models.ForeignKey(BacteriaListModel, on_delete=models.CASCADE, null=True) class SuggestedAntibioticsModel(ColModel): prescription_id = models.ForeignKey(CapturedPrescriptionModel, related_name='antibiotics', on_delete=models.CASCADE) cat_ids = models.TextField() flag = models.IntegerField(default=0) Now I want all the prescriptions with suggested antibiotics where flag=1 I have tried with CapturedPrescriptionModel.objects.filter(antibiotics__flag=1) but that filter the prescriptions not the list of antibiotics in the queryset. [ { "id": 7, "p_id": 0, "p_age": 19, "p_gender": "Male", "p_care_type": "ICU", "bacteria_id": null, "antibiotics": [ { "id": 188, "cat_ids": "[]", "flag": 0, "antibiotic_id_id": 87, "prescription_id_id": 7 }, { "id": 187, "cat_ids": "[]", "flag": 1, "antibiotic_id_id": 112, "prescription_id_id": 7 }, ...... ] } .... ] My expected result will be like this [ { "id": 7, "p_id": 0, "p_age": 19, "p_gender": "Male", "p_care_type": "ICU", "bacteria_id": null, "antibiotics": [ { "id": 187, "cat_ids": "[]", "flag": 1, "antibiotic_id_id": 112, "prescription_id_id": 7 } ] } .... ] -
Loading dictionaries and list only once during a whole django project session
I have a django project where I need to load some external data (sparse matrix, lists, dictionnaries) that will be used for a specific view. Loading these files each time the view is requested is not optimal because it takes time to load them, so I wanted to know if there was a way to load everything only once while the project is being loaded with the command python manage.py runserver and thus have those loaded files as global elements of the project. Is it possible to do so? If it's not possible to do it with the runserver command, what alternative do I have? -
How to Login programmatically in Django?
I need to login programmatically in Django.I had registered by using normal registration page. but i need to login for a single person by saying the username and password in the program itself.So he is allowed to view the requested page.I don't need user authorization, just to redirect the page if username and password is " given in the program.." -
Connect docker to docker containers using wildcard subdomains
I can connect to other docker services from a docker container using their service names. So for example, I can do a get request to my flask app using http://flask-container:5000 from my django app directly. I could also call one django app from another app (same container) using http://django-container:5000/someurlpath. The django project is configured to use django-hosts for subdomains. From my host machine it works using an nginx-proxy. Is there any docker-compose configuration way, such that I can call the subdomains using the service names such as http://api.django-container:5000? -
Using @classmethod for creating objects in django for testing purposes
Both on the higher level perspective work, however which is preferred and why when it comes to creating objects for testing in Django ? For testing purposes, that is , test_models.py file Using @classmethods class AuthorModelTest(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(first_name="Big", last_name="Bob") Or passing self instead of referring to the class class AuthorModelTest(TestCase): def setUpTestData(self): Author.objects.create(first_name="Big", last_name="Bob") -
How to change permission of django project?
I have created my project in centOS 7 using root.Each time when saving the project after changes its asking the password.How do I change the permissions of the whole project now ? -
How to get comma separated values from a table linked with foriegn key?
I have an issue where i want to return a list of images in the response. I created an foreign key named pest_id which is linked to the main KnowledgeBase Table. Now if i use the specified way, like KnowledgeBase.objects.values('id', 'pest_id', 'pest__name', 'pest__title', 'pestimages__image', 'front_image', 'cause', 'effect', 'remedy', 'prevention') I get the list, but the output is { "id": 1473, "pest_id": 249, "pest__name": "Worker stuff little store three operation news. Move world affect small. Entire past face partner.", "pest__title": "surya", "pestimages__image": "extras/f4e8482c69e4e562d86149b45da8565e.jpg", "front_image": "images/plant-3250.jpg", "cause": "Summer popular music provide white.", "effect": "That unit article practice feel nature.", "remedy": "Car including hair before impact least scene tough. Generation job painting in develop issue mean half.", "prevention": "Every business price step themselves own. Treatment guess far senior response. See a development last." }, { "id": 1473, "pest_id": 249, "pest__name": "Worker stuff little store three operation news. Move world affect small. Entire past face partner.", "pest__title": "surya", "pestimages__image": "extras/f2f05d15bf695d5bb45ca909887230f9.jpg", "front_image": "images/plant-3250.jpg", "cause": "Summer popular music provide white.", "effect": "That unit article practice feel nature.", "remedy": "Car including hair before impact least scene tough. Generation job painting in develop issue mean half.", "prevention": "Every business price step themselves own. Treatment guess far senior response. … -
(Django) How can to run test suite in Travis CI
I am having issues running a test suite in a dockerize Django application using Travis CI. I ran the test suite locally without any issue i.e after using: docker-compose up --build -d docker-compose run django --no-deps python manage.py test polls This is my github repo: https://github.com/bgreatfit/Docker_django Everything works(test suite) fine on my local machine that contains the Dockerized Django Application. While in Travis the build creation is successful but test suite doesn't run. This is the last line of the output on Travis: docker_django-mysql | Version: '5.6.43' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) This is my travis url:https://travis-ci.org/bgreatfit/Docker_django This is my travis.yaml file sudo: required services: - docker before_install: - docker-compose up -d - docker ps script: - docker-compose run django python manage.py test polls This is my docker-compose file version: "3.1" services: django: build: ./app container_name: ${PROJECT_NAME}-django command: gunicorn first_project.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/app - static_volume:/app/static expose: - 8000 depends_on: - mysql mysql: image: mysql:5.6 container_name: ${PROJECT_NAME}-mysql volumes: - db-data:/var/lib/mysql environment: - MYSQL_ROOT_PASSWORD=docker_root - MYSQL_DATABASE=docker_django_db - MYSQL_USER=dbuser - MYSQL_PASSWORD=dbpw ports: - "8306:3306" phpmyadmin: image: phpmyadmin/phpmyadmin container_name: ${PROJECT_NAME}-phpmyadmin environment: - PMA_ARBITRARY=1 restart: always ports: - 8082:80 volumes: - /session nginx: build: ./nginx container_name: ${PROJECT_NAME}-nginx volumes: - static_volume:/app/static … -
filter using the djangofilterbackend on the muliselectfeild
Unable to filter using DjangoFilterBackend, Its returns NULL. While using other attribute like name or value it works fine. __basic_fields =('name',) filter_fields = __basic_fields It returns correct value. class MyDetailViewSet(ModelViewSet): queryset = putDetails.objects.all() serializer_class = putDataSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) __basic_fields =('stock',) filter_fields = __basic_fields 'stock' is Multiselectfeild in my models.py. Should I handle multiselect in some other way? -
Why are the two ways different results?
Same code different results. So, why? # User/Info => the model class # First users = User.objects.values('nickname').distinct() # right # Second info = Info.objects.values('area').distinct() # wrong ??? WHY info = Info.objects.order_by('area').values('area').distinct() # right Django Rest Framework 3.9 -
Can't connect to server error Google App Engine Static Files Issue
I’m having difficulties switching my google app engine web app from a standard to a flex environment using Django. I need to switch to a flex environment since I am using the module pdf2image in my app, which uses poppler. Here are my app.yaml, Dockerfile, and snippets from my settings.py. Note: -Before making these changes the app ran as it should locally. -There are probably multiple errors and we would appreciate any feedback on which parts to fix. Thanks! Here is the error which is showing: File "/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 164, in __init__ super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") Here are our relevant code snippets: app.yaml: # [START django_app] runtime: custom env: flex handlers: # This configures Google App Engine to serve the files in the app's # static directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to the main app. # It is required when static routes are defined, but can be omitted # (along with the entire handlers section) when there are no static # files defined. - url: /.* script: auto # [END django_app] Dockerfile: … -
Django Formet adding two rows instead of one with same input id
I'm trying to implement dynamic formset using django. It is working properly except that it adds two rows of input field with same ID when add button is clicked. ony one row is supposed to be added. models.py class StaffEmailCC(BaseModel): staff_email = models.ForeignKey("projects.StaffEmail",blank=True,null=True) cc_addresses=models.TextField(blank=True,null=True) class Meta: db_table = 'staffmailcc' verbose_name = _('staffmailcc') verbose_name_plural = _('staffmailcc') ordering = ('-date_added',) def __unicode__(self): return self.cc_addresses forms.py class StaffEmailCCForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StaffEmailCCForm, self).__init__(*args, **kwargs) class Meta: model = StaffEmailCC fields = ['cc_addresses'] widgets = { 'cc_addresses': autocomplete_light.ChoiceWidget('StaffAutocomplete'), } views.py def create_staff_mail(request): StaffEmailCCFormset = formset_factory(StaffEmailCCForm) staff_email_cc_formset = StaffEmailCCFormset(prefix='staff_email_cc_formset') form = StaffEmailForm() context = { "form": form, "staff_email_cc_formset":staff_email_cc_formset, "title": "Create Staff Mail", "sender_email":sender_email, } return render(request, 'projects/create_staff_mail.html', context) HTML <div class="content formElements add_item_container staff_email_cc_formset"> <table> <tr> <th>CC</th> </tr> {% for i in staff_email_cc_formset.forms %} <tr class="form_set_row"> <td> <span class="left cc_addresses"> {{i.cc_addresses}} </span> </td> </tr> {% endfor %} </table> {{ staff_email_cc_formset.management_form }} </div> js $('.staff_email_cc_formset table tr.form_set_row').formset({ prefix: '{{ staff_email_cc_formset.prefix }}', formCssClass: 'dynamic-formset1' }); Each time i click the add button, two rows are added, out of which only one row working correctly with autocomplete. any idea what i' doing wrong? -
Sending data with HttpClient post to Django backend
I have been trying to send data from my Angular front end to my Django backend and the data doesn't seem to be sending and I can't figure out why. This is my code on the frontend... const post_data = { email: form.value.email, password: form.value.password } const headers = new HttpHeaders({ 'Content-Type': 'application/json', }); const params = new HttpParams() const options = { headers, params, }; this.httpClient.post('https://my_website/signin/check/', post_data, options).subscribe( result => { console.log(result); }, error => { }, () => {} ) and in my Django backend, I print the request.POST to see if the data is sent correctly, and nothing shows up. This is the result: <QueryDict: {}> Any help would be nice. Thanks! -
Django inline formsets - only save the first formset
I am trying to dynamically add formsets, but after submitting it save only the first record and ignore the rest. I am new to django and don not know exactly if the issue in my django code or js code. models.py class PvSystem(models.Model): gm_name = models.CharField(max_length=60, blank=True, null=True) gm_email = models.CharField(max_length=60, blank=True, null=True) class Institution(models.Model): name = models.CharField(max_length=60, blank=True, null=True) tax_card = models.CharField(max_length=15, blank=True, null=True) pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE, blank=True, null=True) class OriginalInstitutions(models.Model): name = models.CharField(max_length=60, blank=True, null=True) tax_card = models.CharField(max_length=15, blank=True, null=True) pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE, blank=True, null=True) forms.py class InstitutionForm(forms.ModelForm): name = forms.ChoiceField(choices=[]) class Meta: model = Institution exclude = () def __init__(self, *args, **kwargs): super(InstitutionForm, self).__init__(*args, **kwargs) cleans = OriginalInstitutions.objects.values_list('name', flat=True) self.fields['name'] = forms.ChoiceField(choices = [(name, name) for name in cleans]) class PvSystemForm(forms.ModelForm): class Meta: model = PvSystem exclude = () InstitutionFormSet = inlineformset_factory(PvSystem, Institution, form=InstitutionForm, extra=1) views.py class PVSystemList(ListView): template_name = 'pvsystem/pvsystem_list.html' model = PvSystem class PVSystemDelete(DeleteView): template_name = 'pvsystem/pvsystem_confirm_delete.html' model = PvSystem success_url = reverse_lazy('pvsystem-list') class PVSystemCreate(CreateView): template_name = 'pvsystem/pvsystem_form.html' form_class = PvSystemForm success_url = '/' class PVSystemInstitutionCreate(CreateView): template_name = 'pvsystem/pvsystem_form.html' fields = ['gm_name','gm_email'] model = PvSystem success_url = reverse_lazy('pvsystem-list') def get_context_data(self, **kwargs): data = super(PVSystemInstitutionCreate, self).get_context_data(**kwargs) if self.request.POST: data['institute'] = InstitutionFormSet(self.request.POST) else: data['institute'] = … -
Remove Django template caching in production server
I have pushed latest changes on server and i can see all files have been updated. I have run collectstatic again to update static files and restart supervisor also to update files. But somehow templates are not showing the updated content as it is serving cached file. i do not have template caching in my settings.py files. How to flush templte caching in production server. I tried clearing django cache with cache.clear(), but nothing works. -
Use a different session engine in each app
I'm creating a Django project which involves the use of a REST framework (using DRF) in one app, and a web-based interface in another app. The REST framework uses the default session engine, which I believe is through database storage, in order to track user metrics more accurately. However, in the web-based interface, I want to use the cookies engine to provide simple authentication services. Is there any way I could use two different session engines in two different Django apps, under one project? -
How to pass object from select control to another view in django
I'm populating a select control in django template, but item options come from external web service which takes several time to query. There is any way to pass objects or "store" data (like jsf) in the view? I don't want request the web service to get the object instance. Actually options are populated with object id in the value option. I used the index of object in the array too, but I don't know what to do. <option value="{{ forloop.counter }}"> <option value="{{ item.id }}"> def get(self, request): client = ExternalServiceClient() products = client.all_products() context_data = {'product_list': products} return render(request, 'product-create.html', context=context_data) I expect query the external service only one time by form and pass the entire object to post method view. -
Django template not iterating over object
I am using Django to render a menu of items. I can get the content I want just fine, but when I return it to the django template, it's just a json string so it won't iterate correct. How do I tell django to return it as an iterable object? I ran across this article. Maybe I want to merge query sets? Python def index(request): if not request.user.is_authenticated: return redirect('/login', {'message': None}) try: menu_categories = MenuCategory.objects.all() menu = [] for cat in menu_categories: items = MenuCategoryItems.objects.filter(category_id=cat.id).all() menu.append({'category': cat, 'items': items}) context = {'menu': menu} # for cat in menu_categories: # items = menu_items.filter(category_id=cat.id) # category_items = [] # for item in items: # category_items.append({ # "name": item.name, # "price": float(item.price), # "id": item.id # }) # menu.append({"category": cat.name, "items": category_items}) except Exception: print('failure') return render(request, 'index.html', context) Template {% for category in menu %} <div>{{ category.name }}</div> {# {% for item in category.items %}#} {# <div>{{ item.name }} | {{ item.price }}</div>#} {# {% endfor %}#} {% endfor %} -
raise TypeError("%s() got an unexpected keyword argument '%s'"
I am trying send extra keyword arguments to django model save method. i am trying to override the save method. Even though the code looks fine but i got this error raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Student() got an unexpected keyword argument 'registration_no' class StudentManager(models.Manager): #check the availability of student def CheckRegistration(self, name, registration_no): print('inside CHECK REGISTRATION') if Student.objects.filter(name=name).exists(): students = Student.objects.filter(name=name) for student in students: student_id = student.id print(str(student_id)) registrations = Registration.objects.filter(student=student_id) for registration in registrations: print(str(registration)) if registration.registration_no==registration_no: raise ValueError('student with same registration number already exist') else: print('registration possible') return 1 class Student(models.Model): name = models.CharField(max_length=300) sex = models.CharField(choices=SEX_CHOICES,max_length=255, null=True) Category = models.CharField(max_length=100, null=True) objects = StudentManager() def __str__(self): return self.name def save(self, *args, **kwargs): if(kwargs): name = kwargs.get('name') registration_no = kwargs.get('registration_no') Student.objects.CheckRegistration(name, registration_no) super(Student, self).save(*args, **kwargs) -
How to convert Django model DateTimeField into local timezone and use Q object to filter
How to convert db datetime field into local time and construct Q object for retrieving dataset? settings.py LANGUAGE_CODE = 'en-us' USER_TIME_ZONE = ‘US/Pacific’ TIME_ZONE = 'UTC' USE_TZ = True models.py class Hello(models.Model): lucky_day = models.DateTimeField() One record in db (UTC format) 2019-02-03 03:02:45 filter.py # Client browser is Pacific time without time, date only. localtime_str = '2019-3-2' qset_filter = Q(lucky_day<to Pacific time from UTC>=localtime_str) -
Checkboxes not appearing in ModelForm
I created a Burger model that can have extras and toppings on the burger. So I created 2 additional classes called Topping and Extra that has choices available for those classes. However when i run the program the checkboxes for Topping and Extra is not appearing I tried having the topping and extras in teh burger class and got the checkboxes appearing but theis created an issue when submitting a form when the checkboxes were ticked. So I tried creating the nex classes and referencing them on a ManyToMany relationship via Burger class this is my model.py code: BURGER_CHOICES = (("AFBB", "Aurion's Famous Beef Burger"), ("AIPB", "Aurion's Infamous Pork Burger"), ("AULB", "Aurion's Undiscovered Lamb Burger"), ("POG", "Pureed Otter Giblets")) BUN_CHOICES = (("WHITE","White Bread"), ("RYE","Rye"), ("TPOODLE", "Teacup Poodles"), ("AFOSSIL","Ammonite Fossils")) TOPPING_CHOICES = (("CHEESE", "Cheese", ), ("LETTUCE", "Lettuce"), ("TOMATOE", "Tomatoe"), ("ONION", "Onion"), ("WSHAVE", "Wood Shavings")) SAUCES_CHOICES = (("OZTS", "Our Zesty Barbaque Sauce"), ("SEZBS", "Someone Elses Zesty Barbaque Sauce"), ("VS", "Varmint Squeezings")) EXTRAS_CHOICES = (("P", "Pinapple"), ("SG", "Soylent Green"), ("SB", "Soylent Blue"), ("MWS", "More Wood Shavings")) class Burger(models.Model): burger = models.CharField(max_length=50,choices=BURGER_CHOICES ) bun = models.CharField(max_length=50, choices=BUN_CHOICES) toppings = models.ManyToManyField('Topping') sauces = models.CharField(max_length=60, choices=SAUCES_CHOICES) extras = models.ManyToManyField('Extra') def __str__(self): return self.burger class Topping(models.Model): topping … -
Complex query using Django QuerySets
I am working on a personal project and I am trying to write a complex query that: Gets every device that belongs to a certain user Gets every sensor belonging to every one of the user's devices Gets the last recorded value and timestamp for each of the user's devices sensors. I am using Sqlite, and I managed to write the query as plain SQL, however, for the life of me I cannot figure out a way to do it in django. I looked at other questions, tried going through the documentation, but to no avail. My models: class Device: user = models.ForeignKey(User) name = models.CharField() ... class Unit: name = models.CharField() class SensorType: name = models.CharField() unit = models.ForeignKey(Unit) class Sensor: gpio_port = models.IntegerField() device = models.ForeignKey(Device) sensor_type = models.ForeignKey(SensorType) ... class SensorData: value = models.FloatField() timestamp = models.DateTimeField() sensor = models.ForeignKey(Sensor) ... class User: email... .... And here is the SQL query: SELECT acc.email, dev.name as device_name, stype.name as sensor_type, sen.gpio_port as sensor_port, sdata.value as sensor_latest_value, unit.name as sensor_units, sdata.latest as value_received_on FROM devices_device as dev INNER JOIN accounts_user as acc on dev.user_id = acc.id INNER JOIN devices_sensor as sen on sen.device_id = dev.id INNER JOIN devices_sensortype as … -
Signals not works? I want create profile instance when user was created
I read a part of the doc, and some articles, but my code is not working. OBS: i'm using custom User created with AbstractUser, but i not add extra fields Look this example profile.signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth import get_user_model from .models import Profile User = get_user_model() @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) now, look in the user creation: >>> from accounts.models import User >>> me = User.objects.create(username='myusr', email='me@email.com', password='me123456') >>> me <User: myusr> >>> me.save() >>> me.profile Traceback (most recent call last): File "<console>", line 1, in <module> File "/mnt/sda4/Development/coding/Projects/codesv3/env/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 415, in__get__ self.related.get_accessor_name() accounts.models.User.profile.RelatedObjectDoesNotExist: User has no profile. i dont know what's wrong. Also because I have not used it before and i not know about SQL triggers