Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Permission Error: [WinError 32] The process cannot access the file because it is being used by another process Django
I am dealing with pdf on my web page using PyMuPdf library(other pdf reading libraries are not working properly for me) ,the user is uploading a pdf file which is been saved in FileSystemStorage because I am unable to read it without saving it(would appreciate if you could suggest a way to do it without saving the file) now after reading the pdf I am using the command os.remove({}.fromat(pdf_path)) to delete it from file system which causes the above mentioned error below is my code def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() fs.save(uploaded_file.name,uploaded_file) pdf_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name) doc = fitz.open("{}".format(pdf_path)) #doing some thing with the content of pdf doc.close() os.remove(pdf_path) return render(request,'upload.html',context) -
how to assign foreign key for two different types of classes
I have 3 classes: class Student(models.Model): name=models.CharField(max_length=200) class Background(models.Model): stud_name=models.CharField(max_length=200) surname=models.CharField(max_length=200) address=models.CharField(max_length=200) class Meta: managed=False db_table='background' class Class101(models.Model): stud_name=models.CharField(max_length=200) math=models.DecimalField(max_length=200) english=models.DecimalField(max_length=200) class Meta: managed=False db_table='class101' Class Student is input model whereas class Background and Class101 are static data taken from DB. When user writes down name the code goes and matches naem to stud_name in class Background and Class101 . In this case how to assign Foreign key ? i am confused here. Any helped is appreciated. Thanks in advance. -
Class Property method not read/called - Django Rest Framework
I am trying to add a class property method to the Game model, however it is not appearing on the frontend when I call game.owner_username. Model: class Game(models.Model): location = models.CharField(max_length=100) players = models.ManyToManyField(User) kickoff_time = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) max_player_count = models.IntegerField(null=True) goal_type = models.CharField(max_length=100) notes = models.CharField(max_length=300, null=True) status = models.CharField(max_length=6) owner = models.ForeignKey( User, related_name="games", on_delete=models.CASCADE, null=True) @property def owner_username(self): return self.owner.username -
Retrieving objects
I made a GET function that will retrieve posts and will make it available only to a particular user as well as its friends list. To make this work partially, I developed a raw query to get my desired output, and somehow it works fine for me. Now, I am trying to learn making queries in django without implementing raw query, so I am trying to maximize the Django ORM and not use raw query but I'm kinda stucked and kept wondering how I am gonna be able to make my queryset works without using raw query. this is my raw query: FeedMedia.objects.raw("""SELECT DISTINCT feed_media.* FROM feed_media INNER JOIN feed ON feed_media.feed_id = feed.id INNER JOIN media ON feed_media.media_id = media.id INNER JOIN profile ON profile.id = feed.profile_id INNER JOIN gosam_friend_profile ON gosam_friend_profile.profile_id = feed.profile_id INNER JOIN friendship_friend ON friendship_friend.id = gosam_friend_profile.gosam_friend_id WHERE friendship_friend.to_user_id = %(friend)s OR gosam_friend_profile.profile_id = %(profile)s""", params={'friend': request.user.pk, 'profile': profile.pk}) -
How to deal with Dynamic form in addition of common form in Django
I am new to Django. I am very confused to store the dynamic form with the common form I have created a model like class AudioDetail(models.Model): filename = models.ForeignKey(AudioData, default=1, on_delete=models.CASCADE) audio_type = models.CharField(max_length=20, null=True, choices=SPEECH_CHOICES) start_time = models.CharField(max_length=20, null=True) end_time = models.CharField(max_length=20, null=True) label = models.CharField(max_length=20, null=True) sentence = models.TextField(null=True, blank=True) class AdditionalFields(models.Model): word = models.CharField(max_length=20, null= True) transcript= models.CharField(max_length=20, null= True) language = models.CharField(max_length=20, null= True, choices=LANG_CHOICES) These 3 fields should be dynamic. if the 'sentence' field in 'AudioDetail' model has the value 'How are you?', then in 'AdditionalFields' it should be saved in 3 rows('How', 'are', and 'you') with the same 'AudioDetail' information in 3 rows. -
Django rest framework create data after check a condition
#View @permission_classes([IsAuthenticated]) class PageUserProjectView(viewsets.ModelViewSet): queryset = PageUserProject.objects.all() serializer_class = PageUserSerializer() def create(self, request): result = PageUserProject.objects.values('id').filter(page=request.data['page'], user=request.data['user'], project=request.data['project']) if len(result)>0: return Response("Selected page access is already given to selected user under this project", status=status.HTTP_200_OK) else: if PageUserSerializer.is_valid(request.data): return PageUserSerializer.create(request.data) #Model class PageUserProject(models.Model): allow_deny_enum = (('Allow', 'Allow'), ('Deny', 'Deny')) page = models.ForeignKey(Page, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) create_date = models.DateTimeField(default=datetime.now) access_status = models.CharField(max_length=20, choices=allow_deny_enum, default='Allow') I just need to add new data if the if condition in views is not satisfied. How to do that? Also with a response of JSON format like, { "id":5, "access_status": "Allow", "page": 2, "user": 1, "project": 2 } If condition is working properly but unable to work with the code inside else condition. -
How to set-up google oauth using django-allauth without the admin panel
Is there a way to set-up google oauth using django-allauth WITHOUT using the admin panel? I am building a website and don't want to use the default django admin app. I've acquired the required Google client id and secret, now I'm not able to understand how to configure the django-allauth SocailApp setting without the admin app. # SETTINGS.py # Django-allauth config SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": ["profile", "email",], "AUTH_PARAMS": {"access_type": "online",}, "APP": { "client_id": env("GOOGLE_CLIENT_ID"), "secret": env("GOOGLE_CLIENT_SECRET"), }, } } How should I add site to this configuration? -
parameters in request to DRF
I'm trying to parse an API page written using DRF import requests from bs4 import BeautifulSoup import time URL = 'url' data = {'user': 'admin','auth':'admin'} full_page = requests.get(URL, params=data) print(full_page) But I get a 403 error. I understand that I do not correctly transfer the login and password. Tell me how to transfer them? -
Django: Override form.errors messages on UserCreationForm
I'm trying to override (add languages) the messages of form.errors. I've tried this: forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.error_messages['duplicate_username'] = 'some message' After the form is submitted, it's not saved because username are unique and the error is displayed on the template. I'd like to make the same with the password but I can't find out the errors' key for each password validation. Can you provide me it? -
How can i inspect the db again in django?
I created my class in models.py with python manage.py inspectdb how can i generate new class if exists somebody new table in db -
Display success message in Django after download
I am trying to trigger a download of an AWS S3 object using Django 3. views.py def pagelanding(request,slug): if some_condition: URL='URL_to_s3_file' return redirect(URL) So far everything works fine, when I trigger the condition in my template, the download is triggered. The problem is that I would like to display a success message. Since the redirect is occupied by the download directive, I can't for example use the Django messages framework on the template. Is there any way to trigger the download and display the message at the same time? -
Docker with Django/Wagtails has a critical error
I am trying to build a Docker image with a Django/Wagtails site, including API endpoints. This works locally, however when I try to build a Docker image and push it up, it throws an error. Here's what my Dockerfile looks like: FROM python:3.7 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim \ ffmpeg # Set environment varibles ENV PYTHONUNBUFFERED 1 ENV DJANGO_ENV dev COPY ./requirements.txt /code/requirements.txt RUN pip install --upgrade pip # Install any needed packages specified in requirements.txt RUN pip install -r /code/requirements.txt RUN pip install gunicorn # Copy the current directory contents into the container at /code/ COPY . /code/ # Set the working directory to /code/ WORKDIR /code/ RUN python manage.py migrate RUN useradd wagtail RUN chown -R wagtail /code USER wagtail EXPOSE 8000 CMD exec gunicorn appname.wsgi:application --bind 0.0.0.0:8000 --workers 3 If desired, I can put my settings file, my api.py and my urls.py file, but none of them are changed from my local copy which works. Here's the error I get: AttributeError: 'WSGIRequest' object has no … -
Django - Return Object of Arrays
I'd like to have my API endpoint send data in the format {'column_name1': [result_array1],'column_name2': [result_array2]} -
error: No module named 'register.forms', using crispy-forms django
I am trying to install a django user registration module in crispy-forms and I am getting the error: No module named 'register.forms' The exact line giving me issues appears to be from .forms import RegisterForm I do have crispy-forms installed (secret) user@client:~/www/src/exchange $ pip3 install django-crispy-forms Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple Requirement already satisfied: django-crispy-forms in /home/kermit/Env/secret/lib/python3.7/site-packages (1.9.0) . (secret) user@client:~/www/src/exchange $ cat register/views.py from django.shortcuts import render, redirect #from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("home/") else: form = RegisterForm() form = UserCreationForm() return render(response, "register/register.html",{"form":form}) (secret) user@client:~/www/src/exchange $ cat register/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate #from django.models import models class RegisterForm(UserCreationForm): email = models.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] . (secret) user@client:~/www/src/exchange $ cat exchange/urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view, user_view from userdash.views import userdash_detail_view, userdash_create_view from django.conf.urls import include from register import views as v from pages import views urlpatterns = [ path('', views.home_view, name='home'), path('', … -
(pre-receive hook declined) while deploying on heroku
When I try git push heroku master, this error pops up ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/web--dev.git' Also this is in my settings.py file where it can be an error import dj_database_url from decouple import config DATABASE = { 'default': dj_database.config( default=config('DATABASE_URL') ) } -
Now able to register using class based view.?
I want to work with company model where i am to register using subdomain and have to login using that same domain name. I created a model using following fields : models.py class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=2000) sub_domain = models.CharField(max_length=30) user_limit = models.IntegerField(default=5) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) And my registration form is like something below: forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Company fields = ['name', 'address', 'sub_domain', 'country'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs = {"class": "form-control"} But when it comes to views i dont know how to handle class based views and as i am a newbie facing problem to save data in db. views.py class RegistrationView(CreateView): model = Company form_class = RegistrationForm template_name = "company_register.html" def is_valid(self, form): company = Company.objects.create_company(form.cleaned_data['name'], form.cleaned_data['address'], form.cleaned_data['sub_domain'], form.cleaned_data['country']) company.save() return super(RegistrationView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(RegistrationView, self).get_context_data(**kwargs) Please someone help!!! -
TemplateSyntaxError while using typeform sdk to pass url parameter to class
I am using Django. I have pip installed typeform sdk using https://pypi.org/project/django-typeform/ I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0 But this gives me Exception Type: TemplateSyntaxError Exception Value: 'sekizai_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache django_typeform i18n l10n log static tz -
Type error Exception Value: 'Profile' object is not iterable
Not sure what's going wrong here. IF two users have both voted yes to each other, hence both having a vote attribute of True, I am attempting to add both of them to my matches database. But it's not working and I'm not clear why the Profile object is not iterbale. It works fine in my other methods when I try to get it this sort of way. traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 167, in create_vote npm = Profile.objects.get(request.user) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get clone = self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1187, in build_filter arg, value = filter_expr File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 257, in inner return func(self._wrapped, *args) TypeError: … -
After successfully installing mysql and mysql workbench i get this error message each time i run the pip install mysql-python command on virtualenv
ERROR: Command errored out with exit status 1: command: /Users/ebrima/Documents/djangoapp/computerinventory/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"'; file='"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-record-QYXGl9/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ebrima/Documents/djangoapp/computerinventory/venv/include/site/python2.7/mysql-python cwd: /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/ -
Unable to trigger Ajax click function in Django
Trying to update a model based on which download link was pressed in Django. Please see current code below, so fair it doesn't appear to be logging to console either. From profile.html {% for x in source %} {% if forloop.counter <= 4 %} <div class="content-section"> <div class="media-body"> <h2 class="account-heading">{{ x.video_id }}</h2> {% for y in records %} {% if x.video_id == y.sourcevideo.video_id %} <div class="media-body"> <video width="320" height="240" controls> <source src="{{ y.highlight.url }}" type="video/mp4"> Your browser does not support the video tag </video> <br> <a class="btn" id="download" href="{{ y.highlight.url }}" data-id="{{ y.highlight_id }}" download>Download</a> </div> {% endif %} {% endfor %} </div> </div> {% endif %} {% endfor %} <script type="text/javascript"> $("#download").click(function() { console.log( $(this).attr("data-id") ); var catid; catid = $(this).attr("data-id"); $.ajax({ type:"POST", url: "/downloaded", data: { highlight_id: catid }, success: function( data ) { console.log(data) } }) }) </script> From views.py def downloaded(request): if request.method == 'POST': highlight_id = request.GET('highlight_id') downloadedvideo = Highlight.objects.get(pk=highlight_id) downloadedvideo.used = True downloadedvideo.save() return else: return Any help is greatly appreciated! -
Django generic detail view must be called with an object pk or a slug but my URL has a PK already
AttributeError at /mini_fb/profile/1/delete_status/14 Generic detail view DeleteStatusMessageView must be called with either an object pk or a slug in the URLconf. Isn't my PK 1 and 14 already in the URL? Why am I getting this error? <a href="{% url 'delete_status' profile_pk=profile.pk status_pk=x.pk %}">delete</a> class DeleteStatusMessageView(DeleteView): '''A class for the view for deleting status messages.''' template_name = 'mini_fb/delete_status_message.html' queryset = StatusMessage.objects.all() def get_context_data(self, **kwargs): '''Return a dictionary with context data for this template to use.''' context = super(DeleteStatusMessageView, self).get_context_data(**kwargs) st_msg = StatusMessage.objects.get(pk=self.kwargs['status_pk']) context['st_msg'] = st_msg return context # return the dictionary -
User Serializer is showing null in AJAX fetch but shows data in DRF
I have below the details of my serializer for the current user serializers.py class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'email', 'first_name', 'last_name', ] views.py class UserViewSet(APIView): def get(self, request): serializer = UserDetailSerializer(request.user) return Response(serializer.data) urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^user/', accounts_views.UserViewSet.as_view()), ] going to http://localhost:8000/user/ shows the proper json/api data: { "id": 1, "username": "stormadmin", "email": "", "first_name": "", "last_name": "" } but when I try to use ajax to fetch the data: async getUser() { const response = await fetch('http://127.0.0.1:8000'+'/user/'); const resData = await response.json(); return resData; } I get this instead: {id: null, username: ""} My question is, how do I get the data I want with an AJAX call? Or is there a better way to do this? -
How to return a template from a function without the request argument?
I am not sure if this makes any sense but I am trying to figure out a way to get a function without request argument to return an HTML template. The code below will help you better understand my point. views.py def home(request): global running, row_count, thread if request.method == 'POST': row_count = 0 thread = threading.Thread(target=fun) thread.daemon = True thread.start() running = True return render(request, 'scraper/home.html', {'countries': countries, 'running': running}) else: return render(request, 'scraper/home.html') def fun(): global row_count, finished, thread while True: row_count += 5 if row_count == 15: finished = True thread.join() return time.sleep(5) What I am trying to achieve is to reflect that finished=Truein my 'scraper/home.html/ template. I want to make an element in my template based on the value of finished. Something like this: scraper/home.html {% if finished %} <p>Finished!</p> {% endif %} I'll appreciate your help on this. Thanks -
Django schema explorer simple recursive algorithm - confused by results / how to fix
I am using Django and have a couple of use cases for which the ability for objects to trace their relationships through several models is required. I don't want to hand-code this functionality for every model. Some example models: class Project(models.Model): project_name = models.CharField(max_length=200, default="development_project") class Question(models.Model): project = models.ForeignKey(Project, default=1, on_delete=models.CASCADE) question_text = models.CharField(max_length=200, default="question text") class Extra(models.Model): extended_q = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) summary_of = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) content = models.CharField(max_length=200, default="simple summary") class Answer(models.Model): question = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) Using models as nodes of a network and relationships as edges, this seems like it should be manageable, but for some complexity where there are 'redundant' edges - do we permit an Extra to summarise Answers from a different project? my use cases will be: a models.Manager class that can act as the default manager for a sub-class of Django apps that work together in a unified site and help do the sort of row-separating management that will keep users, even in the admin, from getting under each others feet. an overall app using ContentTypes that can help the user build datasets and organise tables for dataframes (taking fks and making them appropriate category … -
Label and input value overlaps with django-material and datepicker
So the idea is that I need a pop-up and in that pop-up there should be a form in which you have to choose the date, so the pop-up have a Form object with a TextField that emulates the a date input to use the datepicker of material, the problem comes with the label of that input that overlaps with the input itself like this. I tried using javascript to add the class "active" to the label when you click the input because that is what triggers the label to go up but it doesn't recognize it and doesnt apply the class. The html renders like this: <div class="input-field col s12 required" id="id_fecha_cobro_container"> <i class="material-icons prefix">insert_invitation</i><input id="id_fecha_cobro" name="fecha_cobro" type="date"> <label for="id_fecha_cobro">Fecha de Cobro</label> </div> This is the modal in django: {% block change_form %} {% form %} {% part form.fecha_cobro prefix %}<i class="material-icons prefix">insert_invitation</i>{% endpart %} {% endform %} {% prepopulated_fields_js %} {% endblock %} This is the form class: class AvisoVacacionForm(forms.Form): fecha_cobro = forms.DateField(label="Fecha de Cobro", required=True, widget=forms.TextInput(attrs={'type': 'date'})) def __init__(self, *args, **kwargs): super(AvisoVacacionForm, self).__init__(*args, **kwargs) This is what I've tried using javascript: $('#id_fecha_cobro').click(function(){ $("label[for='id_fecha_cobro']").addClass("active") });