Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tracking unregistered users in Django website
I need to track unregistered users in my Django website. This for conversion optimization purposes (e.g. registration funnel, etc). A method I've used so far is using IP address as a proxy for user_id. For various well-known reasons, this has led to fudged/unreliable results. What alternative can I use? Currently, I'm thinking I'll set a session variable every time an unauthorized user hits my web app's landing page, like so: if not request.session.exists(request.session.session_key): request.session.create() From here on, I'll simply track them via request.session.session_key. Would this be a sound strategy? Or are there edge cases that will fudge my data here as well? -
How to annotate exist for each raw of filter in Django
I have this model: class User(AbstractUser): first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) ... class Friends(models.Model): owner = models.ForeignKey(User, related_name="owner_friends") user = models.ForeignKey(User, related_name="user_friends") Assume "Alex" want's to see "Bob" friends. I can do this with this code: Friends.objects.filter(owner_friends_first_name="Bob") now I want to generate another filed that show "Jon" who is "Bob" friend, also is "Alex" friend or not. I think I can do this with annotate but I don't know how. Excuse me for my bad english . -
Django can't locate my static files
I deploy the static settings like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static/"), ] And I got a static folder in root with some css files, I use the link like: <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/station_list.css'"> <img src="{{ STATIC_URL }}images/logo.png"> The css path is correct but the html can't display the css style, and I check the terminal, it says: Not Found: /raise/station/css/station_list.css' Not Found: /raise/station/images/logo.png Why the path is not /static/ but an app root? Thanks. -
Storing data files on Django application
I am building a web application that allows users to login and upload data files that would eventually be used to perform data visualisation and data mining features - Imagine a SAS EG/Orange equivalent on the web. What are the best practices to store these files (in a database or on file) to facilitate efficient retrieval and processing of the data and the pros and cons of each method? -
IMAP4 not working on python anywhere server but same code works on localhost
I want to user to login in my django web app using our institute mail server. But this code allow to login using institute mail on localhost but not on server. I tried on pythonanywhere django provided shell: from imaplib import IMAP4 c = IMAP4('newmailhost.cc.iitk.ac.in') error comes in web server but not in local host shell.. socket.gaierror: [Errno -2] Name or service not known In mylib/backend.py from django.contrib.auth.models import User from imaplib import IMAP4 class MyCustomBackend: # Create an authentication method # This is called by the standard Django login procedure def authenticate(self, username=None, password=None): try: # Check if this user is valid on the mail server c = IMAP4('newmailhost.cc.iitk.ac.in') c.login(username, password) except: return None user, created = User.objects.get_or_create(username=username) return user # Required for your backend to work properly - unchanged in most scenarios def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None in setting.py AUTHENTICATION_BACKENDS = ( 'mylib.backend.MyCustomBackend', 'django.contrib.auth.backends.ModelBackend', ) -
Django Session KeyError when key exists
The following code works locally when I use Django's development server, but I am running into intermittent bugs in production with Nginx and Gunicorn. views.py def first_view(request): if request.method == "POST": # not using a django form in the template, so need to parse the request POST new_post = {key:val for key,val in request.POST.items() if key != 'csrfmiddlewaretoken'} request.session['new_post'] = new_mappings # save for use within next view # more logic here (nothing involving views) return redirect('second_view') def second_view(request): if request.method == 'POST': new_post = request.session['new_post'] # ... more code below # render template with form that will eventually post to this view I will sometimes receive a KeyError after posting to the second view. Based on the documentation on when sessions are saved, it seems like the session variable should be saved since it is modifying the session directly. Also, if I take the sessionid provided the error page's debug panel and access the session via Django's API, I can see the 'new_post' session variable python manage.py shell >>> from django.contrib.sessions.backends.db import SessionStore >>> s = SessionStore(session_key='sessionid_from_debug_panel') >>> s['new_post'] # dictionary with expected post items Is there something I'm missing? Thanks in advance for your help! -
Deleting folders in docker conatiner using python
I have this function which deletes the given directory when row is being deleted in Django Admin. The row is successfully deleted when done on Django Admin but the directory still exists. models.py from django.db import models from django.conf import settings import git, os, shutil class DIR (models.Model): username = models.CharField(max_length=39) repository = models.CharField(max_length=100) def get_dir_name(self): return os.path.join(settings.PLAYBOOK_DIR, self.repository) def rm_repository(self): DIR_NAME = self.get_dir_name() shutil.rmtree(os.path.join(DIR_NAME)) def delete(self): self.rm_repository(self): super(DIR, self).delete(*args, **kwargs) But when I try it using shell, the directory and contents get deleted $ docker exec -it <container> python manage.py shell >>> import os, git, shutil >>> DIR_NAME = '/opt/app/john' >>> shutil.rmtree(DIR_NAME) What is the difference between shell. There were no errors given, just not sure why doing it in Django Admin's delete doesn't work. While it is working when tested on python shell? -
Conceptualizing a Django model
I'm working on my first Django project outside of an online tutorial and I've having some trouble on identifying the best way to create one of my models. I want to have the ability to have all the personnel login into the page, so I was going to extend the built-in Django users model. However, I have a class of users with a role of operator that needs to have 4 special characteristics added to their account. I'm looking for the best way to solve this issue. Right now I have the following logic whiteboarded: Users have a first name, last name, bio, group, etc... Each user is assigned a group, and if they are a member of the operators group, then add the additional characteristics to a model called OperatorInfo. I know that I can do all of this in a form, and call the information back to my templates this way, but I don't know if this is the best way to proceed. I want my app to have the ability to scale in the future, and I don't know the best way to setup these models to scale. Any info you could provide would be greatly appreciated. -
django_rest_framwork occured “TypeError: 'Link' object does not support item assignment”
A project using django rest framework. I am trying to use the builtin docs but i keep getting this error.enter image description here whats the solution? -
Django serializing view for model and non model serilizer
Expectation: Expected output: { "id": 123, "name": "abc", "body_measurement": { "weight": 75, "bp": "normal, "bloodgroup": "A-positive", }, } models.py class Health(models.Model): name = models.CharField(max_length=64, unique=True) body_measurment = JSONField(_('measurments'),dump_kwargs={'indent': 4}) serializer.py class HealthSerializer(serializers.ModelSerializer): class Meta: model = Health fields = '__all__' class MeasurementSerializer(serializer,Serializer): weight = serializer.IntegerField() bp = serializer.CharField() bloodgroup = serializer.CharField() views.py class HealthViewSet(viewsets.ModelViewSet): queryset = Health.objects.all() serializer_class = HealthSerializer How can i add set of key values into the body_measurment with out adding in models. -
Django: Extended User Model Cant Save
I have extended the django user model with another model called profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) chosenCharity = models.ForeignKey('meta.Charity', db_column='chosenCharityid', related_name='user_chosenCharity') bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When I try to create a new user within the view with the code below i get the following error "(1048, "Column 'chosenCharityid' cannot be null")": @transaction.atomic def register(request): selectedTeams = StraightredTeam.objects.filter(Q(teamid=request.session['team1id']) | Q(teamid=request.session['team2id'])).order_by('teamname') request.POST.get('currentCharities') next_url = request.POST.get('next', request.GET.get('next', reverse('straightred.payment'))) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_user = form.save() I know when a user has already created I should be able to use: user = User.objects.get(pk=user_id) user.profile.chosenCharity = 12 user.save() But I am unsure how to do this when creating the user. Any help would be appreciated. Below is a copy of the registration form to help: class RegistrationForm(BootstrapModelForm, UserCreationForm): email_opt_in = forms.BooleanField(label='Receive DWAD e-mail updates', required=False) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) # The default Django user model doesn't require these fields to be set # but we do. self.fields['email'].required = True def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('There is already … -
Django - How to update user but not provide username and password
I have a set of APIs that give staffs changing some fields of normal user. I want instead of providing username(email)/password of a specific user, staff/super users can change that user's information without username(email)/password (of him/her). I tried set two fields "username", "password" in User Serializer but it did not work: a created user don't have email and password. Please give me a hand :D. Thanks all -
.data function and/or jsonrequest method
Here is my .ajax call : (function($){ var bindEvents = function(node){ $('.btn-fax', node).bind('click', function(e){ e.preventDefault(); var data = {}; var fax_number = {{ contract.request.customer.convert_fax_number }}; $.ajax({ url : $(this).attr('href'), type: 'POST', data : data, success: function(data, textStatus, jqXHR) { if (data.success) { console.log('place 1'); if (data.redirect_to) { console.log('place 2'); window.location.href = data.redirect_to; } else if (data.reload) { console.log('place 3'); window.location.reload(); } } else { console.log('place 4'); alert('Error! See console for details :('); console.error(textStatus, data); } }, error: function (jqXHR, textStatus, errorThrown) { console.log(fax_number); console.log(fax_number === ''); if (!fax_number) { alert('Please, attach the fax number to your profile'); return; } console.error(textStatus, errorThrown); } }); return false; }); }; $.lw.on('init', function(args){ bindEvents(args.node); }); })(typeof(django) == 'undefined' ? jQuery : django.jQuery); and here is the portion of my django template which use the button : <a href="{% url "contracts:fax" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 btn-fax" data-turbolinks="false">{%trans "Fax contract" %}</a> My code is not being rendered by Django - It is in a separate JavaScript file, not in a Django template. Hence, I could not define a variable as var fax_number = {{ contract.request.customer.convert_fax_number }}; Somme people told me that I could use a jQuery .data() function or I can build … -
Moving a project around - ImportError: No module named django.core.management
Why does django give this error below when I move the project from one place to another? $ python manage.py runserver 0.0.0.0:8000 /var/www/html/python-frameworks/django-project/foo-restructure/foo Traceback (most recent call last): File "manage.py", line 13, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management I have to re-built the project every time when I have it moved around. The project was at /var/www/html/django-project but I moved it into another folder at /var/www/html/python-frameworks/django-project. How can I avoid this error? I am on Ubuntu 17.04. -
Creating CRUD with pymongo in django
I'm trying to build a CRUD view with MongoDB using PyMongo (and I'm a little bit new to mongo/pymongo). I created the full CRUD view using the normal forms and mysql, how can I use Mongo to do the same? these are the main parts for my contacts app so far: models.py: class Contact(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) phone_number = models.CharField(max_length=60) email_address = models.EmailField() forms.py: class ContactForm(forms.ModelForm): class Meta: model = Contact fields = '__all__' and views.py: def contact_list(request): contacts = Contact.objects.all().order_by("phone_number") return render(request, 'contacts/contact_list.html', {'contacts': contacts}) def save_contact_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True contacts = Contact.objects.all().order_by("phone_number") data['html_contact_list'] = render_to_string('contacts/includes/partial_contact_list.html', { 'contacts': contacts }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) else: form = ContactForm() return save_contact_form(request, form, 'contacts/includes/partial_contact_create.html') def contact_update(request, pk): contact = get_object_or_404(Contact, pk=pk) if request.method == 'POST': form = ContactForm(request.POST, instance=contact) else: form = ContactForm(instance=contact) return save_contact_form(request, form, 'contacts/includes/partial_contact_update.html') def contact_delete(request, pk): contact = get_object_or_404(Contact, pk=pk) data = dict() if request.method == 'POST': contact.delete() data['form_is_valid'] = True contacts = Contact.objects.all() data['html_book_list'] = render_to_string('contacts/includes/partial_contact_list.html', { 'contacts': contacts }) else: … -
Django annotate not bringing back distinct
I am trying to query a queryset in Django using annotate to get a calculation for each different 'field2'. The query looks like: offer_lines.filter('field1'=x).order_by().values('field2').annotate( total=F('field3') * F('field4') While I am expecting it to return something that looks like this: [{'field2_value1': '1'}, {'field2_value2': '2'}] I am getting multiple entries for the same field2 value. So it looks more like this: [{'field2_value1': '1'}, {'field2_value1': '2'}, {'field2_value1': '5'},{'field2_value2': '2'}, {'field2_value2': '1'}] I have order_by() in the query as I saw in other questions that it sometimes matters, but it did not help me. How can I query it to only return one entry per each unique field2 value? -
Django Rest Framework Token Auth w/ Django Channels?
Is there any way to get Django Rest Framework's Token Auth scheme working with a websocket connection (Channels)? I'm essentially looking to authenticate the user in the same way I do my Rest API, by passing the authorization Token in the header of the request. Right now I get a 503, but using the http session decorator I can get it to work when logged in through the Browsable API. -
Apache - add a new virtualhost proxy that directs to a php file?
How can I add a new port that directs to a php file? I have directed my default port 80 to 3838 for a django project: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyPass / http://127.0.0.1:3838/ ProxyPassReverse / http://127.0.0.1:3838/ </VirtualHost> But I need some the PHP adminer which was on port 80 - http://127.0.0.1/adminer-4.3.1.php. So I thought I can assign a new port 9999 and direct it to this file again? $ sudo nano /etc/apache2/sites-available/000-default.conf <VirtualHost *:9999> ServerAdmin webmaster@localhost DocumentRoot /var/www/html CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyPass / http://127.0.0.1/adminer-4.3.1.php/ ProxyPassReverse / http://127.0.0.1/adminer-4.3.1.php/ </VirtualHost> Does not work of course. I get 404 from django project: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:3838/adminer-4.3.1.php/ As you can see http://127.0.1.1:9999/ is directed to http://127.0.0.1:3838 Is it possible? Or any better solutions? -
How to make an editable table as the list_editable of django admin
Hello everyone I have this queryset but it only allows me to modify a field, and the textinput q is generated for the other fields is only one, as to show the textinput corresponding to each object to edit them. views.py: def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad).order_by('- articulo') pedido2 =Pedido.objects.filter(especialidad=especialidad).filter(estado='pendiente').order_by('-articulo') pedido3 =Pedido.objects.filter(especialidad=especialidad).filter(estado='entregado').order_by('-articulo') for ped in Pedido.objects.filter(especialidad=especialidad): if request.method == 'GET': form = PedidoEditForm(instance=ped) else: form = PedidoEditForm(request.POST, instance=ped) if form.is_valid(): form.save() return HttpResponseRedirect('/solicitar/lista_active/%s/' % id_especialidad) return render(request, 'ingresa.html', {'form':form, 'pedido':pedido, 'pedido2':pedido2, 'pedido3':pedido3, 'especialidad':especialidad}) form.py: class PedidoEditForm(forms.ModelForm): cantidad = forms.IntegerField(widget=forms.TextInput(attrs={'multiple': True})) class Meta: model = Pedido fields = [ 'cantidad', ] template with table: <form id="myform" method="POST"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> </tr> </thead> <tfoot> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td><input type="submit" class= "btn btn-primary" value="Guardar"></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> <td>{% csrf_token %} {{ form.as_p }}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> Help me please, I have arrived like 5 hours and I can not do it, thank you. -
What's the difference between "virtualenv" and "-m venv" in creating Virtual environments(Python)
Sorry if I sound a bit foolish. I'm confused about this what's the difference between the two virtualenv myvenv and -m venv myvenv The first one works well for me in creating virtual environments while the other does not. I CD into my development directory and use "virtualenv myvenv" and it creates the virtual environment. But if I use "-m venv myvenv" it just gives errors. Please help me understand -
Django HTML5 audio tag do not work properly in Safari
I've created simple index.html file in some local folder with content: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <audio controls> <source src="example.mp3" type="audio/mpeg"> </audio> </body> </html> Everything works and looks fine in any browser. In Safari: But when I do exactly the same page in Django using TemplateView: url(r'^$', TemplateView.as_view(template_name='base.html'), name='base'), I get: It works - audio plays, but no progress bar, time remaining, etc. So, the only difference is that Safari via Django does not determine audio file duration and treats it like Live Broadcast. I guess that some http header should be passed somewhere, but it is just guesses Static files serves by Django in DEBUG = True Everything is fine in Chrome, FF and Opera (both in local and django files) Safari version: 10.1.1 (Latest for now) Django version: 1.11.1 (Latest for now) -
How to link HTML Website completely to Django?
I have a website with 1 database containing Login Sigup and Post Info fields. I want to connect the complete website to Django for easier access of information among my team mates. How can I completely convert it? I mean, How can I connect the database, HTML pages, along with Django Admin page for various blog post.? -
Django Form errors not displaying in template
I'm using Django 1.11. I have a form with validation methods, which correctly raise ValidationErrors. When a form is submitted invalid, form.error_messages get filled as expected. However when I want to display errors in template, both form.non_field_errors and form.[field].errors are all blank. Do I need to do anything extra to be able to use these? I'm kinda confused because this always "just worked" for me. I've read Django documentation on forms through and through as well as related SO questions and nothing helped. Thanks for any advice. PS. I know I could use Django-included PasswordChangeForm and a respective view. I have my reasons that are not obvious from the code below. Thanks. forms.py class PasswordChangeForm(forms.Form): prefix = 'password_change' error_messages = { 'password_mismatch': "The two password fields didn't match.", 'password_incorrect': "Your old password was entered incorrectly. Please enter it again.", } old_password = forms.CharField( label="Old password", strip=False, ) new_password1 = forms.CharField( label="New password", strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label="New password repeated", strip=False, ) field_order = ['old_password', 'new_password1', 'new_password2'] def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) … -
Change get_fields based on the value of the field on django admin
The problem is that I need to change the fields in get_fields based on what values are in other fields, change the display of fields based on the state of a particular model. I know that I have 4 methods: save_model() response_add(), response_change(), get_fields(), but I do not know in what order and how to use them correctly. By example: fields = super(MyModelAdmin, self).get_fields(request, obj) if user.status == 'NEW': fields.remove('username') return fields Is it correct? If so, in which of the methods is it used? -
Django app deploy on Heroku with DEBUG=False Server Error 500
I have an app deployed to Heroku. It runs fine both locally and on Heroku with "DEBUG = True". However, when I run it on Heroku with "DEBUG=False" I get a Server Error 500 like so: 2017-05-20T22:00:26.864342+00:00 heroku[router]: at=info method=GET path="/plans/planslist/" host=app.mysite.com request_id=b9a4de90-4a81-42ff-b936-59aa3d17e02e fwd="50.181.204.79" dyno=web.1 connect=0ms service=443ms status=500 bytes=253 protocol=http 2017-05-20T22:00:27.304092+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=app.mysite.com request_id=b24922e4-974a-45db-8ce0-def179602203 fwd="50.181.204.79" dyno=web.1 connect=1ms service=57ms status=500 bytes=239 protocol=http I must have a setting wrong but cannot figure it out. Any help would be greatly appreciated. I've hacking on this for half the day and have gotten no where. My settings.py import os from django.conf import settings from .base import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DEBUG = False TEMPLATE_DEBUG = False import dj_database_url DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } ALLOWED_HOSTS = ['app.mysite.com'] INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.humanize', 'bootstrap3', 'company_account', 'company_data', 'plans', 'django.contrib.admin', 'registration', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # Usual Middleware here WSGI_APPLICATION = 'mywebapp.wsgi.application' STATIC_URL = '/collectstatic/' STATIC_ROOT = 'staticfiles' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'