Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Live Streaming for numerous devices
Currently the idea is too have a raspberry pi that has two USB cameras attached streaming video preferably at 1080p 60fps or as close to that as I can. Both cameras don't always have to stream at the same time but sometimes they both need streamed. From the PI I want to send that video off to a Django Rest Server that saves the video and then restreams it off to a mobile application that requested it. So a device is associated with an account thus only that account should be able to view their devices stream. How do I go about accomplishing this? Was looking into pygst but their weren't enough resources for me to understand it. Figured sockets would be the best way to associate different devices to different client requests. Trying to get this done for my Senior Design project and this is the biggest issue. -
console not showing print message on server, django and uwsgi with nginx
I am currently using django's back end to post another api which works correctly when I am developing locally. But when I push it to a staging cloud server which uses uwsgi with nginx that it is not working properly anymore. I am trying to use print from django to either save the messages into a file or somehow show it in terminal so I can know the post response to start debugging but I have no luck trying to find a way to log any print I have already did something like this in the settings LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/path/to/your/file.log', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } } it does work perfectly and show messages normally but how can I also print messages into the file too? Can someone give me an idea or advice? Thanks in advance -
How could I add or remove a form as a different type of user?
I have two user types: a teacher and a student. I wanted that a teacher could add or remove an upload form, from the course page. But a student could upload a file only once, and after form is submitted it won't show again. I managed to implement that after a student submits the file form it won't show anymore, but now I am a bit stuck. How do I allow a teacher user to add or remove the form from the course page for each particular course that he has ? For example show the form for course number 1 only and not other courses, and when he wants he can just remove it from that course as well. Here is what I did so far: def courses(request, slug): query = Course.objects.get(slug=slug) data = request.POST.copy() data['course'] = query.id form = StudentFileForm(data, request.FILES) if request.method == 'POST': if form.is_valid(): upload = form.save(commit=False) upload.user = request.user student = upload.user.student student.file_status = True student.save() upload.save() return HttpResponseRedirect(reverse('courses:confirmation')) else: form = StudentFileForm(initial={'course': query.id}) context = {'courses': Course.objects.filter(slug=slug), 'students': Student.objects.all(), 'students_data': StudentData.objects.all(), 'lectures': query.lectures.order_by('lecture_category'), 'form': form, 'uploads': StudentFileUpload.objects.all(), } return render(request, 'courses/courses.html', context) {% if user.is_student %} {% if user.student.file_status == False %} <form … -
Shorten a Python Django DB query
We have m2m relationship between E and U models: class E(models.Model): us = models.ManyToManyField('U', related_name='events', symmetrical=False) class U(models.Model): pass Now we want to remove all links for U with pk=2. I wrote this code: U.events.through.objects.filter(u=2).delete(). Can this code be shortened/simplified? -
How do i make djangoCMS urls to work with my django app urls?
I'm developing a django site and i have built all my templates and then decided to install djangoCMS to manage my content, so the problem is that my django url patterns don't seem to work with djangoCMS page generated paths and this is causing a serious problem with the placeholders in my template pages since they only show up on structure view when i navigate to a djangoCMS page generated path but when i access the same page with my own defined urls the placeholders are not visible in structure view of the page? what might be causing this problem? -
Migrating to django-guardian permissions with custom User class
I am trying to migrate my models to use Guardian permissions. At this point I have: class Data(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: permissions = ( ('view', 'View'), ('edit', 'Edit'), ('owner', 'Owner'), ) I created one migration that added the new permissions, and in a custom migration I am trying to assign the permissions like this: def assignDataPermissions(apps, schema_editor): Data = apps.get_model('api', 'Data') for data in Data.objects.all(): assign_perm('api.owner', data.user, data) class Migration(migrations.Migration): dependencies = [ ('api', '0169_auto_20180304_1619'), ] operations = [ migrations.RunPython(assignDataPermissions) ] This fails with guardian.exceptions.NotUserNorGroup: User/AnonymousUser or Group instance is required (got EmailUser object). Is there a better/proper way of migrating to Guardian? If not, how do I make it see my custom User class? -
How can I pass a variable from one page(view) to another on GET?
I need to pass on GET a variable from one page to another. On the next page, in the view/template I check the variable, and if exist I make some adjustments how the page is rendered. -
How to save to a remote server with Django
I'm fairly new to Python and Django. I've recently got a Django app working on localhost in Linux Mint 18.3 with a Postgresql database. I've uploaded the app to PythonAnywhere, but unfortunately it requires Java for some of the NLP features (Stanford POS). Is there a way to parse and process the data on a local system and save it to the remote Postgres DB and serving the data from the remote server? I've looked at some answers on here regarding SSH tunnelling, but I'm not sure this applies here? -
Wagtail: render a page programmatically in a Class Based View
I've got a Wagtail setting where a user can select a page to render, and if it is not set, it returns a listing page using ListView of recent posts. Here is the setting: @register_setting class PeregrineSettings(BaseSetting): """ Settings for the user to customize their Peregrine blog. """ landing_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, help_text='The page to display at the root. If blank, displays the latest posts.' ) The setting works. When I try to use it in the ListView, I'm attempting to pass the url_path to Wagtail's serve method, but it doesn't render the page view; I get a 404. Here's the code of the ListView: class PostsListView(ListView): """ Paginated view of blog posts. """ model = SitePost template_name = 'peregrine/site_post_list.html' context_object_name = 'posts' paginate_by = 10 ordering = ['-post_date'] def get(self, request, *args, **kwargs): peregrine_settings = PeregrineSettings.for_site(request.site) if peregrine_settings.landing_page is None: # Render list of recent posts response = super().get(request, *args, **kwargs) return response else: # Render landing page serve(request, peregrine_settings.landing_page.url_path) It feels like I'm missing a way to just pass the Page instance stored in peregrine_settings.landing_page to a method to render. Can anyone shed some light on the internals at work here? Thank you! -
Test Application Keys for Twilio Authy Client
I am using Python Client for Twilio Authy API (https://github.com/authy/authy-python). To create a new Connection Instance the following is used: from authy.api import AuthyApiClient authy_api = AuthyApiClient('#your_api_key') For testing purposes, are test Application Keys available that do not necessarily send the OTP to phone but gives the appropriate responses? Where or how do I get this test Application Key? -
Django Iterating over Many to Many Objects
My main problem is that my code never goes into the for loop though within the debugger I can see that hardware exists. The for loop gets just skipped and I can´t figure out why this is the case. Models: class Hardware(models.Model): name = models.CharField(max_length=30) description = models.TextField() class Bundle(models.Model): name = models.CharField(max_length=30) description = models.TextField() devices = models.ManyToManyField(Hardware) class BundleForm(ModelForm): class Meta: model = Bundle fields = ('name', 'description', 'devices') labels = { 'name': _('Bundlename'), 'description': _('Beschreibung des Bundle'), 'devices': _('Hardware im Bundle') } Views: elif request.method == 'POST' and 'newbundle' in request.POST: form = BundleForm(request.POST) if form.is_valid(): bundle = form.save(commit=False) bundle.save() for hardware in bundle.devices.all(): print(hardware) messages.success(request, 'Erfolg! Die Daten wurden erfolgreich gespeichert.') return redirect('/knowledgeeditor/bundle/', {'messages': messages}) -
How to fix Django "NoReverseMatch" Error
I have built a simple blog app with Django and I have had some issue with NoReverseMatch. here are my problem screenshot: 1. https://prnt.sc/imqx70 2. https://prnt.sc/imqwpt Here is my code on Github: https://github.com/nafiulhasanbd/Django_blog_app Can anyone please explain. Thank you Best Regards Nafiul Hasan -
Multiline Charfield Django
How can I make a multi-line CharField in a model form in Django? I don't want to use Textarea, as I want the input to be with limited length. The question is about the field 'description' This is my model: class Resource(models.Model): type = models.CharField(max_length=50) name = models.CharField(max_length=150) description = models.CharField(max_length=250, blank=True) creationDate = models.DateTimeField(default=datetime.now, blank=True) And this is my form: class AddNewResourceForm(forms.ModelForm): class Meta: model = Resource fields = ("name","type","description") def __init__(self, *args, **kwargs): super(AddNewResourceForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'new-res-name', 'placeholder' : 'max 150 characters'}) self.fields['type'].widget.attrs.update({'class' : 'new-res-type', 'placeholder' : 'max 50 characters'}) self.fields['description'].widget.attrs.update({'class' : 'new-res- description', 'placeholder' : 'max 250 characters'}) -
How does one build an spa with webpack when deploying Docker container to Heroku
I'm developing an Aurelia Single Page App that will talk to a REST api built with Django Rest Framework. Without containers, I would have two buildpacks, one for Node that runs a script in the package.json file and another for Python that builds the Django app. If I push a container image, then what mechanism replaces the node buildpack that calls the script in package.json to trigger webpack to create the asset bundles? -
How to separate a Django app in order to make part of its GitHub repo private
I have hired a contractor to do some web development work on my app and would like to only give them access to certain parts of my GitHub repo (I would like to keep the Python utility files private). The stack is Python/Django/GitHub/Heroku. Based on other SO posts, it sounds like the solution is to create two GitHub repositories, one which is public and the other which is private, and then manage these two repos via Git. The problem is that if I move the Python utility files to another repo, outside of my Django root project, then I'm not sure how to import those files into my Django project. I went down the route of moving the Python files to an external location and then trying to import them via sys.path.append('/mypath') in the Django settings file and alternately tried packaging my python files into a separate module and then installing it via pip but have run into issues with both of these methods. Is there a suggested approach for how to best separate these two parts of the code base, such that the Django project is able to import the Python files? -
How to get user details using JWT token
I'm using angular 5 front end and django as back end. I use JWT token to communicate between django to angular. How can I get logged user details in backend using token. EG: class PostSerializer(ModelSerializer): class Meta: model = PostDetail fields = [ 'title', 'upvote', ] Here upvote is a many to many field contain all voted user list. I want to add one more field "user_vote_status" to check the vote status of logged in user. How can I figure out this issue, please help me. -
how to call some logic in my views after rendering template in django
I am using form.py and the user is typing some Email-id, let us say I want to send an email to that particular email and write all that email into google sheet using gspread, I am able to do this in my views.py, but the problem is it's taking a lot of time to write which slow down the rendering process. Is there any other way I can use my logic after rendering the template. -
Django how to update object with multiple fields which is already saved in Database
I'm trying to create a logic in Django which checks if User had already provided certain information. If not then it creates new object and save in the databse. And information was already there then it updates the same object with the new information. I'm making some mistake because it is able to create a new object but not updating it. try: # Check if user already have data available data_created_or_not = UserUsageInfo.objects.get(user_id=request.user.id).data_available_or_not except Exception: # If not available than, make it false data_created_or_not = False if not data_created_or_not: # If its False then create new object UserUsageInfo.objects.create(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) else: # If already there then update it UserUsageInfo.objects.update(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) -
ImproperlyConfigured: Field name `address` is not valid for model `User`
I am trying to overide Djoser User registration serializer to add a custom field to user model. Following is my models.py from django.db import models class User(models.Model): email = models.CharField(max_length=100, blank=False) first_name = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=30, blank=True) password = models.CharField(max_length=100, blank=False) and my serializers.py looks like follwing: from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'first_name', 'address', 'password') and this is my view.py from User.models import User from User.serializers import UserRegistrationSerializer from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserRegistrationSerializer I have configured Djoser configurations in setting.py in following way DJOSER = { 'SERIALIZERS': { 'user_create': 'User.serializers.UserRegistrationSerializer', }, } I am getting following error when I try to create a new user I ran makemigration and migrate but error is still there. any help is appreciated :) -
CSV to sqlite import
Trying to import an existing csv into a table that will have blank elements but they're already allowed to have nulls and blanks. It seems no matter which approach I take I get binding errors or a syntax error on the %s portion of the insert. The Csv has four elements and does not include column headings. import csv, sqlite3,sys con = sqlite3.connect('db.sqlite3') cur = con.cursor() query="""INSERT INTO adm_Appointment(sch_time, operation_id, surgeon, pat_name) VALUES(%s,%s,%s,%s)""" with open('dailypatientlist.csv','r') as csvfile: reader = csv.reader(csvfile, delimiter=',') next(reader) for line in reader: elements="line[0],line[1],line[2],line[3]" cur.execute(query,(elements,)) con.commit() con.close() -
Why pip freeze >requirements.txt return Permission denied
When I worked in a virtual environment, I installed my packages django-2.0 there. Yet it is installed globally: sudo virtualenv -p /usr/bin/python3.5 ~/.virtualenv/venv source ~/.virtualenv/venv/bin/activate (venv) $ pip install django==2.0 And I had django-1.11 in my global environment before. However django-1.11 is also hoping to be installed into the other virtual environment, but it was also installed globally. I uninstall this package, and try to install it into my virtual environ again. but it seems like not work at all. All package installed newly were in global env. Now i want to use pip freeze >requirements.txt to get requirements file,but it return : (venv) $ pip3 freeze >requirements.txt bash: requirements.txt: Permission denied (venv) $ sudo pip3 freeze >requirements.txt bash: requirements.txt: Permission denied I thought maybe it was because that i install these package globally?I don't know. How can i install package into my virtual environment correctly, and get requirement file:( -
Django update or delete own made data only
Trying to add permissions on a django form. User created own instances. That data only updatable/deletable if the creator trying to do action. I'm using generic updateview. Thanks in advance -
django multi form and file field
I am currently using several differents forms on a single view. I am able to fill my forms but when i submit one of them, it seems that my form is unvalid. I displayed the request.POST (it contains all my informations) and my form (it is empty but i don't understand why) Could you explain me how to correct it? Could it be linked to my models? (I am using bootstrap 3 through django) my view : def view_addfiles(request): try: print(request.POST) except: {} if request.method == 'POST' and 'search' in request.POST: print("recherche") recherche=searchbar(request.POST, prefix='search') if recherche.is_valid(): print("recherche") else : recherche=searchbar(prefix='search') if request.method == 'POST' and 'film' in request.POST: print("film") addfilm=Addfilms(request.POST,request.FILES, prefix='film') print(addfilm) if addfilm.is_valid(): print("film") return redirect(view_accueil, inscription=3) else : print("dfsd") addfilm=Addfilms(prefix='film') if request.method == 'POST' and 'serie' in request.POST: print("serie") addserie=Addseries(request.POST,request.FILES, prefix='serie') if addserie.is_valid(): print("serie") return redirect(view_accueil, inscription=3) else : addserie=Addseries(prefix='serie') return render(request, 'menuAjout.html',locals()) my html : <form action="{% url "add_files" %}" method="post"> {% csrf_token %} {{ recherche.as_p }} <input type="submit" id="validation" name="search"/> </form> <div id="films"> {% load bootstrap3 %} {% bootstrap_css %} <form action="{% url "add_files" %}" method="post"> {% csrf_token %} {% bootstrap_form addfilm %} {% buttons %} <button type="submit" class="btn btn-primary" id="submitbutton" name="film" value="submit"> {% bootstrap_icon "star" … -
What should I use to create a drag and drop form that allows users upload image and then display it?
I use Django and want to create a form that get an image, upload it to the server and then display it on the same page. This should work without user authentication. Appreciate any directions. -
Website in Angular, django and Firebase
Is it possible to create a web application which use Angular as view, django as Controller and firebase Nosql database as modal. If it is possible what are gonna be the benefits and drawbacks of this approach.