Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - How to get location through browser IP
I have a really basic django app to get weather. I need to get user's location to show them their current location's weather. I am using GeoIP for that. But an issue has come up that GeoIP does not have information of all the IP addresses. It returns NoneType for those IP addresses. I want to know if there is any other precise way by which I can info about User's current latitude and longitude, like maybe browser API? It should not miss any User's location like GeoIP does. -
Creating user views using django admin functionality
i'm wondering what is the right way of extending django admin functionality. I mean i've some table in admin site and it has a pretty looking style table as well as sortable columns by clicking on the table header and all i want is to extend that table appearance in user view but making it read only. It would be nice if i could have authentication functional available. -
annotate second minimal value in django ORM
I have two classes: Subject and Visit (where visit has a subject field) When performing retrieving of Subject data I can add field (annotate objects) with additional min/max data from related tables like: Subjects.objects.annotate(min_date=Min('visit_set__datetime_begin')) I would like to do similar thing but with second to the lowest value. Is it possible without iterating over all elements or executing custom SQL? -
Connection refused on socket.connect (Django app deployed on uWSGI + Nginx)
I have a Django application deployed on a VM using uWSGI & Nginx setup. I would like to print some data, by passing the required information to a printer that is configured on the same network using a socket: printer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) printer_socket.connect(('10.125.125.2', '9001'])) printer_socket.send(bytes(source='data', encoding='utf-8')) Note: the IP address and the port are here for illustration purposes. Problem: I get a Err 111 Connection refused error, however. The error is triggered at the printer_socket.connect step. Additional information: The python code that initializes the socket, connects to the required IP address/Port and sends the data works fine when it's run from the python interactive shell. Question: What do I need to configure in order to allow opening sockets from a django web application, deployed using uWSGI and Nginx? Please keep in mind that the configuration of the project is out of the scope of this question. I don't have troubles configuring the app. The app works fine. I am specifically interested in how to allow opening sockets from a web app, served using uWSGI + Nginx setup Thank you. -
django polimorphic StackedPolymorphicInline.Child and modeltranslation: how to set?
From the documentation example: class PaymentInline(StackedPolymorphicInline): """ An inline for a polymorphic model. The actual form appearance of each row is determined by the child inline that corresponds with the actual model type. """ class CreditCardPaymentInline(StackedPolymorphicInline.Child): model = CreditCardPayment class BankPaymentInline(StackedPolymorphicInline.Child): model = BankPayment class SepaPaymentInline(StackedPolymorphicInline.Child): model = SepaPayment model = Payment child_inlines = ( CreditCardPaymentInline, BankPaymentInline, SepaPaymentInline, ) How can I set inlines childs to be used with modeltranslation? -
Reuse Abandoned Django User IDs?
I have a new public-facing Django/PostgreSQL-based web site that requires users to create a new username/password and then fill out a profile that requires three more screens (forms) after the initial username/password page to complete their membership. As you would expect, I have a small number of users that don't complete the entire signup process leaving me with abandoned user IDs. Do either Django and/or PostgreSQL provide any convenient means of recovering and reusing these abandoned user IDs? -
How to deal with certain tags or characters in API to deal with XSS?
In django,i have a following serializer class test(serializers.Serializer): first_name = serializers.CharField(max_length=100, required=True) last_name = serializers.CharField(max_length=100, required=True) address = serializers.CharField(max_length=100, required=True) I want to stop the untrusted user from using(script tags OR alert(1233)) kind of things in some charfields since the rest API having above as a request serializer is going to be open. -
Django Localhost not loading static files
I have a working app and have downloaded the relevant django files locally (via git) and am trying to run the app locally. However, static files are not loading. I receive the following console error when accessing, say, the home page (http://localhost:8000/home/) of the app: GET http://localhost:8000/static/imported_JS/jquery/jquery.min.js net::ERR_ABORTED or this error: http://localhost:8000/static/globe.png 404 (NOT FOUND) In my settings.py file, I can confirm: BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)),'..')) # i.e. location of settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn/') I can also confirm there is indeed a static_cdn/ file directory and it does contain the relevant static files. The live dev and prod versions of the app work (which are hosted on separate web servers) but, for whatever reason, when running the app locally, static files are not served. Any ideas on how to have the localhost server static files? Most of the answers on SO regarding this type of question relate to mistakes with setting up STATIC_URL vs. STATIC_ROOT but these appear to be correct (at least on dev and prod). Let me know if you require more info. Thank you. -
Django allauth facebook authentication Incorrect Value
I have earlier created a Facebook app version 2.4 in my Facebook account and got the access token to get validated using Django allauth, this works fine, but if i create a new app in Facebook with version of 2.10 and try to validate the access token it shows "Incorrect Value". whether i need to update the plugin or any fix is available kindly help me. -
How to sort queryset output in view django?
I have these two models : class Home(db_interface.Entity): patient = models.ForeignKey(Patient, help_text='Patient') sode = models.ForeignKey(Sode, help_text='sode') class Sode(db_interface.Entity): start_date = models.DateField(validators=[validate_date_range], null=True, help_text="Start Date") path = models.ForeignKey('Path', null=True, blank=True) help_text="Path") and my view is inherited from a ListView of Django .To return a queryset I override get_queryset() method : def get_queryset(self): instance = self.get_instance() if instance: return Sode.objects.filter(patient=instance).select_related('path').prefetch_related( 'home_set') return [] to list data in my template I use a for loop : {% for h in sode.home_set.all %} data is displayed in lists perfectly, but what I want to do now is to filter the list (not the standard filter approach) I mean the items in the list will be modified depending of the status of some items . I tried to write a custom filter so that the every time my template is loaded I have data in the list are shown as I want. But I recognized that in my filter I used objects from database which must be in the view to separate presentation code from data logic, so filtering models musn't be in a filter I ended up by moving the logic I wrote in the custom filter to a function in my model's ListView … -
How to implement the SimpleMiddleware?
I am struggling getting MiddleWare to work. I put this in my settings.py: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'portal.middleware.SimpleMiddleware' ] and I implemented this class in portal/middleware/MiddleWare.py: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response But when running, I get a TypeError: TypeError: __init__() takes exactly 2 arguments (1 given) -
log a message in my terminal server (localhost:8000)
def clean_expired_requests(): now = datetime.datetime.now() qs = Request.objects.filter( expires_at__date=now, state__in=[ 'documents', 'validation', 'evaluation', 'signature']) for req in qs: log.debug('Request %s expired' % req) req.expired_at_state = req.state.name req.save() req.expire() EmailFromTemplate('expired-request').send_to(req.customer.user) I am working on a Django project with this method. I would like to insert something which will advise me that has been called. I thought it could write me a message in my terminal server 'clean_expired_request has been called!'. How could I do such thing? -
Simple Django Form
I'm trying to implement a Twitter-like follow system (one user can follow and be followed by many other users). I've tried a number of ways, but I keep getting errors. Currently, every time I drop debuggers or print statements throughout the form, I find that I don't ever get into the clean methods, nor is kwargs ever populated with values. I want to be able to pass in the follower & following as arguments to the Form and just assign them in the __init__ but everything is going wrong. When I get the response back in Javascript (React & Redux), all I'm getting is errors for both follower & following saying "This field is required." Here's what I've got so far: Models class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' class UserFollow(models.Model): follower = models.ForeignKey('User', models.CASCADE, related_name='follows') following = models.ForeignKey('User', models.CASCADE, related_name='followed_by') class Meta: unique_together = ('follower', 'following') def to_user(self): return { 'id': self.pk, 'follower': self.follower.pk, 'following': self.following.pk } Views def follow(request, id): following = User.objects.get(pk=id) form = UserFollowForm(follower=request.user, … -
How can I delete form field data in django after submit
I'm working on a django project where during registration, a user can submit a code to get special discounts. The validation of the discount codes is already working nicely, but I'm missing one beautifying aspect: After the user submits an invalid code I want to empty out the input field; i.e.: def validate_code(value): # check code for validity or raise ValidationError class CodeForm(forms.Form): code = forms.CharField(validators=[validate_code]) # in my views.py def code_verification_view(request): if request.method == 'POST': form = CodeForm(request.POST) if form.is_valid(): # proceed with given code else: # modify form to return an empty html input for the code field # this is where I'm stuck form.fields['code'].value = '' # ... render the form in a template The end result should be a form with an empty input field, but the validation errors showing. The behavior should be similar to how password input fields are emptied if the form verification fails. -
Django 1.11 error with change from views based in fuction to views based in class
I have a problem when I want change from views based in function to views based in class. I change the def index by class IndexView in my views.py and in my url.py I change url(r'^$',views.index, name="index"), by url(r'^$',IndexView.as_view(), name="index"), but all see correct, but I have a mistake because don't find IndexView My urls.py is the next: from django.conf.urls import url, include from . import views urlpatterns = [ #url(r'^$',views.index, name="index"), url(r'^$',IndexView.as_view(), name="index"), url(r'^panel/$',views.main_panel, name="panel"), url(r'^panel/evento/nuevo/$',views.crear_evento, name="nuevo"), url(r'^panel/evento/(?P<evento_id>\d+)/$',views.detalle_evento, name="detalle"), url(r'^panel/evento/editar/(?P<evento_id>\d+)/$',views.editar_evento, name=""), ] My views.py is the next: from django.shortcuts import render, redirect, get_object_or_404 from .models import Event, Category from django.views.generic.base import TemplateView from myapps.users.models import User from .forms import EventoForm from django.core.urlresolvers import reverse # Create your views here. def login(request): return render(request, "login.html", {}) #def index(request): # events = Event.objects.all().order_by('-created')[:6] # categories = Category.objects.all() # return render(request, 'events/index.html', {'events': events, 'categories': categories}) class IndexView(TemplateView): template_name = 'events/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['events'] = Event.objects.all().order_by('-created')[:6] context['categories'] = Category.objects.all() return context def main_panel(request): #organizer = request.user.username events = Event.objects.filter(organizer__username='').order_by('is_free', '-created') cantidad_eventos = events.count() return render(request, 'events/panel/panel.html', {'events': events, 'cantidad': cantidad_eventos}) def crear_evento(request): if request.method == 'POST': modelform = EventoForm(request.POST, request.FILES) if modelform.is_valid(): organizador = User.objects.get(pk=3) nuevo_evento = … -
Django REST ImageField default is absolute url?
Softwares: Python3.6.2 Django1.11 djangorestframework-jwt==1.11.0 djangorestframework==3.6.4 I can not get url from the Django REST when I am using it with jwt_response_payload_handler https://gist.github.com/elcolie/1e291af47aa7312ec7d06f76c91f797e Attempt: That keyword argument use_url=True does work with viewset, but it does not when I integrated to the customized jwt function. References: Django serialize imagefield to get full url -
How can i store the form values in csv using django instead of usind Database?
Name,Email (entered details from form values) Fields store in csv file using python django -
HTML File link - force download always
I have a Django view that renders a list of uploaded files, and the user can click on them to begin the download. When the project was deployed, we found there's one file that browsers open instead of download it. It seems related to the .dxf extension. This is how the link is created: <a href="{{ MEDIA_URL }}{{ file.url }}" target="blank">...</a> As a result: http://localhost:8003/media/folder/whatever.dxf So, why the same browser behaves differently? if I run it on localhost, then it downloads the file. But accessing the real server, it'd open it. Can I prevent the server to open them in browsers? -
Getting two letter language code from get_current_language
I am using Django internationalization and use the get_current_language call to get the current language. However, that is a language code plus region code (e.g. en-gb), while I only want the language code (e.g. en). How can I get just the two-letter language code? -
Django write in database when form is submit
i want to use html form to be able to send back information to my view.py, the goal is to get the data, use it as arguments in a call to a stored procedure. def mouvementCreation(request): idMI = 0 especes = TbEspece.objects.order_by('id') #Get Mouvement informations #Connection to 'erp-site' DB cursor = connections['erp-site'].cursor() try: #Get Produits list from Espece query = "{CALL SP_webGET_PRODUIT_FROM_ESPECE(%s,%s,%s,%s,%s)}" arguments = (2016, 'C', 0, 10, 'A',) cursor.execute(query, arguments) produits = dictfetchall(cursor) #Get Transporters list cursor.execute("{CALL SP_webGET_TRANSPORT}") transporters = dictfetchall(cursor) #Get Livreur list cursor.execute("{CALL SP_webGET_LIVREUR}") livreurs = dictfetchall(cursor) finally: cursor.close() cursor = connections['site'].cursor() try: #Get Circuit list cursor.execute("{CALL SP_webGET_CIRCUIT_FOR_MVT}") circuits = dictfetchall(cursor) #Get Source list cursor.execute("{CALL SP_webGET_SOURCE_FOR_MVT}") mvtsources = dictfetchall(cursor) #Get Dest list cursor.execute("{CALL SP_webGET_DEST_FOR_MVT}") destinations = dictfetchall(cursor) #Get PontBascule list cursor.execute("{CALL SP_webGET_PBASCULE}") pontBascules = dictfetchall(cursor) finally: cursor.close() reg_normes = TbRegauxnormes.objects.all() ordreexecs = TbOrdreexecution.objects.all() form = mouvementForm(request.POST or None) if form.is_valid(): pont = form.cleaned_data['pont'] dateheure = form.cleaned_data['dateheure'] poid = form.cleaned_data['poid'] dsd = form.cleaned_data['dsd'] typepesee = form.cleaned_data['typepesee'] #Connection to 'erp-site' DB cursor = connections['pontbascule'].cursor() try: #Get Produits list from Espece query = "{CALL SP_ADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s)}" arguments = (pont, '11', dateheure, poid, dsd,typepesee, '','','','','','','','','','','','','','','','') cursor.execute(query, arguments) finally: cursor.close() return render(request, 'mouvementCreation.html', {'form': form, 'especes' : especes, 'produits' … -
ImageField not uploading my pic in template
I have a problem with uploading an image to my template. Code below, project-tree screen too. If you will need anything to help me, write pls. project-tree screen (model) Here comes particular model with which I got the problem. class WorkingPlace(models.Model): company_name = models.CharField(max_length=100, default='') logo = models.ImageField(upload_to='img') location = models.CharField(max_length=200) from_date = models.DateField(blank=True, null=True) till_date = models.DateField(blank=True, null=True, default='now') def __str__(self): return self.company_name (view) def main_view(request): form = ContactMe(request.POST or None) if form.is_valid(): form.save() print('saved') return HttpResponseRedirect('CV/base.html') else: form = ContactMe() print('unsaved') hobbies_and_interests = HobbiesAndInterest.objects.all() personal_features = PersonalFeature.objects.all() skills = Skill.objects.all() letter = Letter.objects.get(id=1) working_places = WorkingPlace.objects.all() activities = Activity.objects.all() return render(request, 'CV/base.html', { 'form': form, 'hobbies_and_interests': hobbies_and_interests, 'personal_features': personal_features, 'skills': skills, 'letter': letter, 'working_places': working_places, 'activities': activities }) (settings) Static and Media settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "CV/../CV/../static"), ] STATIC_ROOT = 'WebCVDjangoI' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', "media") (template) Problem part of the template. {% for place in working_places %} <div class="row work-block"> <div class="col-md-1"> <i class="fa fa-bookmark" aria-hidden="true" style="font-size: 3em;"></i> </div> <div class="col-md-11 flex-around"> <img src="{{ place.logo.url }}" class="img-respomsive visible-lg-block visible-md-block visible-sm-block" style="width: 30%"> {{ place.logo.url }} <!--Mobile--> <img src="{{ place.logo }}" class="img-respomsive visible-xs-block" style="width: 50%"> <!--end--> <div style="width: 30%" class="text-center visible-lg-block … -
Importing data from multiple related tables in mySQL to SQLite3 or postgreSQL
I'm updating from an ancient language to Django. I want to keep the data from the old project into the new. But old project is mySQL. And I'm currently using SQLite3 in dev mode. But read that postgreSQL is most capable. So first question is: Is it better to set up postgreSQL while in development. Or is it an easy transition to postgreSQL from SQLite3? And for the data in the old project. I am bumping up the table structure from the old mySQL structure. Since it got many relation db's. And this is handled internally with foreignkey and manytomany in SQLite3 (same in postgreSQL I guess). So I'm thinking about how to transfer the data. It's not really much data. Maybe 3-5.000 rows. Problem is that I don't want to have same table structure. So a import would be a terrible idea. I want to have the sweet functionality provided by SQLite3/postgreSQL. One idea I had was to join all the data and create a nested json for each post. And then define into what table so the relations are kept. But this is just my guessing. So I'm asking you if there is a proper way to do … -
Uploading Files in django-admin
I am making a project in django where only the admin will be having the permission to upload files. How can i modify the admin page so that option to upload files is only visible to admin? currently it is looking something like this.. But i want an upload files option also below add choice actionenter image description here -
Cannot "open" notification that is received when the app is in background
i have a problem when i want to process notification that is received when the app is in the background. I do receive the notification, when i click on the notification, the app opens however the FCM.on method is not executed at all, it seems it does not handle the callback. When the app is in the foreground everything is working fine, and it process the notification without any problems. This is the code in react-native FCM.on(FCMEvent.Notification, notif => { switch(notif.fcm.action){ case 'fcm.ACTION.HANDLEMESSAGE': var data = { thread: notif.pk, message: JSON.parse(notif.message) } this.props.dispatch(fcmMSG(data)); this.props.dispatch(addNotification(notif.pk, notif.job_id)); break; case "fcm.ACTION.HANDLEAPPLICATION": axios.get(newServerURL + "/jobs/companyJobDetails/" + notif.recruitJobId + "/") .then((response) => { var jobMainRecruits = response.data; const {navigator} = this.refs; navigator.push({ jobMainRecruits, }); }) .catch((error) => { console.log("ERROR") }); break; default: } }); EDIT: this is my code in the backend push_service = FCMNotification(api_key=FCM_API_KEY) registration_id = token.token message_title = jobInfo.title message_body = "New application" message_icon = 'ic_launcher' sound = 'Default' color = '#362F64' click_action='fcm.ACTION.NEWJOBAPPLICATION' data_message = {'recruitJobId': self.request.data['job'], 'message_title': message_title, 'message_body': message_body} result = push_service.notify_single_device(click_action=click_action, registration_id=registration_id, message_title=message_title, message_body=message_body, message_icon=message_icon, sound=sound, data_message=data_message, color=color) Thanks for help in advance. -
Date format changes on UpdateView in Django
I have a form to create an object where the date input format is 'dd/mm/yyyy', when I submit the form, it is saved without any problem, but when I edit this object, the date shows as 'yyyy-mm-dd'. settings.py DATE_INPUT_FORMATS = ('%d/%m/%Y') forms.py class MyForm(forms.ModelForm): created_date = forms.DateField(input_formats=['%d/%m/%Y',], widget=forms.DateInput(attrs={'class':'datepicker form-control', 'placeholder':'Select a date'}), required=False) models.py created_date = models.DateField(blank=True, null=True, verbose_name="Created on") views.py class MyEdit(SuccessMessageMixin, UpdateView): model = MyModel form_class = MyForm template_name_suffix = '_edit' success_message = '...' and in my template I use $(".datepicker").datepicker({ format: 'dd/mm/yyyy', autoclose: true, changeYear: true, changeMonth: true });