Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django widget tweaks popover won't move with content
I'm using django widget tweaks to render a form field that is required. It all works fine, if the field is blank, I see a cute little popover that says field is required and all that, but if I scroll the page (the form is a little big), the popover won't move with the form field. It'll stay put and that is not good. Here's my code: {% load widget_tweaks %} {{form.order_number.label}} {% render_field form.order_number required="true" %} Also, this is happening only on Firefox, not on Chrome. I'm on Firefox 57.0. Here's a screenshot to help. In Pic1, you'll see it is supposed to be where I like it without scrolling. In Pic2, it has gone way upwards to the top of the div when I scroll up. Could someone please explain why this is happening and how I can fix it? -
"AnonymousUser" Error When Non-Admin Users Log In - Django
When I try to login users registered through my AbstractBaseUser model I get the error: 'AnonymousUser' object has no attribute '_meta' Which highlights the code: login(request, user) However, if the user is an admin there is no problem, leaving me to believe that the problem isn't with the 'login_view', but a problem with how the user is tagged (so to speak) when they are registered with AbstractBaseUser. Any help would be much appreciated! Here is my code: Models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_admin=False): if not first_name: raise ValueError("Users must enter their first name") if not last_name: raise ValueError("Users must enter their last name") if not email: raise ValueError("Users must enter an email") if not password: raise ValueError("Users must enter a password") user_obj = self.model( first_name = first_name, last_name = last_name, email = self.normalize_email(email), ) user_obj.set_password(password) #set and change password? user_obj.admin = is_admin user_obj.staff = is_staff user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_superuser(self, first_name, last_name, email, password=None): user = self.create_user( first_name, last_name, email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) … -
Celery + django - pdf generator
I have some question, how to catch pdf file witch I generate in tasks.py and start download it automaticly after redirect to home page and put the download link to this page? My task.py work because I see the result in terminal. My tasks.py: @shared_task def html_to_pdf(ctx): html_string = render_to_string( 'pdf_template.html', ctx) html = HTML(string=html_string) html.write_pdf('/tmp/report.pdf') fs = FileSystemStorage('/tmp') with fs.open('report.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] \ = 'attachment; filename="report.pdf"' return response My views.py: class PdfCreatorView(View): def get(self, request): form = PdfForm return render(request, 'home_page.html', {'form': form}) def post(self, request): form = PdfForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] date_of_generation = form.cleaned_data['date_of_generation'] pdf_text_content = form.cleaned_data['pdf_text_content'] pdf_numbers_content = form.cleaned_data['pdf_numbers_content'] ctx = {'name': name, 'date_of_generation': date_of_generation, 'pdf_text_content': pdf_text_content, 'pdf_numbers_content': pdf_numbers_content} html_to_pdf.delay(ctx) url = reverse('home_page') return HttpResponseRedirect(url) -
Django: Uploading files using a validator but without using a database/table
I'm trying to use a really simple upload form with a validator to check the file extension. But when I try to upload something I get the error "OperationalError at /upload/ no such table: mysite_document" I don't need a table though, I just need to allow people to upload files. I read that putting "managed = False" into the model class will stop it doing this but I still keep getting this error. Can anyone tell me where I'm going wrong? -
Raise Validation Error Instantly in Django Forms
I am working with a ModelForm that looks like this: class TestForm(forms.ModelForm): class Meta: model = TestModel fields = ('name', 'description', 'date') widgets = { 'execution_date': forms.DateInput(attrs={'type': 'date'}), } What I' m hoping to do is look at the date field and make sure it is today's date or a future date before submitting the form, the same way an EmailFieldraises and error instantly if you enter an address without the @ sign and try to move on. Normally I'd let the user hit submit, then check the date and return the form if things don't look right, however I am working with stripe and the submit button actually triggers a Stripe check out then validates the form which would charge the customer twice if they had en error. Any ideas on how I can solve this? -
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited
I have the models "Software" , "Company". >>> Software._meta.get_fields() (<ManyToManyRel: newapp.company>, <django.db.models.fields.AutoField:id>, <django.db.models.fields.CharField: name>) >>> Company._meta.get_fields() (<django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: name>, <django.db.models.fields.related.ManyToManyField: product>) I've created the following objects: >>> c3=Company.objects.create(name='Oracle Corporation') >>> s3=Software.objects.create(name='Oracle Database') When I add a Software instance to a Company object, it is ok. >>> c3.product.add(s3) >>> Company.objects.all() <QuerySet [<Company: JetBrains (PyCharm)>, <Company: Apple (iOS)>, <Company: Oracle Corporation (Oracle Database)>]> However, I tried to get the same result in other way. And I got the following error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use product.set() instead. How to use product.set() in order to get the same result shown above? -
Django permission to create a folder when being served by Apache2
I am serving a Django site using Apache2 and mod_wgsi on a Debian 8 machine. I have correctly set the permissions to access the database and static file directories and the directory my_site/media. However, the site needs to create a directory in my_site/media (i.e. my_site/media/another_directory) and I can't seem to give apache2 permission to do this. The permission for media are: drwxrwxrwx 2 scamp www-data 4096 Jan 10 03:09 media The Django error I get is Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'media/new_folder' This is my django.conf: Alias /robots.txt /home/scamp/trcalc_django/static/robots.txt Alias /favicon.ico /home/scamp/trcalc_django/static/favicon.ico Alias /media/ /home/scamp/trcalc_django/media/ Alias /static /home/scamp/trcalc_django/static <Directory /home/scamp/trcalc_django/static> Require all granted </Directory> <Directory /home/scamp/trcalc_django/media> Require all granted </Directory> WSGIScriptAlias / /home/scamp/trcalc_django/wsgi.py <Directory /home/scamp/trcalc_django> <Files wsgi.py> Require all granted </Files> </Directory> Is there something else I need to put in the apache conf? or some other permissions that need to be set? -
Django ListView inserting blank <li> after each element
I am new to Django and trying to grasp why or how to mitigate the extra <li> and have not found anything yet. Here is an image of what the output is doing.li elements And here is a snippet of my template: template -
Any good examples of an open source news site / project built on Wagtail
Complete django / wagtail beginner here working to build a news platform. Does anyone know of good examples I can use as a reference point for a project like this? All I have ever built is a personal blog so I'm not entirely sure how to go about structuring things like my apps and whatnot. -
How to deal with CMS style HTML fields and malformed HTML
I have a text field on my django site that allows certain users to insert HTML and text, and I want to make sure that the inserted text does not mess with the code outside of the div that contains the text. For instance if I accidentally specify " without and open tag I wouldn't want the textfield to malform/escape out of the parent div. What is the best way to deal with this? I want to continue to allow full HTML on this field at the moment as I only use it personally to create posts. -
Django: When to use model fields and when to use reverse queries.
I have a question regarding best practices with Django models. I have webscraper running that indexes both 'Ads', 'Sellers' and 'Searches'. A (simplified) representation of these models would look like this: class Search(models.Model): date: models.DatetimeField(auto_now=True) class Seller(models.Model): name: models.CharField(max_length=500) profile_url: models.CharField(max_length=500) class Ad(models.Model): title: models.CharField(max_length=500) price: models.FloatField() seller: models.Foreignkey(Seller, related_name='ads') found_in: models.Foreignkey(Search, related_name='ads') I'm currently creating detailview for these different models that each display statistical information. For the 'Seller' model I would like to show 'total ads', 'average price' and 'median price' attributes, and for the search I would like to display these as well. What I am wondering is how I should get that data. I could do it by a reverse query (Seller.ads, etc), or I could create a new field on the Seller model that is set after each scraping operation. It seems somewhat silly to set these fields that can be easily retrieved with a simple query, but this database is probably going to reach tens of thousands of lines, so it might get slower in the long run. I am basically wondering what the best practices are, and if there is a somewhat specific 'cut of point' between retrieving information via a database query vs … -
create httpOnly cookie in Angular and Django
Am building an app using Django as the backend and Angular as the frontend. I understand that saving authentication token in httpOnly cookies is the safest, great. The real question is how do i do that. Been hearing around that i will need something like a middle man server to do that but i have not the slightest idea. Could anyone kindly point me in the right direction? I would be eternally grateful. I've tried setting it on django that was when i realized it cannot be set across domain. So pls help Angular 5 python 3.6 django 1.11 -
Couldn't load "object". Somehow it went missing?
Am using haystack with solr 6.6 for search indexing. Now i want to automatically update indexes when data changes in my models under indexing, so am using celery_haystack for that. Unfortunately, each time index should be updated i get could not load [app.model.pk]. Somehow it went missing error python 3.6.3 django 1.11.6 celery 4.1.0 django-haystack 2.7.dev0 celery-haystack 0.10 Thanks in advance. -
Passing a nested dictionary to requests module
I have a nested dictionary, which I want to pass to a web service (written in PHP) and am struggling, as I can't access the data I need. The dictionary looks something like import requests from nested_dict import nested_dict data = nested_dict() data['name'] = 'test' data['cookies']['PHPSESSID']['name'] = 'PHPSESSID' data['cookies']['PHPSESSID']['essential'] = 'Essential' data['cookies']['CookieNotice']['name'] = 'CookieNotice' data['cookies']['CookieNotice']['essential'] = 'Essential' Then I make my request: r = requests.post('someurl.com', data = data) In the receiving url someurl.com (written in PHP), I can access the first level no problem eg header('Content-Type: application/json'); $data = $_REQUEST; $response['content'] = $data['name'] $response = $response['content'] echo json_encode($response); The problem is trying to access the data in the nested dict. I don't know what form this is arriving in when it hits someurl.com, and as a result I can't use to produce a loop. What I want to do is this: header('Content-Type: application/json'); $data = $_REQUEST; $response['content'] = $data['name'] foreach ($data['cookies'] as $k => $v): $response['content'] .= $k." ".$v; endforeach; $response = $response['content'] echo json_encode($response); When the response is printed out in the template, there is content present for the nested section ... Any help much appreciated! -
Error uploading Django project to Digital Ocean
I've a Bad gateway error whenever I try and upload my Django project to Digital ocean. I was following this guide https://pythonprogramming.net/django-web-server-publish-tutorial/ but I didn't update Django, I'm using version 1.8.7. Do I need to change the secret key on the server to the secret key on my project? This is the Nginx error message 2018/01/10 17:07:58 [error] 2210#2210: *5 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 86.167.15.195, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "159.65.16.251" 2018/01/10 17:08:45 [error] 2210#2210: *7 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 86.167.15.195, server: _, request: "GET / HTTP/1.1", upstream: I've changed allowed hosts in the settings file to = [159.65.16.251] Do I also need to change this our just leave it out? ALLOWED_HOSTS = ip_addresses() Url.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), url(r'^writing/', include('writing.urls')), ] -
Django - Set a default image on a model from a ForeignKey model
the problem I am having is as follows. I have two models as shown below, 'Profile' and 'Image', where each Image instance is connected by a ForeignKey to a single profile, so multiple Images will be linked to a single Profile. From this, I want to set a default image to the Profile by returning the first Image out of the set of related Images. class Profile(models.Model): ... def default_img(self): if self.p_image.count() > 0: return self.p_image[0] else: return False class Image(models.Model): ... related_profile = models.ForeignKey(Profile, related_name='p_image') img_path = models.ImageField(upload_to=profile_img,null=True,verbose_name='Image URL',height_field='h_field',width_field='w_field') With the method that I am trying to do, Django returns the error ''RelatedManager' object does not support indexing' which is through the line 'return self.p_image[0]', where I try to get the first object out of the set. Any help on how to get this first object (without having to search through the entire set of Image objects)? Thanks -
Django access data from a variable in other method in views.py
I am new Django so bare with me for a silly question. Currently I am using method based views. So my views.py file looks like this views.py from django.shortcuts import render def index(request): query = request.GET.get('query') **** DO SOMETHING HERE **** return render(request, 'home.html') def analysis(request): x = query return render(request, 'analysis.html', {'query': x}) Now I want to use the query variable in my other (analysis) method. One way is to make a class and then use self.query but I think I cannot do that like this in Django. I was looking for class based views but I don't know whether that will help. So please guide me how can I do that ? -
Use a minimum number of queries over 4 models with two foreign keys
I have 4 models : Company, Products, Logos and Images. Logo has and FK to Company class Logo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) Product has an FK to company class Product(SEO, MetaData, NotificationStream): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) Image has an FK to Company class Image(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) For the Company DetailView(GCBV) corresponding template page in the context objects I want to get: the company attributes a specific version of the logo the last 3 products of the company ; or all in another version a specific image for each product I tried to use Prefetch objects, but are limited(slicing) or/and I don't understand them enough, so they are not working def get_queryset(self): qp = Product.objects.prefetch_related(Prefetch('images', queryset=ProductImage.objects.all()[0])) return super().get_queryset().prefetch_related(Prefetch('products', queryset=qp)) then I tried to do add them in context one, by one: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) products = Product.objects.filter(company_id=context['company'].id)[:3] I can't do prefetch_related to the Image, because of slicing. What I want o achieve is to have only 4 queries: company logo product images And in template context to have: {{company}} {{company.logo}} {% for product in company.products.all:%} {{ product.image}} I know I can call each other in template but I will get a lot of queries, … -
Google maps javascripts api with more than 100000 markes
I have a google maps app in django a try to draw a map with near 200.000 markers, the time to load is around 45 seconds, I want to less it. I use MarkerClusterer for agregattion this markers, but the process spend more time es create the markers. In a static .js, I have: function addMarkers() { add_marker(features) ... (others 200.000 lines)... }(+- 40 MB) And in the html file: function add_marker(array){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(lt,lg), map: map, (with others features) }); gmarkers.push(marker); google.maps.event.addListener(marker, 'click', function(){ window.open(...); }); google.maps.event.addListener(marker, 'rightclick', function(){ this.info.open(map, this); }); } Clusterer = new MarkerClusterer(map, gmarkers, options); -
How to reduce duplication of html on a pure client-side site
I have an old pure HTML/CSS site that I want to clean up. I have two HTML pages that contain the same navigation bar. If I were using a framework like Django, I would extract that navigation bar HTML code into its own template (navigation.html) and then import that template using {% include 'navigation.html' %}. Is there a way to do the same thing without using a heavy framework? At the very least, I don't want to use any server-side scripts. -
Django - join two query sets by id?
Im trying to join two tables together before being sent to a view, using _set in a view causes 100s of queries which is highly inefficient. example structure sites.models.py class SiteData(models.Model): location = models.CharField(max_length=50) site_type = models.ForeignKey(SiteTypes, verbose_name="Site Type", \ on_delete=models.PROTECT) bgp_as = models.CharField(max_length=6, verbose_name="BGP AS Number") opening_date = models.DateField(verbose_name="Site opening date") last_hw_refresh_date = models.DateField(verbose_name="Date of latest hardware refresh", \ blank=True, null=True) is_live = models.BooleanField(default=False, verbose_name="Is this a live site?") example structure config.models.py class SiteSubnets(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Location", \ on_delete=models.PROTECT, blank=True, null=True) subnet = models.GenericIPAddressField(protocol='IPv4', \ verbose_name="Subnet", blank=True, null=True) subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True) peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True) site_ip = models.BooleanField(default=False, verbose_name="Is this a site supernet IP?") class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" Queries: site_subnets = SiteSubnets.objects.only('subnet').filter(site_ip=True) site_data = SiteData.objects.only('location','is_live','bgp_as','postcode','opening_date','live_link_type') Desired Outcome example: Location | Subnet | BGP AS --------------------------------- London | 10.10.10.0 | 65001 Manchester | 10.10.20.0 | 65002 ... I cant do a select_related without having the SitesSubnet table as the main table, as when I do it on site data, I get django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'site_subnets'. Choices are: site_type If I use the SiteSubnet as the main table, if a … -
pytest.mark.parametrize with django.test.SimpleTestCase
I am using pytest 3.2.2 and Django 1.11.5 on Python 3.6.2 on Windows. The following code import django.test import pytest class ParametrizeTest: @pytest.mark.parametrize("param", ["a", "b"]) def test_pytest(self, param): print(param) assert False works as expected: scratch_test.py::ParametrizeTest::test_pytest[a] FAILED scratch_test.py::ParametrizeTest::test_pytest[b] FAILED But as soon as I change it to use Django's SimpleTestCase, like this: class ParametrizeTest(django.test.SimpleTestCase): ... it fails with TypeError: test_pytest() missing 1 required positional argument: 'param' Can anybody explain why? And what to do against it? (I actually even need to use django.test.TestCase and access the database.) I have the following pytest plugins installed: plugins: random-0.2, mock-1.6.2, django-3.1.2, cov-2.5.1 but turning any one of them (or all of them) off via -p no:random etc. does not help. -
Saving data to a Django Model from views.py
I have to save some data to a model in my database. The data was sent to views.py from the client using ajax, was formatted in views.py and now needs to be saved. My problem is, I don't know how to create an instance of the form without a form contained in request.POST. How do I create the ModelForm in views.py and populate it with data when I don't have anything in request.POST to start the form off with? Here is the model: class CompleteBallot(models.Model): ElectionID = models.ForeignKey(Election, on_delete=models.CASCADE) Vote = models.TextField(null=True) Here is the form: class SubmitBallotForm(forms.ModelForm): class Meta: model = CompleteBallot fields = '__all__' -
Django - filter model with DateTimeField to include records in every n minutes
I have a model with time series data. Model has a DateTimeField called timestamp, which is also my primary key, and has records with an interval of 1 minute (i.e. there is a record with time 2012/01/01 00:00:00, 2012/01/01 00:01:00, 2012/01/01 00:02:00 and so on). class MyModel(models.Model): timestamp = models.DateTiemField(primary_key=True) . . En example query I want to run on this model is; to get records for every 4 minutes in a time interval. So that I will end up with records on; 2012/01/01 00:00:00 2012/01/01 00:04:00 2012/01/01 00:08:00 2012/01/01 00:12:00 . . How can I run such a query? I'm open to answers using .raw() or .extra() -
webpack 0.0.0.0 docker not working
I'm using docker-compose to serve django at 0.0.0.0:80 and webpack-dev-server at 0.0.0.0:3000. They're both work perfectly at 0.0.0.0 I also have domain bound to my external IP and I even can access django from this domain. But somehow, I can't access webpack-dev-server, neither by external IP, nor by domain. Here is some additional data: docker-compose.yml web: build: backend/ command: sh dockerfiles/init.sh ports: - 0.0.0.0:80:80 js: build: webclient/ command: yarn runserver ports: - 0.0.0.0:3000:3000 As you see, they are both served same way here server.js new WebpackDevServer( webpack(config), { publicPath: config.output.publicPath, hot: true, historyApiFallback: true, allowedHosts: [ '0.0.0.0', 'localhost', 'DOMAIN', '*.DOMAIN' ], headers: { "Access-Control-Allow-Origin": "*" } } ).listen(3000, '0.0.0.0', function (err, result) { if (err) { console.log(err) } console.log('Listening at 0.0.0.0:3000') }) When I ping the port 0.0.0.0:3000 - the port is open. When i ping DOMAIN:3000 - the port is closed. Do you have any ideas what's going on?