Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save model tries to create new object
I have the following two Django models: class A: uuid = CharField(primary_key=True) code = CharField(unique=True) class B: uuid = CharField(primary_key=True) a = ForeignKey(A, related_name='bs') def save(**kwargs): self.a.save(**kwargs) super(B, self).save(**kwargs) If I want to use them in a test case and write this function: def setUp(): a = A.objects.create(uuid='a') b = B.objects.create(uuid='b', a=a) I get the following error: UNIQUE constraint failed: app_name_a.code It looks like that in the save method of B, it tries to create another A with the same values instead of updating the existing instance. Why would this be so? I am using Python 3.5 and Django 1.8.14. By the way: the reason I want to save the parent is that I have functionality in the save method that is updating an updated_at timestamp. -
making a python website which sends facebook message
I have a desktop application, which uses the fbchat plugin to notify users on facebook. However, since the program runs on multiple computers, facebook banned my account, because there are so many log-ins coming from different locations. To solve this problem I thought of creating a website that communicates with the desktop applicaation instances and sends the facebook notifications. This way there only be one log-in to facebook from one location, that of the web server. My idea is that it will receive requests from the desktop applications and use that information to send the facebook notifications. How would I go about making a web app with this functionality? I heard about django but I do not know how to go about using it. -
Using Instagram API to make users populate images into my Djangs application directly from Instagram Pictures
My use case or what I want to do is: Users click a Upload button, it authenticates user, its shows Instagram images, users select, and user click upload button to upload images or videos (media) from Instagram directly into my django app. What I have done is: Instagram integration: pip install python-instagram views.py: @login_required() def instagram_pictures(request, template='dashboard/add-instagram-pictures.html'): user = request.user gallery = [] gallery = Gallery.objects.filter(service_provider=user.service_provider_profile) context = {'gallery': gallery} return render(request, template, context) @login_required() def add_instagram_pictures(request, template='dashboard/add-instagram-pictures.html'): access_token = "YOUR_ACCESS_TOKEN" # Dont know how this gets factored in for any user client_secret = settings.SECRET_ID api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="userid", count=10) for media in recent_media: print(media.caption.text) template/my-gallery.html: {% extends 'base.html' %} {% load static %} {% block title %}My Dashboard{% endblock %} {% block content %} <div class="page-header" style="background: url({% static 'img/banner1.jpg' %});"> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="page-title">My Gallery</h1> </div> </div> </div> </div> <div id="content"> <div class="container"> <div class="row"> {% include '_side_menu.html' %} <div class="col-md-8 page-content"> <div class="inner-box text-center"> <a href="{% url 'dashboard:add-instagram-pictures' %}" class="btn btn-md btn-success"> <span class="fa fa-plus-circle"> Upload from Instagram</span> </a> <ul> <!-- I will re-write this loop to redefine how images are rendered for the project. Maybe in Carousels--> {% … -
Django: Display error message passed by Http404("msg") in custom 404 error handler
Using django 1.11, I have defined a custom 404 handler, by writing in my main URLs.py: handler404 = 'myApp.views.myError' The function myError() looks like this: def myError(request): #errorMsg=request.error_404_message return render(request,'404.html') This function works when I call raise Http404("My msg"). However, when I try to get the message passed by the Http404 call (see commented section in myError), my code crashes: Server Error (500) How can I then get the error message? I read a lot of questions about it like this one, but most answers refer to getting the message in the html file and not in a custom python error handler function. EDIT: The problem is, that I cannot see the debug page, because the error obviously only occurs when myError() is called and this happens only, if debug=False in the settings. -
Could not append all subelemnt to a single element using Django and Python
I need some help. I need to append all data into a single parent value which are present inside one xml file using Django and Python. I am explaining my code below. def some(request): if request.method == 'POST': location_name = request.POST.get('lname') rname = request.POST.get('rname') seat = request.POST.get('seat') projector = request.POST.get('projector') video = request.POST.get('video') num=str(random.randint(100000000000,999999999999)) droot = ET.Element("roomlist") doc = ET.SubElement(root, "locationname", name=location_name) doc1 = ET.SubElement(doc, "roomid", name=num) ET.SubElement(doc1, "roomname", name=rname).text = rname ET.SubElement(doc1, "noseats", name=seat).text = seat ET.SubElement(doc1, "projectorscreen", name=projector).text = projector ET.SubElement(doc1, "videoconf", name=video).text = video tree = ET.ElementTree(root) root1 = tree.getroot() xmlstr = ET.tostring(root1, 'utf-8', method='xml') with open("filename.xml", "a") as myfile: myfile.write(xmlstr) Here I am getting the output like below. <roomlist><locationname name="cuttuck"><roomid name="853112054052"><roomname name="cottage">cottage</roomname><noseats name="12">12</noseats><projectorscreen name="No">No</projectorscreen><videoconf name="Yes">Yes</videoconf></roomid></locationname></roomlist> <roomlist><locationname name="puri"><roomid name="593513125603"><roomname name="puri room">puri room</roomname><noseats name="30">30</noseats><projectorscreen name="No">No</projectorscreen><videoconf name="No">No</videoconf></roomid></locationname></roomlist> But Here I need to append all data into single <roomlist></roomlist> . Please help me. -
Django Rest Framework - use serializers to send json with requests library
I hava DRF setup that receives data in json and stores it inside django. Serializer is following class ReservationSerializer(serializers.ModelSerializer): room = RoomSerializer() reserved_days = DaySerializer(many=True) additional_services = AdditionalServicesSerializer(many=True) class Meta: model = Reservation fields = [ 'start', 'end', 'check_in_time', 'check_out_time', 'reserved_days', 'additional_services', 'room', 'has_refund', 'payed', 'guest_name', 'reservation_number', ] Can I use this serializer to prepare models in json and then send this json with Requests library ? -
How to configure django restframework swagger base path
I need to set up swagger UI for my Django restframework apis on development server. the project is deployed using apache2 and the url is user41.dc/django/ and so my APIs usr41.dc/django/api/.. but the Swagger UI sends the requests to usr41.dc/api/ skipping the '/django' and the setting related to swagger SWAGGER_SETTINGS = { 'JSON_EDITOR': True, 'base_path': '/django/', 'VALIDATOR_URL': None } Note : it works correctly using localhost:port/api -
Why won't my index.html file be found in directory?
I'm 100% sure my path is correct in my code, why is it giving me TemplateDoesNotExist error? I can't see how this is possible. I tried: settings.py > TEMPLATES > Dirs: [/template/music] and a laundry list of other things on SO but it doesn't rectify my problem. Here's my views.py file: from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('music/index.html') return HttpResponse(template.render()) def detail(request, user_id): # Testing out page 2 return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>") Here's my index.html file: <!DOCTYPE html> <html lang="en"> <head> <title>The Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form action="#"> <div class="form-group"> <label for="firstName">First Name:</label> <input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName"> </div> <div class="form-group"> <label for="">Last Name:</label> <input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName"> </div> </form> <div class="checkbox"> <label><input type="checkbox" name="remember">Remember me</label></div></br> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </body> </html> -
build_attrs() got an unexpected keyword argument 'type' with django-bootstrap3-datetimepicker sample
hi try to use django-bootstrap3-datetimepicker. in first time i try only with sample form package, and i have this error : TypeError at /sample/ build_attrs() got an unexpected keyword argument 'type' Request Method: GET Request URL: http://localhost:8000/sample/ Django Version: 1.11.2 Exception Type: TypeError Exception Value: build_attrs() got an unexpected keyword argument 'type' Exception Location: C:\git\ATH_intranet\env_p3\lib\site-packages\bootstrap3_datetime\widgets.py in render, line 110 Python Executable: C:\git\ATH_intranet\env_p3\Scripts\python.exe Python Version: 3.6.1 Python Path: ['c:\\git\\ATH_intranet', 'C:\\git\\ATH_intranet\\env_p3\\Lib', 'C:\\git\\ATH_intranet\\env_p3\\DLLs', 'C:\\git\\ATH_intranet\\env_p3\\Lib\\lib-tk', 'C:\\another-library', 'C:\\git\\ATH_intranet\\env_p3\\Scripts\\python36.zip', 'C:\\git\\ATH_intranet\\env_p3\\Scripts', 'C:\\git\\ATH_intranet\\env_p3', 'C:\\git\\ATH_intranet\\env_p3\\lib\\site-packages', 'C:\\git\\ATH_intranet\\env_p3\\lib\\site-packages\\django_bootstrap3_datetimepicker-2.3-py3.6.egg'] Server time: jeu, 15 Jui 2017 13:28:05 +0000 Error during template rendering In template c:\git\ATH_intranet\todo_app\templates\todo_app\template.html, error at line 27 build_attrs() got an unexpected keyword argument 'type' 17 max-width: 500px; 18 } 19 </style> 20 </head> 21 <body> 22 <form method="post" role="form"> 23 {% for field in form.visible_fields %} 24 <div id="div_{{ field.html_name }}" 25 class="form-group{% if field.errors %} has-error{% endif %}"> 26 {{ field.label_tag }} 27 {{ field }} 28 <div class="text-muted pull-right"> 29 <small>{{ field.help_text }}</small> 30 </div> 31 <div class="help-block"> 32 {{ field.errors }} 33 </div> 34 </div> 35 {% endfor %} 36 {% for hidden in form.hidden_fields %} 37 {{ hidden }} Traceback Switch to copy-and-paste view C:\git\ATH_intranet\env_p3\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\git\ATH_intranet\env_p3\lib\site-packages\django\core\handlers\base.py in _get_response … -
Django Channels over apache server
I have a django project that's working well on my vps over apache. after adding django channels to my project it's working on localhost perfectly but in my vps my browser logged an error "WebSocket connection to '...' failed: Error during WebSocket handshake: Unexpected response code: 404" and project failed. according my googling i thing apache can't support web-socket. but cann't find a clear answer and trip for running channels on apache this is my apache config in 000-default.conf: <VirtualHost *:80> Alias /static /opt/kalameh/static <Directory /opt/kalameh/static> Require all granted </Directory> <Directory /opt/kalameh/server> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess kalameh python-path=opt/kalameh python-home=opt/kalameh/kalamehenv WSGIProcessGroup kalameh WSGIScriptAlias / opt/kalameh/server/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> and this is my wsgi.py import os import sys sys.path.append('/opt/kalameh/') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") application = get_wsgi_application() -
H18 Error: Django app Media Upload failing on Heroku
Our Django App is failing media upload. This has been an off-and-on issue for us for a while. however, for about a week now, it's been consistently failing to upload media. Our media files are stored on S3. On inspection, the uploaded files were found in the S3 buckets... However, the logs display the message below while the app throws an Application error... -
Django matching list autofill, getting values from backend
I have a web from which has a matching list field, currently I am saving the list values in the frontend. But I want to push the values from the server, is it a good practice? I am using django and I would like to know how values can be sent from backend to frontend in cases like dropdowns, matching lists etc. The values are not stored in the database too. They are well known fixed values that I don't want to be seen in the frontend. -
Django: Create staff user from oneToOneField
I have a model in order to extend the user model with some extra fields. The "therapeut" model has a user field that's a OneToOneField connected to User from django.contrib.auth.models. Here's the code: from django.db import models from django.contrib.auth.models import User class Therapeut(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # some more fields here Now when I want to add a "therapeut" from the model through the Django Admin, I can choose from the available Users or add a new one. When click I add a new one (green + next to the User dropdown), I would like that new user to have staff status and add it to the user group "therapeuten", in order to manage the permissions for this new user. I dont see how to archieve this (automatically), neither do I have the option to set staff status and user group in the popup. Note I am logged in as the superuser. See pic: Any help on how to do this would be much appreciated! -
Getting blank sender email id using Imap4
I am getting header 'from' blank i.e. unable to get sender address c.select('INBOX', readonly=True) for i in range(1, 30): typ, msg_data = c.fetch(str(i), '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) for header in [ 'subject', 'to', 'from' ]: print '%-8s: %s' % (header.upper(), msg[header]) Here is the output SUBJECT : Here is testing subject TO : "abhi.don@gdp.gov" FROM : -
Django annotated queryset vs model properties
I have model with custom manager (replaced from properties) that annotate queryset by pseudo fields (adds some annotation inside get_queryset). And its cool because I have one database query per list and so on. But in some cases this is a problem. For example I want to get my_annotated_field inside signal function or with Django Rest Framework on save ViewSet (where we didn't get object via my manager). Model class doesn't have those fields. Is there way to solve this problem without extra query like obj = MyModel.objects.get(pk=obj.id)? -
Pythonanywhere: Running Django shell in .ipynb Python notebook
I am running Django on Pythonanywhere. I have created a .ipynb notebook in the same directory having manage.py file. I have added the following code: import csv, os,sys from __future__ import absolute_import from django.conf import settings settings.configure() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settingsfile") import django django.setup() from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from app.models import model_one, model_two But am getting the following error: RuntimeError: Model class app.models.the_model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Can some someone please tell me how to correct it, and what is the best way to run python shell in iPython notebook? TIA -
How to observe scheduled tasks output with Django celery and Docker
I have setup my celery app for django and trying to test a simple periodic tasks in my django app. I have used RabbitMQ as message broker and setup broker_url by passing environment variables from docker-compose.yml file as well. I have following structure in docker-compose.yml file. version: '3' services: nginx: restart: always image: nginx:latest container_name: NGINX ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /static:/static depends_on: - web web: restart: always build: . container_name: DJANGO command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload" depends_on: - db volumes: - ./src:/src - /static:/static expose: - "8000" links: - db - rabbit db: restart: always image: postgres:latest container_name: PSQL rabbit: hostname: rabbit image: rabbitmq:latest ports: # We forward this port for debugging purposes. - "5672:5672" # Here, we can access the rabbitmq management plugin. - "15672:15672" environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=mypass # Celery worker worker: build: . command: bash -c "python manage.py celery worker -B --concurrency=1" volumes: - .:/src links: - db - rabbit depends_on: - rabbit For testing purpose, I have created a schedule tasks in settings.py as follows:(scheduling for 10 seconds) CELERYBEAT_SCHEDULE = { 'schedule-task': { 'task': 'myapp.tasks.test_print', 'schedule': 10, # in … -
Does Anyone know django-channels good tutoiral link? [on hold]
I need to develop a real-time chat application. I thought of using django framework with channels for the application. But couldn't find any good tutorials. Can anyone point me in the correct direction to start with some links to tutorials? Also should I be using django or use nodejs for building the app? -
How to create an ordered list containing different models in Django?
I am trying to create an ordered list of items coming from different models in Django. As context: I am working with the Facebook messenger API. I am trying to create a welcome message that can contain different types of answers such as: Text (which would be its own model with a CharField containing the text) Image (which would be its own model with a CharField containing the image) Article (which would be its own model containing a Title, a thumbnail, an action call and a link) A typical welcome message could contain any combination of the above objects, and I want them to be sent in a specific order, for instance: Text 1 Text 2 Article 1 Image 1 All of the above would be 1 welcome message. My current thinking is to create: - 1 model for WelcomeMessage - 1 model for TextMsg with ForeignKey WelcomeMessage - 1 model for ImgMsg with ForeignKey WelcomeMessage - 1 model for ArticleMsg with ForeignKey WelcomeMessage What is unclear to me is: how can I then order the different TextMsg, ImgMsg, ArticleMsg inside my WelcomeMessage? Or is there a better approach to the problem that I'm not seeing? -
Giving AnonymousUser a default Account?
I am working on a Django Project where the Site is customizable for each User. I build the Site in a Way that it is necessary to have a Profile and Account Settings. My Problem is now that when a User who does not have an Account or simply not logged in cannot do anything since he/she gets directly a 404 or with Debug= True 'AnonymousUser' object has no attribute 'profile'. Is there a way to give Users a "default" Account just for the Session which contains the necessary Parts so the Site would run? Im searching for a solution where the user does not have to register or login in any way. Hope somebody has an Idea. Regards Marla. EDIT: Just found this but in this case I would need a huge number of different Accounts since i never know how many Users come to the site without an Account right? Cant give everybody the same Account... -
Use Docker, Gunicorn, Nginx in django development environment but can only see nginx welcome page?
I use Docker, Gunicorn, Nginx in django development environment but can only see nginx welcome page. my docker file: django: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN groupadd -r django \ && useradd -r -g django django COPY ./requirements.txt /requirements.txt RUN pip install --no-cache-dir -r /requirements.txt \ && rm -rf /requirements.txt COPY ./compose/django/gunicorn.sh / RUN sed -i 's/\r//' /gunicorn.sh \ && chmod +x /gunicorn.sh \ && chown django /gunicorn.sh COPY . /app RUN chown -R django /app RUN mkdir /static RUN chown -R django /static USER django WORKDIR /app nginx: FROM nginx:latest ADD nginx.conf /etc/nginx/sites-enabled/django_blog.conf gunicorn.sh: #!/bin/sh python /app/manage.py collectstatic --noinput /usr/local/bin/gunicorn blogproject.wsgi -w 4 -b 127.0.0.1:8000 --chdir=/app nginx.conf: server { charset utf-8; listen 80 default_server; location /static { alias /app/static; } location / { proxy_pass_header Server; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:8000; } } docker-compose.yml: version: '3' services: django: build: context: . dockerfile: ./compose/django/Dockerfile command: /gunicorn.sh nginx: build: ./compose/nginx depends_on: - django ports: - "80:80" commands I run: docker-compose build docker-compose up It seems Nginx doesn't pass request to gunicorn? -
How to print a result in the django python console
I created a form which has login option. I want to show the username which was given in the username label in the python console. Here is my views.py file: from django.views.generic import TemplateView from django.shortcuts import render from app.forms import * class login(TemplateView): template_name = 'app/login.html' def clean(self): form = RegistrationForm() print form.cleaned_data['username'] The following is my forms.py file: from django import forms class RegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=30) password = forms.CharField(label='Password', widget=forms.PasswordInput()) def clean_password(self): username = self.cleaned_data['username'] This doesn't print what I wanted. Pls help me solve this. -
Django delete error message
i have two models. when i try delete contact recevied error Exception Value: ("Cannot delete some instances of model 'GuestContact' because they are referenced through a protected foreign key: 'Reservation.res_company'", <QuerySet [<Reservation: Reservation object>, <Reservation: Reservation object>]>) i dont' want see django error page. i want send information " this record can't be delete, but this contact is used in reservation" can you help me ? regards -
Can not append the data into xml file using Django and Python
I have an issue. I am trying to append all my post data into xml file but it always overwrite. I am explaining my code below. def some(request): if request.method == 'POST': location_name = request.POST.get('lname') rname = request.POST.get('rname') seat = request.POST.get('seat') projector = request.POST.get('projector') video = request.POST.get('video') root = ET.Element("roomlist") doc = ET.SubElement(root, "locationname", name=location_name) doc1 = ET.SubElement(doc, "roomid", name="1234") ET.SubElement(doc1, "roomname", name=rname).text = rname ET.SubElement(doc1, "noseats", name=seat).text = seat ET.SubElement(doc1, "projectorscreen", name=projector).text = projector ET.SubElement(doc1, "videoconf", name=video).text = video tree = ET.ElementTree(root) tree.write("filename.xml") return render(request, 'booking/bmr.html', {}) Here I need when user will submit the form all data will append into the existing xml file but in my case its overwriting every time.Please help me to resolve this issue. -
Django quill - Form error while saving the form field within quill's id
<link href="https://cdn.quilljs.com/1.2.6/quill.snow.css" rel="stylesheet"> <!-- Create the editor container --> <div id="editor"> {{ form.description }} </div> <!-- Include the Quill library --> <script src="https://cdn.quilljs.com/1.2.6/quill.js"></script> <!-- Initialize Quill editor --> <script> var quill = new Quill('#editor', { theme: 'snow' }); </script> the form gets saved successfully when it is not enclosed within the id "#editor" but when I enclose it, the form fields appears with editing options,but when I try to submit I get the following error that the field description is required.