Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF validation fails
I am using django 1.10. I have {% csrf_token %} in my forms where POST is been used. I am using django registration redux for handling the registration process. While trying to register a new user, I get a 403 error CSRF VERIFICATION FAILED. REASON for failure CSRF cookie not set. CSRF_COOKIE_SECURE is set to false. This are the middleware clases 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_user_agents.middleware.UserAgentMiddleware', ] -
Best way to call api url x times
I'm doing a little project in django where I connect to one or more Firewall to change some protocols or just look for the status of the machine. Connect to one Firewall it's easy, I just call the api in the views.py. But if I have 3 Firewalls I want to connect to each one of them to apply the same changes at once, which is the best way to call the api 3 times? I thought a for each would do the trick but it doesn't seem really clean to me. Anyone knows another method? Thanks a lot. -
Django: MakeValid not working for a single object
I'm trying to use MakeValid for fixing my geometry fields. I can make it work by getting and updating in single line: from django.contrib.gis.db.models.functions import MakeValid MyModel.objects.filter(id=<id>).update(the_geom=MakeValid('the_geom')) but for some cases, I've to update polygon of a single object already existing in function (means I need not to do .filter/.get) which gives me an error. // np is an object of MyModel which has a field 'polygon' np.polygon = MakeValid(np.polygon) // np.save() TypeError: Cannot set MyModel SpatialProxy (MULTIPOLYGON) with value of type: <class 'django.contrib.gis.db.models.functions.MakeValid'> What am I doing wrong? -
How to add extra fields to django registration form?
I have a registration form which generates in view. Now I need to added some fields from other model. How should I change view to add fields from another model? Here is my view code: def register(request): """ User registration """ if auth.get_user(request).username: return redirect('/') context = {} context.update(csrf(request)) context['form'] = UserCreationForm() if request.POST: newuser_form = UserCreationForm(request.POST) if newuser_form.is_valid(): newuser_form.save() newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2']) auth.login(request, newuser) return redirect('/') else: context['form'] = newuser_form return render(request, 'user_auth/user_auth_register.html', context) -
how to log a file in Django
I have this function in views.py ( related to contact form). I need to log all the inputs and output to a temporary file, but i don't know how to do it in django. The function in views.py : def contact(request): form = FeedbackForm(request.POST or None) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.urlencode(values).encode() req = urllib2.Request(url, data=data) response = urllib2.urlopen(req) result = json.loads(response.read().decode()) ''' End reCAPTCHA validation ''' if result['success']: form.save() message = u'You have feedback\nName: %s\nEmail: %s\nPhone: %s\nCountry: %s\nFeedback:\n%s' % ( self.cleaned_data.get['name'], self.cleaned_data.get['email'], self.cleaned_data.get['phone'], self.cleaned_data.get['country'], self.cleaned_data.get['feedback']) try: send_mail('NEW FEEDBACK', message, '', settings.DEFAULT_FROM_EMAIL) # to admin send_mail('THANK YOU for contacting us', 'We will be back to you promptly.', '', [self.cleaned_data.get['email'],]) # to user messages.info(request, 'SUCCESS! Your message has been sent!') form = FeedbackForm() except: messages.info(request, 'Sorry, can\'t send feedback right now.') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') else: form = FeedbackForm() return render(request, 'contact.html', {'active_page':'contact','form': form,}) I viewed this page on google, but i don't know how to do it : https://docs.python.org/2.3/lib/node304.html -
Every once in a while I see users having issues to update due to errors like this:
E: Type 'See' is not known on line 3 in source list /etc/apt/sources.list E: The list of sources could not be read. -
Django: set ManyToMany field initially empty in model create form
I have following models: class Robject(models.Model): project = models.ForeignKey(to=Project, null=True) author = models.ForeignKey( to=User, null=True, related_name="robjects_in_which_user_is_author") name = models.CharField(max_length=100) create_by = models.ForeignKey( to=User, related_name="robjects_created_by_user", null=True) create_date = models.DateTimeField(null=True) modify_by = models.ForeignKey(to=User, null=True) name = models.ManyToManyField( "Name", related_name="robject_name", help_text='The name of robject' ) class Name(models.Model): name = models.CharField(max_length=100) primary = models.BooleanField() I want to create a form where user can create new Robjects. I want this form works the same as Robject create form in admin page. It means I want to have 'plus' button next to 'name' select multiple input, that user can click and create new Name in window popup form. After Name creation popup closes and user can see new Name in select input. My problem is that user shouldn't see any already existing Name objects created during other Robject creation attempts. When he wants to create new Robject, select multiple Name input should be empty from the beginning. I'm using django-addanother to imitate admin form in my own form. This is how form looks: class RobjectForm(forms.ModelForm): class Meta: model = Robject fields = '__all__' widgets = { 'name': AddAnotherWidgetWrapper( forms.SelectMultiple, reverse_lazy('add_name', args=['proj_1']), ), } I will be gratefull for any ideas how to solve my problem. -
Custom Django command implement Scheduled job
Problem I've been looking how to implement an scheduled job in Django and found out that this question suggests many options: Django - Set Up A Scheduled Job?. How ever none of them is given an example. The most supported option suggest to add a custom command in Django in which implement a cron (Linux) or at (Windows) task. No big deal as there are available examples of both creating custom django command and cron/at tasks. My problem is that I want to execute the cron/at task just at the start of the application (when python manage.py runserver is invoked). I'm considering to use cron as I'm developing a small application. Questions: Should I call this command in my new custom command python file and then execute the cron/at task? It's better to just add the cron/at task in the new custom command and when starting the application use both commands as follow: python manage.py runserver && python manage.py cron/at_task.py? Is there a way to specify runserver to run a custom python script, in which add the cron/at task? -
How to zip 2 different length array so that can loop in django loop?
I have 2 arrays: First array: ['Tan','Goh','Tio'] Second array: [['Honda','Toyota','Proton'],['Toyota'],['Proton','Lambo']] How to zip this 2 arrays so that when i apply this code: {% for i in loop_times %} {{i|safe}} {% endfor %} So,the out put will be like this: <li> <a href="#"> <span class="ca-icon">Tan</span> <div class="ca-content"> <h3 class="ca-main">Honda</h2> <h3 class="ca-sub">Toyota</h3> <h3 class="ca-sub">Proton</h3> </div> </a> </li> <li> <a href="#"> <span class="ca-icon">Goh</span> <div class="ca-content"> <h3 class="ca-sub">Toyota</h3> </div> </a> </li> <li> <a href="#"> <span class="ca-icon">Tio</span> <div class="ca-content"> <h3 class="ca-main">Proton</h2> <h3 class="ca-sub">Lambo</h3> </div> </a> </li> Anyone can share me idea? I have study this https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ but I still not able to understand, can anyone give some ideas ? -
Accessing dictionary by dynamic key in Django template
From views.py I have: def do_something(request, context, template="index.html"): .... type = ['A', 'B', 'C'] map = {'A': 'a', 'B': 'b', 'C': 'c'} context['type'] = type context['map'] = map return (request, template, context) And in the template I would like to access to play with value in map like this: </html> .... {% for t in type %} {% with m = map[t] %} {% endwith %} // do sth {% endfor %} But I got TemplateSyntaxError: Could not parse the remainder: '[t]' from 'map[t]' Anyone please help me, thanks so much. -
How to minimize database query in DjangoREST Serializer
car/models.py class CarData(AbstractSoftModelController, AbstractDataType): ... license_plate = models.OneToOneField(LicensePlate, related_name='car_data', verbose_name=_('License plate')) ... license/models.py class LicensePlate(AbstractSoftModelController, AbstractDataType): hiragana_prefix = models.CharField( max_length=50, db_index=True, verbose_name=_('Hiragana prefix'), null=True, blank=True ) vehicle_class_number = models.CharField( max_length=100, db_index=True, verbose_name=_('Vehicle class number'), null=True, blank=True ) regional_code = models.CharField( max_length=50, db_index=True, verbose_name=_('Regional code'), null=True, blank=True ) serializers.py class MailLogOrderCarSerializer(serializers.ModelSerializer): hiragana_prefix = serializers.SerializerMethodField() vehicle_class_number = serializers.SerializerMethodField() regional_code = serializers.SerializerMethodField() class Meta: model = CarData fields = ('brand', 'model', 'license_plate') def get_hiragana_prefix(self, obj: CarData): return obj.license_plate.hiragana_prefix def get_vehicle_class_number(self, obj: CarData): return obj.license_plate.vehicle_class_number def get_regional_code(self, obj: CarData): return obj.license_plate.regional_code Question How do I optimize my serializer? Hit database 3 times for single instance is not good. Suppose I query 500 cars. Then it will hit 1500 times which is considerable big performance issue for me. -
Django Tutorial - choice_set typeerror
So I was looking at this post to try and resolve some issues encountered in my Django tutorial: TypeError: 'choice_text' is an invalid keyword argument for this function in django tutorial I'm still facing exactly the same problem after taking the suggested solution of changing "choice_text" to "choice" - i.e exactly the same error message, and the documentation version for the Django tutorial is for Django 1.11 (my version). Does anybody know the correct syntax for creating choice sets? Thanks! -
How to set permission as per user using Django and Python
I need to some help. I need to set permission as per registered user using Django and Python. I have done something but confused whether it is fulfilled my requirement or not. I am explaining my code below. class Control(models.Model): """docstring for Control""" user_id = models.ForeignKey(User) control_reactor = models.IntegerField(default=0) find_reactor = models.IntegerField(default=0) view_reactor = models.IntegerField(default=0) class Meta: """docstring for Meta""" permissions = ( ("view_reactor", "can view reactor"), ("find_reactor", "can find reactor"), ("controll_reactor", "can controll reactor"), ) I am access those permission using Django decorator function like @permission_required. Here I need as per user I will set the 3 permissions but confused that this model class is doing as per requirement. Please help me. -
Run process when django server shut down
I run a Django Web Server by Python 3 with a Raspberry Pi. During the common business i use some RPi.GPIO commands (set Pin to GPIO.HIGH and GPIO.LOW). When I restart the Django Server I receive a warning, that some Pins are used. It is possible to ignor this warning, but I strongly believe, that ignoring the warning is not a good practice. Is it a good solution to ignor the warning? Is it possible to run a proces after the shut down process has been finished, to run RPi.cleanup()? Is it possible to run th RPi.cleanup()or an other process before the server runs, or in the ready() method at the apps.py file? -
How to serve media files?
I have an Django application and I trying deploy this, but I have problem, in this moment I can see my media files because I add media and static into urls.py (as must be done in development), but I trying change to production mode and I use nginx, but I don't understand how to server my media files with nginx, I have configured nginx this way server { listen 80; server_name 54.175.254.152 location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/tracker-web/trackerServer; } location /media/ { alias /home/ubuntu/tracker-web/trackerServer/media/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/tracker-web/trackerServer/trackerServer.sock; } } Before I only use /static/ and all works fine, but I don't understand how to use the same way my media folder to serve files, I want to clarify that I use as an angular 2 interface , so I do not use Django templates, and also use gunicorn. -
Django Administration remove or hide entire header
in my project i would to remove or hide the entire djando administration header bar I try to define in my custom base_site.html the {% block extrahead %} like this: {% block extrahead %} <style type="text/css"> #header #branding h1{ background: None; // here you remove the django image } </style> {% endblock %} but nothing happens Anyone have an idea about? Thanks in advance -
Single Page Application Web crawlers and SEO
I have created my blog as a single page application using mithril framework on the front end. To make queries I've used a rest API and Django at the backend. Since everything is rendered using javascript code and when the crawlers hit my blog all they see is an empty page. And to add to that whenever I share a post on social media for instance all Facebook sees is just an empty page and not the post content and title. I was thinking of looking at the user agents and whenever the USER-AGENT is from a crawler I would feed it the rendered version of the pages but I'm having problems implementing the above method described. What is the best practice to create a single page app that uses rest API and Django in the backend SEO friendly for web crawlers? -
Alternative for django.db.close_connection()
Is there a possible way to re-establish Mysql connection in Django after it goes down? I am getting the following error while trying to access Mysql using the get_wsgi_application in django.core.wsgi: (2006,'MYSQL server has gone away') -
Multilevel display for a model in Django admin
I have a model as follows : class Transaction(models.Model): transaction_id = models.AutoField(primary_key=True) transaction_unique_id = models.CharField(max_length=100, null=True, blank=True, unique=True) route_id = models.ForeignKey(FlightScheduleDetail, null=False, blank=False) flight_number = models.ForeignKey(FlightNumbers, null=False, blank=False) device_id = models.ForeignKey(DeviceInfo) crew_code = models.ForeignKey(Crew) time_of_transaction = models.TimeField() total_quantity = models.IntegerField() manually_added_flag = models.BooleanField(default=False) seat_number = models.CharField(max_length=200, null=True, blank=True) transaction_type = models.CharField(max_length=200) reason_code_id = models.ForeignKey(ReasonCode, null=True, blank=True) total_amount = models.FloatField() amount_by_card = models.FloatField(null=True, blank=True) payment_mode_id = models.ForeignKey(PaymentMethod, null=True, blank=True) transaction_date = models.DateField(null=True, blank=True) created_at = models.DateTimeField(null=True, blank=True) def __unicode__(self): return u'%s' % self.transaction_unique_id class Meta: verbose_name_plural = "Post Flight Transaction" In my admin, I need a customization which displays all the route_id values from the model and when I click on one route_id , it displays all the transaction_date values and under them, it displays all the transaction_id values and when I click on one entry , in this level, I need to display its edit screen. Basically I need a folder like implementation for a model. I need to group and display all the entries. I googled for the same, but could not find any solution. Is this even possible in django? Please help. -
Android client consumes API returns bad request
I am currently learning django and android. I created a REST API for my backend. The endpoints are working since I can GET/POST with Postman, Insomnia, and httpie. However, if I try it with my android app it gives the response 'Bad Request'. I've been working on it for many hours now. Could someone explain to me why is this happening? ![1]: http://imgur.com/a/NF1oY ![2]: http://imgur.com/a/UG06U -
React Native app fails to reach endpoints on python virtualenv, but succeeds with global python env
I had been building my React Native app for a long time using a global python environment, which I know is bad form, so I decided to create a virtualenv. But now when I activate the virtualenv and run the server, none of my api endpoints are reachable (I'm using django btw). Instead, the network call doesn't return for a very long time and then comes back with the error "Network Request Failed". But if I deactivate the virtualenv and go back to global python and run the server, everything works fine. I've seen this "Network Request Failed" error before during times where I've forgotten to turn the server on, so I know it indicates that the server is unreachable. Here's one last weird aspect though. If I activate the virtualenv and turn on the server and then type the url to an endpoint into the browser, it successfully reaches the browsable django api for the endpoint. So it seems to be set up fine except that the app for whatever reason can't communicate with it. Very bizarre. -
How to display data label on top of nvd3 multi bar chart?
I tried a few different methods I found online. For example, the one below and "showValues". However, none of these actually work. Can someone provide an example of how to do this properly? d3.selectAll('.nv-multibar .nv-group').each(function(group){ var g = d3.select(this); // Remove previous labels if there is any g.selectAll('text').remove(); g.selectAll('.nv-bar').each(function(bar){ var b = d3.select(this); var barWidth = b.attr('width'); var barHeight = b.attr('height'); g.append('text') // Transforms shift the origin point then the x and y of the bar // is altered by this transform. In order to align the labels // we need to apply this transform to those. .attr('transform', b.attr('transform')) .text(function(){ // Two decimals format return parseFloat(bar.y).toFixed(2); }) .attr('y', function(){ // Center label vertically var height = this.getBBox().height; return parseFloat(b.attr('y')) - 10; // 10 is the label's magin from the bar }) .attr('x', function(){ // Center label horizontally var width = this.getBBox().width; return parseFloat(b.attr('x')) + (parseFloat(barWidth) / 2) - (width / 2); }) .attr('class', 'bar-values'); }); }); -
Incomplete validation message when request body is blank
This is my model: class Profile(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=20, blank=True, null=True) designation = models.CharField(max_length=50, blank=True, null=True) roles = models.ManyToManyField(Role, related_name="profiles") and this is the serializer: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) full_name = serializers.CharField(max_length=60, write_only=True) phone = serializers.CharField( max_length=20, allow_blank=True, required=False, write_only=True) designation = serializers.CharField( max_length=50, allow_blank=True, required=False, write_only=True) roles = serializers.MultipleChoiceField( choices=models.Role.objects.values_list('id', flat=True), write_only=True) class Meta: model = User fields = ('id', 'email', 'full_name', 'phone', 'designation', 'roles') Problem All requests are sent with Content-Type: application/json When I POST a request with an empty payload, DRF raises a 400 (with incomplete required fields) { "full_name": [ "required" ], "email": [ "required" ], } When the POST request body is {}, DRF raises 400, with all mandatory fields { "full_name": [ "required" ], "email": [ "required" ], "roles": [ "required" ] } Question How can I ensure that if the request body is blank, DRF raises a ParseError? Already tried Adding allow_blank and required to roles in UserSerializer has no effect. There is no inconsistency when I test it using APITestCase. I can reproduce the error through ARC. Workaround Added a custom exception handler that checks for this: request = context['request'] if request.content_type == 'application/json' and type(request.data) … -
Convert String object to file object for use of chunks()
Error: 'str' object does not have attribute chunks() This is a part of my views.py, What i am trying to achieve is that, i want to unzip an uploaded zip file. I will explain you my code step by step. 1) The code takes a file(newfile) and checks if the extension(fileparts[-1]) is 'zip' if yes then it unzips the file, and iterates over the contents. 2) The function formatFileName does nothing but converts the filename to lowercase and does rpartition on ('.'). 3) Now the next part is of making versions of the attachment or uploaded file which is the try and except part( dont give much importance as its complicated ) 4) the last part which is handle_uploaded_file which is below takes the file and writes it in chunks. Now the issue is that the variable file_new is a str and chunks() only works on file object, so is there any way I can convert the string to file object so that the file can be written correctly? if 'addfilebutton' in request.POST: newfile = request.FILES.get('newfile') if newfile: fileparts = formatFileName(newfile.name) if fileparts[-1] == "zip": x = zipfile.ZipFile(newfile) y = x.namelist() for file in y: file_new = file.split('/', 1)[-1] fileparts … -
How to understand the files in a PyCharm project?
How to understand the files in the PyCharm project? As the snapshot shows, there are so many files: 1) Type-1, with .start: .eslintignore, .eslintrc, .gitignore, .gitreview... 2)Type-2, .cfg files: babel-django.cfg, babel-djangojs.cfg 3)Type-3, .rst files: CONTRIBUTING.rst, HACKING.rst 4)Type-4, Makefile 5)Type-5, MANIFEST.in 6)Type-6, package.json 7)Type-7, requirements.txt 8)Type-8, setup.cfg 9)Type-9, setup.py What does these files means? what function do them have?