Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending webRTC video stream to server with django channels
I am trying to create a face detection web application written in django. The app works this way. The user navigates to the url The camera starts on the client machine Each frame is then sent to the server for face detection Processed frame is then displayed on the web page I understood I could not use opencv VideoCapture because, it only works on the server side. When I read online people asked me to use javascript and specifically webRTC to start live stream on the client side. So I found this tutorial which explains how to start webcam on the client machine with javascript. Now my question is how to send each frame from javascript on the client machine to opencv python on the server side? All this should happen in real time. So I cannot save the live video and then run the python code on the saved video. Some sites asked me to use AJAX to send data to the server side but I am not sure how to target each frame that is to be sent in the javascript code. This is my code so far CLIENT SIDE CAMERA ACCESS WITH webRTC <!DOCTYPE html> <html> <head> … -
mongoengine: invalid dictionary key name - keys may not contain . or $
I am trying to store a report using a Django model connected with MongoDB. models.py class Report(me.EmbeddedDocument): report = me.DictField() class ReportDocument(me.Document): report = me.EmbeddedDocumentField('Report') storing json def store_report(report): # report is json given in link above. rd = ReportDocument(report={"report": report}) rd.save() I am getting following error on rd.save() mongoengine.errors.ValidationError: ValidationError (ReportDocument:None) (report.Invalid dictionary key name - keys may not contain "." or "$" characters: ['report']) -
How to user VueJS variable in Django if else tag
I want to use VueJS variable in Django {% if %} tag. My vue have delimiters: ['${', '}']. Exactly what I want to do is: {% if django.variable == vue.variable %} ... {% endif %} How to do this? Thanks. -
how use annotation Instead loop on filter
i use a table Bid in this table have multi fields and a field named user other hand have a Dealer table that save users in Dealer_serializer i have a bids_count serializer Method Field that return each user count in Bid table i want use annotate instead of loop over filter! to get each user how many in Bid Table. if my idea not true explain me what exactly doing annotation? -
How to Pass Custom Values like Username or E-mail into SurveyMonkey
Working on Integrating a SurveyMonkey Survey into a website. How do I pass Username or Email of a Logged in User to the Survey? I am using an Embedded Survey. Any Documentation Links would be welcome. Also, Can I get real-time Response from SurveyMonkey to get the results after a user has finished the taking survey? I have a Paid Plan. Using Django to build the website. -
Programmaitically finding the data in django python django rest framework
I have 3 tables PC(ID, PcNAME, Brand), CellPhoness(ID, CellPhoneName, Brand), Printers(ID, PrinterName, Brand). there is no relationship between the 3 tables. I would like to run query where in the user can input the search string and the program would search the 3 models for where the data exists and return the same with the Id, name and brand in the form of a Json response. -
Django create session which does not destroy after logout
In my django project I want a session which only destroys after a certain time, for that I set the expire time but session is also destroying after logout. Basically what I want to a session which is not effected by any login/logout activity. I search it for but not found any solution, anyone help me. -
Problem linking custom javascript file in Django Admin Panel
I want to customize the admin page for one of my models (create/update view) and I linked the custom javascript file in model admin as follows. class ScheduleDefAdmin(admin.ModelAdmin): class Media: js = ('js/admin/scheduledef.js',) I updated the settings.py file to point my static file dir. STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) My static directory structure as follows. However I get a 404 (not found error) for the above javascript file when I visit the create/update views in Admin panel. See the console error below. -
Django form is not submitting
I am trying to save a modelform which has following fields class DiaryText(models.Model): DiaryUser=models.CharField(max_length=30,unique=False) DateCreated=models.DateTimeField(default=timezone.now) DiaryBody=models.TextField(max_length=10000) DiaryHeading=models.CharField(max_length=50,unique=False,null=True) the corresponding modelform is :- class MakeADiaryForm(forms.ModelForm): class Meta: model=DiaryText fields={'DiaryHeading','DiaryBody'} widgets={ 'DiaryHeading':forms.TextInput(attrs={'placeholder':'Enter Title','class':'Headline'}), 'DiaryBody':forms.Textarea(attrs={'placeholder':'Start Writing','class':'BodyDiary'}), } Corresponding View function is as follows:- def NewEntryView(request,slug): UserPresent=get_object_or_404(DiaryUser,Username=slug) if request.method=='POST': form=MakeADiaryForm(request.POST) if form.is_valid(): BlogEntry=form.save(commit=False) BlogEntry.DiaryUser=slug BlogEntry.save() return redirect('Display',**{'slug':BlogEntry.DiaryUer}) else: form=MakeADiaryForm() return render(request,'Mobile/AddNewEntry.html',{'form':form,'slug':slug}) But the form is not saving the entered value and keeps on redirecting to same page. Display here is the name of another view while slug is the username. can i also use a better keyword in place of slug like username. if yes, please specify how to -
Django: capture JS value to use in view
So, I've a template that generates a token value using a js library and some js: So when user clicks on this button, a form is displayed and after user submits it's data a token is created. html: <button id="buyButton">Pagar</button> I need to capture this token and send it to a function in my view to do some processing using this variable. js: <script> $('#buyButton').on('click', function (e) { // Abre el formulario con la configuración en Culqi.settings Culqi.open(); e.preventDefault(); }); </script> This Js correctly generates the token, and alerts it: <script> function culqi() { if (Culqi.token) { // ¡Objeto Token creado exitosamente! var token = Culqi.token.id; alert('Se ha creado un token:' + token); } else { // ¡Hubo algún problema! // Mostramos JSON de objeto error en consola console.log(Culqi.error); alert(Culqi.error.user_message); } }; </script> Now, I would have to send it to this function to execture the function: charge = culqipy.Charge.create(dir_charge) def main(): dir_charge = {'amount': 1000, 'capture': True, 'currency_code': 'PEN', 'description': 'Venta de prueba', 'email': 'wmuro@me.com', 'installments': 0, 'metadata': {'test': '1234'}, 'source_id': token['id']} charge = culqipy.Charge.create(dir_charge) -
How to handle multiple forms on one page in Django?
First time posting here and I've searched but can't find anything that has shined light on my situation. I have a page with 5 individual forms consisting of one input field. Each form correlates to a single product, and the input field refers to a price (value) of the product. The idea is to be able to type a number into the input field, click submit, and have that value stored along with every other value related to that particular product. Here is an image of the actual form: form Currently I have a Price object with three attributes: Value (number typed into input box) Title (name of the product) Date Submitted One way I have considered doing this is making a new object for each product and storing all the price values within it, but this seems inefficient and difficult to scale (eventually I would like to be able to add new products from an admin page, and add a LOT of products). Here is my models.py: from django.conf import settings from django.db import models from django.utils import timezone from django import forms # Create your models here. class Price(models.Model): value = models.IntegerField() title = models.CharField(max_length=200, default='product_name') submitted_date = … -
Foreign Key Relation Problem in Django Rest Framework API
I have the following models: class Users(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) username = models.CharField(max_length=50, null=True, blank=True) home_page = models.CharField(max_length=100, null=True, blank=True) user_email = models.EmailField(max_length=70, unique=True) user_password = models.CharField(max_length=50) mobile_number = models.CharField(max_length=20, unique=True) is_active = models.BooleanField(default=True) class Posts(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id = models.ForeignKey(Users, on_delete=models.CASCADE) uri = models.CharField(max_length=45) title = models.CharField(max_length = 20) summary = models.CharField(max_length=30) post_body = models.CharField(max_length=3000) post_datetime = models.DateTimeField(auto_now_add=True) votes = models.IntegerField() location = models.CharField(max_length=200) and I have the following Serializers: class UsersSerializer(serializers.ModelSerializer): class Meta: model = models.Users fields = ('user_id', 'firstname', 'lastname', 'user_email', 'username', 'home_page', 'user_password', 'mobile_number', 'is_active') class PostsSerializer(serializers.ModelSerializer): class Meta: model = models.Posts fields = ('post_id', 'user_id', 'uri', 'location', 'title', 'summary', 'post_body', 'post_datetime', 'votes') I have an API running using Django Rest Framework. However, when I try to add a new Post to a specific user_id, i get the following error from the API view: Cannot assign "'528c2d9e-da2e-4c3d-9a92-eafb98e5d06e'": "Posts.user_id" must be a "Users" instance. Is it a problem with my Serializers implementation? user_id is already stated as a foreign key in Posts Model. django-version: 2.1.3 DRS-version: 3.9.0 -
How to create a page that can be unlocked with a code
So basically I want to create a page that is locked, and the only way to unlock it is by entering a specific code. So far the only thing that I know is that there will be a database of codes. Whatever input the user enters will be compared with the codes in the database, and if there is a match the user will be granted access. The idea is to allow users into a payment gateway only if they have specific code. I have no clue how to go on about it. Would I be able to use some prebuilt functions in Django? If anyone can point me in the right direction that would be nice. -
Django login and register modal
I have succeeded in creating django login and register modal but at the same time there's still the login page which looks like that login page So my question is how to disable the user from entering this url ? -
How can you add a many to many field in Wagtail Admin?
I am trying to set make a footer for a Wagtail site that is included on every page, but I want to include a list of links (phone, email, social media). If I try the code below without the panel = [...] I can see it sort of works, but I am unable to add any items: from wagtail.contrib.settings.models import BaseSetting, register_setting from django import forms class ContactInfo(models.Model): CONTACT_CHOICES = ( ('fas fa-phone', 'Phone'), ('fas fa-envelope', 'Email'), ('fab fa-facebook-f', 'Facebook'), ('fa-instagram', 'Instagram'), ('fab fa-linkedin', 'LinkedIn'), ('fab fa-twitter', 'Twitter'), ('fab fa-pinterest', 'Pinterest'), ('fab fa-github', 'GitHub'), ('fab fa-gitlab', 'GitLab'), ) contact_type = models.CharField(choices=CONTACT_CHOICES, max_length=50) contact_info = models.CharField(max_length=50) info_prefix = models.CharField(max_length=10, editable=False) def save(self, *args, **kwargs): if self.contact_type == 'Phone': self.info_prefix = 'tel:' elif self.contact_type == 'Email': self.info_prefix = 'mailto:' else: self.info_prefix = '' @register_setting class Contact(BaseSetting): contact = models.ManyToManyField(ContactInfo) panels = [ FieldPanel('contact', widget=forms.CheckboxSelectMultiple) ] Is there a to add items to the M2M field? Is there a way to make lists of items in the Wagtail settings? Is there an easier way to make a footer that automatically is rendered on every page? -
Passing Django url to redirect after ajax in JQuery
I am using an ajax to check a status and if the status is correct, I want to direct to another page. How can I pass the Django url in JQuery? urls.py, path('confirm/', views.confirm, name='confirm'), In JQuery, $.ajax({ url: url, data: data, type: 'POST', }).done(function(msg) { if (msg == 'confirm') { window.location.replace("/confirm/"); <-- } }).fail(function(err) { alert(err) }); It doesn't work. How's missing here? -
Django - Perform a complex operation in .update()
I have the following model: class Address(models.Model): full_address = models.CharField(max_length=100) Some full_address ends with "Region". Examples: 123 Main Street, Markham, York Region 1 Bloor Street, Mississauga, Peel Region I want to remove "Region" from any full_address field that ends with it Here is one possible solution, but it is slow, since you need to go over each Address one by one: for i in Address.objects.filter(full_address__endswith=' Region'): i.full_address = i.full_address[:-7] i.save() Is there some way to achieve the above function using Address.objects.update()? -
Creating a form out of relation based key, values in django
I have a django based application where I want to create a form out of key, value pairs from a model. The `Child' model consists of the following rows of data: (<parent 1>, 'component 1', 'dummy content 1'), (<parent 1>, 'component 2', 'dummy content 2'), Here is are my models: # models.py class Parent(models.Model): class Meta: verbose_name = 'Parent' db_table = "parent" title = models.CharField(max_length=28) def __str__(self): return self.title class Child(models.Model): class Meta: verbose_name = 'Child' db_table = "child" parent = models.ForeignKey(Parent, on_delete=models.CASCADE) key = models.CharField(max_length=20) value = models.TextField() def __str__(self): return self.parent Following is the direct model to form mapping I am currently using for my other forms to keep it straight forward and simple # forms.py class MyForm(ModelForm): class Meta: model = Child fields = () # fields go here Then I pass this form to my view. The view page_view takes pk of the parent, gets the parent and passes it to the form. The form is then passed on to the template parent_view.html via the view. # views.py @login_required def page_view(request, parent_pk): parent = get_object_or_404(Parent, pk=pk) my_form = MyForm(request.POST, instance=parent) return render(request, 'parent_view.html', { 'parent': parent, 'my_form': my_form, }) In the template I render the form … -
Get user in the form
I have a model class Dogadjaj(models.Model): TIME_ZONE = 'Europe/Belgrade' sportovi = (('Nije naveden omiljeni sport', "Nije naveden omiljeni sport"), ("Fudbal", "Fudbal"), ("Kosarka", "Kosarka"), ("Tenis", "Tenis"), ("Odbojka", "Odbojka")) novac = (("Ima novcane nagrade", "Ima novcane nagrade"), ("Nema novcane nagrade", "Nema novcane nagrade")) gradovi = (("Nije naveden grad", "Nije naveden grad"), ("Beograd", "Beograd"), ("Cacak", "Cacak"), ("Uzice", "Uzice"), ("Ivanjica", "Ivanjica"), ("Novi sad", "Novi sad"), ("Nis", "Nis"), ("Pozega", "Pozega"), ("Lucani", "Lucani")) user = models.OneToOneField(User, on_delete=models.CASCADE) datum_kreiranja = models.DateField(default=timezone.now) naziv = models.CharField(max_length=150, blank=False, null=False) datum_odrzavanja = models.DateField() opis = models.TextField(max_length=1000, blank=False, null=False) potrebno_igraca = models.PositiveIntegerField(validators=[MinValueValidator(1)]) novcana_nagrada = models.CharField(max_length=100, choices=novac, default="Nema novcane nagrade") novac_za_prijavu = models.PositiveIntegerField() grad = models.CharField(max_length=254, default="Nije naveden grad", choices=gradovi) mesto = models.CharField(max_length=150, blank=False) odrzano = models.BooleanField(default=False) sport = models.CharField(max_length=254, choices=sportovi, blank=False, null=False, default='Fudbal') Here I have fields that have to be filled and the user field that is connected to the users table In my forms class DogadjajForm(forms.ModelForm): class Meta: model = Dogadjaj fields = ['naziv', 'datum_odrzavanja', 'opis', 'potrebno_igraca', 'novcana_nagrada', 'novac_za_prijavu', 'grad', 'mesto', 'sport', 'user'] widgets = { 'grad': forms.Select(choices=Dogadjaj.gradovi, attrs={'class': 'form-control'}), 'sport': forms.Select(choices=Dogadjaj.sportovi, attrs={'class': 'form-control'}), 'novcana_nagrada': forms.Select(choices=Dogadjaj.novac, attrs={'class': 'form-control'}), 'datum_odrzavanja': TextInput(attrs={'class': 'form-control', 'type': 'date'}), 'mesto': TextInput(attrs={'class': 'form-control', 'placeholder': "Mesto na kome se odrzava dogadjaj"}), 'naziv': TextInput(attrs={'class': 'form-control', 'placeholder': "Naziv dogadjaja"}), 'opis': … -
Django models - auto-increment id for elements of a child table for each parent reference
I'm trying structure the database of an app in Django that will have companies and projects. Each company can have many projects and each project will belong to only one company. class Company(models.Model): name = models.CharField(max_length=20) class Project(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) project_id = models.PositiveIntegerField() name = models.CharField(max_length=20) I'd like to have a field or a property in the model Project that acts like an auto-increment integer for the projects within a Company. The behaviour should be like the following: c1 = Company(name="C1") c2 = Company(name="C2") px = Project(company=c1, name="X") py = Project(company=c2, name="Y") pz = Project(company=c1, name="Z") px.project_id 1 py.project_id 1 pz.project_id 2 What would be the correct approach? -
error in migrations/0001_initial.py when upgrading to DJango 2: migrations/0001_initial.py
I've recently upgraded from Django 1.11 to 2.1 This went fine in two different test envorinments, but when I tried to apply the changes to my productions environment, I get an error when I try to makemigrations: $ ./src/manage.py makemigrations Traceback (most recent call last): File "./src/manage.py", line 11, in <module> execute_from_command_line(sys.argv) ... File "/home/90158/hackerspace/src/quest_manager/migrations/0001_initial.py", line 69, in Migration ('quest', models.ForeignKey(to='quest_manager.Quest')), TypeError: __init__() missing 1 required positional argument: 'on_delete' Of course, many of the changes I needed to make were to add on_delete to my ForeignKeys, but none of my test environments gave this migration error! -
Wagtail Form Builder: Make the Custom Form Submission a Foreign Key in Another Model and Auto Update it on Submit
I'm creating an app in wagtail using the form builder. I've added a custom form submission model as outlined in the documentation. I'm making the custom form submission model a foreign key in another model (here just called BridgeModel), that will also store additional foreign keys. When the form submits, I'd like the bridge model to automatically update (Create new rows) as well. My biggest challenge is getting access to the current primary key of the submission model so that I can save that to the bridge model. A proof of concept is below class FormBuilderField(AbstractFormField): form_builder_page = ParentalKey('FormBuilderPage', on_delete=models.CASCADE, related_name='form_fields') class FormBuilderPage(AbstractEmailForm): content_panels = AbstractEmailForm.content_panels + [ FormSubmissionsPanel(), InlinePanel('form_fields', label="Form fields"), ] def get_submission_class(self): return FormBuilderSubmission def process_form_submission(self, form): self.get_submission_class().objects.create(form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),page=self) class FormBuilderSubmission(AbstractFormSubmission): def get_data(self): form_data = json.loads(self.form_data) form_data.update({ 'submit_time': self.submit_time, }) #Tried this, doesn't work. submission_id = FormBuilderSubmission.objects.get(id=self.id) update_bridge = BridgeModel.objects.create(form_builder=submission_id) process_update = update_bridge.save() return form_data class BridgeModel(models.Model): form_builder = models.ForeignKey('FormBuilderSubmission', default=1, on_delete=models.CASCADE) #other foreign keys here -
Python Django DTO
I'm using Django REST Framework and want to send DTO(Data Transfer Object) to request. In Java we can set up a class with needed fields and type for each field. Can we do the same thing in Python? If we create a model, we can use something like that username = models.CharField(max_length=255), but if I create just an object(not real DB model), I don't have possibility to do that. Is it correct? So, please suggest, how to create correct DTO model(with right fields) and where should I store it? Can I use just simple solution like that: class UserDTO(object): def __init__(self, name): self.name = name Is this way correct? Thanks -
Django - How to display parent model property in template
This is a pretty generic issue I'm having and I have so far not been able to debug this any further after reading the Django documentation nor any of the other somewhat related responses on this site. My issue is this, and I'll post the code so people can see what I'm trying to accomplish as well. I have the following models class Tournament(models.Model): name = models.CharField(max_length=128, null=True) description = models.CharField(max_length=2000, null=True) number_players = models.IntegerField(default=-1) teams_per_game = models.IntegerField(default=-1) template = models.IntegerField(default=-1) created_by = models.ForeignKey('Player') created_date = models.DateTimeField(auto_now=True) number_rounds = models.IntegerField(default=-1) is_finished = models.BooleanField(default=False) has_started = models.BooleanField(default=False) players_per_team = models.IntegerField(default=1) private = models.BooleanField(default=False,db_index=True) start_option_when_full = models.BooleanField(default=True) host_sets_tourney = models.BooleanField(default=False) max_players = models.IntegerField(default=-1) template_settings = models.TextField() @property def time_since_created(self): print("Here!") fmt = '%H:%M:%S' td = datetime.strptime(datetime.now(), fmt) - datetime.strptime(self.created_date, fmt) vars(td) print ("Hours: {}".format(td.hours)) print ("Minutes: {}".format(td.minutes)) print ("Seconds: {}".format(td.seconds)) if td.hours > 0: return td.hours + " hours ago" if td.minutes > 0: return td.minutes + " minutes ago" if td.seconds > 0: return td.seconds + " seconds ago" def __str__(self): return "Tournament: " + self.name class SwissTournament(Tournament): type = models.CharField(max_length=255, default="Swiss") max_rating = models.IntegerField(default=0) min_rating = models.IntegerField(default=0) best_record = models.CharField(max_length=10, null=True) max_teams = 128 min_teams = 16 When I do … -
Django/DRF: Calculating running balance using window function with non-unique field
I have a that query calculates a running balance based on the amount field of my Transaction and is sorted by created_time. This works great for getting an accurate running balance when date and created_time are the same day. However, date won't always match the created_time of the transaction. Is there any way that I can use date for this running balance calculation? Current Query: queryset = self.queryset.annotate(balance=Window(Sum('amount'), order_by=F('created_time').asc())).all().order_by('-created_time') Full usage: class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer def list(self, request, *args, **kwargs): queryset = self.queryset.annotate(balance=Window(Sum('amount'), order_by=F('created_time').asc())).all().order_by('-created_time') # noqa: E501 page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Model: class Transaction(models.Model): date = models.DateField() payee = models.CharField(max_length=256) category = models.CharField(max_length=256) amount = MoneyField(max_digits=19, decimal_places=2, default_currency='USD') memo = models.CharField(max_length=256) is_cleared = models.BooleanField() paid_or_deposited = models.BooleanField() created_time = models.DateTimeField(db_index=True, # maybe remove the index auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) Serializer: class TransactionSerializer(serializers.ModelSerializer): balance = serializers.DecimalField( decimal_places=2, max_digits=19, read_only=True) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Transaction fields = ('id', 'date', 'payee', 'category', 'amount', 'balance', 'created_time', 'modified_time', 'is_cleared', 'paid_or_deposited') If I try to use date in the Window function, the calculated balance is not …