Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to get instance values for form in django?
I've overridden a detail view so I can render form elements with render_field. However, when rendered they do not show the saved values. I can't set the value in the template because I can't put {{}} within {% %} syntax. How can I access and display the previously saved model instance values? (these are sliders that I want to keep as sliders, and they also have a lot of data attributes that I want to keep consistent, so I can't just write the inputs manually in the template) In views.py: class MyDetailEditMixin(SingleObjectMixin): """ Hybrid mixin to edit a detail """ model = MyModel form_class = forms.MyForm raise_execption = True def get_context_data(self, **kwargs): """ expose the form """ kwargs.setdefault('form', forms.MyForm) return super(MyDetailEditMixin, self).get_context_data(**kwargs) class MyDetailView(MyDetailEditMixin, DetailView): """ Shows the details for a specific strategy """ I feel like I need to explicitly mention the instance somehow? I'm not sure. The inputs render correctly with all their specific data attributes, just no set values. -
Python Django: Annotating a same name with a database field
I need to annotate something that has to be named 'id' that is the same as the primary key of the table 'id'. The final output should be an array of dictionaries. I know that I can annotate with another name like 'id_for_tree' and then after using values() to make the dictionaries and change the key in a loop. Something like: item_list = MyTable.objects.annotate(id_for_tree=Concat(F('id'), F('Code'), output_field=CharField())).values('Name', 'id_for_tree') for any_item in item_list: any_item['id'] = any_item.pop('id_for_tree') It's clear that this solution does not have a good performance. How can I get rid of the "The annotation 'id' conflicts with a field on the model" exception by discarding the previous 'id' and annotate a new 'id'? -
Send a PDF generated from an API to an external server?
I have a NodeJS-ExpressJS server (to host a web page) and Django API server. When a specific endpoint in the Django server is called from the ExpressJS server (when a user clicks a button on the web page), a PDF is generated. I want to send this PDF from the Django server to the ExpressJS server and then download it to the user's browser (The user only interfaces with ExpressJS server). In order to do this I encode the PDF as a base64 string in the Django server and return the string in an HTTP response. In the ExpressJS server, I decode the base64 string and then use the res.download() method provided by the ExpressJS framework to download the PDF to the user's browser. This method appears to work, but can it corrupt the PDF file? Is there a way to simply send the PDF file as a binary file and download it to the browser that way (If possible, please provide an example)? Any answers, examples, and suggestions are greatly appreciated. Django API server def process_upload(request): ''' Process request and generate PDF .... ''' with open(pdf, "rb") as pdf_file: encoded_string = base64.b64encode(pdf_file.read()) return HttpResponse(encoded_string) ExpressJS server server.get('/api', function(req, res, … -
Django models - Able to dynamically calculate the value of a field
Say for example I have a rating which is attached to a product model like so.. class Product(models.Model): ... rating = models.IntegerField(...) I want the product rating to change as new Reviews (that include a star rating of the product) change or updated/deleted. class Review(models.Model): ... related_product = models.ForeignKey(Product, on_delete=models.CASCADE, ...) rating = models.IntegerField(...) Initially, I used a method on the product class to calculate the value of rating by counting the rating value from each review and then dividing by the number of reviews to get an average. class Product(models.Model): ... def rating(self): total_rating = ... reviews_count = ... average = total_rating / reviews_count However, this doesn't allow me to use order_by('rating') when querying the objects and sending back the objects by order of their rating since 'rating' has to be defined in the database (i.e. as a field instead of a method). Is there any way that I can calculate the value for rating which is then stored in the database? -
django imagefield uploading a file "This field is required" error
So I used this link to extend my user model to have a profile page. Now it did work, and I decided to try it out with adding a field for uploading a user avatar. For some reason, whenever I upload an image, it won't save it, and it keeps giving me the error mentioned in the title. What exactly is going wrong here? I can add the image just fine in the admin page, but once I get to the html page, and try to add or change it over there, it will only give me an error saying "This field is required". models.py: class Profile(models.Model): CATEGORIES = [ ('CU', 'Cute'), ('FU', 'Funny'), ('DA', 'Dank'), ('OS', 'Only Smart People Will Understand'), ] user = models.OneToOneField(User, on_delete=models.DO_NOTHING) avater = models.ImageField(upload_to='avatar') fb_link = models.URLField() seenMemes = models.ManyToManyField('Meme') top_3_cat = models.CharField( max_length = 50, choices = CATEGORIES, default = 'DA', ) def __str__(self): return self.user.username @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() views.py: @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('profile') else: messages.error(request, ('Please correct the error … -
Django 'AnonymousUser' object has no attribute '_meta' error when trying to login users
Previously, I have been using the default Django user model but I have now changed to a custom user model so I can remove the 'username' field on my registration form. Everything seems to be working smoothly with regards to registering new users, and adding them to user groups etc. However, when I try to log in these new users I get the error message: 'AnonymousUser' object has no attribute '_meta' Which points at the line of code: login(request, user) My 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 … -
Details for model and form model on detail page
I have problem with connect two models on one page, detail page (Django 1.11). I have model Event - I want to display details for this model on detail page - this is working for me. class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = models.TextField() image = FilerImageField(null=True, blank=True) free_places = models.IntegerField() class Meta: ordering = ['-date'] def __str__(self): return self.title On another hand I have model Register class Register(models.Model): event = models.ManyToManyField(Event) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=50, blank=True) post_code = models.CharField(max_length=30, blank=True) city = models.CharField(max_length=30, blank=True) email = models.EmailField() phone_number = models.IntegerField(max_length=30) def __str__(self): return self.first_name I want to signup user on event with folder on detail page, below details for events. Here is my detail view, where I want to display details for event and take data from user to Register model: class EventDetailView(DetailView, FormMixin): model = models.Event form_class = forms.RegisterForm def get_success_url(self): return reverse('events:list') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) Template: {% extends 'base.html' %} {% block content %} <ul> <h1>Detail page:</h1> <li>{{ object.title }}</li> <li>{{ object.text }}</li> <li>{{ object.date }}</li> </ul> <form method="post"> {% csrf_token %} {{ … -
Is it possible connect a Django app with Chatfuel?
I have this project where I have to connect my Django app with a Chatfuel bot. I have my admin panel, so whenever I update a field like complete certain task, I have to notify my client through the chatbot that this field change. But I can't find info for do that. -
work with list in jquery
with Django Rest Framework i "get" this data to localhost/api/data: [{"date":"2018-01-02","time":"21:00","people":6}, {"date":"2018-01-11","time":"21:00","people":2}, {"date":"2018-01-04","time":"21:00","people":4}, {"date":"2018-01-06","time":"21:00","people":2}, {"date":"2018-01-06","time":"21:00","people":10}, {"date":"2018-01-03","time":"21:00","people":2}, {"date":"2018-01-06","time":"21:00","people":6}, {"date":"2018-01-06","time":"21:00","people":4}, {"date":"2018-01-06","time":"21:00","people":4}] Now I want to pass them to chart.js charts, for example: - Line chart: from 1 to 30 January (to show all booked in 1st jan e.g) - Bar chart: the count filtered by week day (monday,...) - Bar chart: the count filtered by hour (21, 22, 23...) I can take data in jquery function but I can't manipulate data...someone can help me? -
Django ManytoMany filter exact list with duplicate items
This is extension for the question Django ManytoMany filter exact list Looks like accepted answer doesn't work when list contains duplicates. Is there any solution? Basically, I split sentence into tokens and want to search by that tokens. class Sentence(Model): name = CharField() class Tokens(Model): token = CharField() sentence = ForeignKey(Sentence, related_name='tokens') Suppose, I have the tokens ['che', 'farebbe', 'dalle', 'dalle']. I want to find sentence that consist exactly of these tokens. Sentence.objects.annotate(n=Count('tokens')).filter(tokens__name='che').filter(tokens__name='farebbe').filter(tokens__name='dalle').filter(n=4) doesn't work. n is more than 4 (I guess, because of joins). If list of tokens doesn't have duplicates then everything is working fine. -
Django auth permission interfering with Rest Framework
I am trying to POST something to my API from a view. My API view has a custom made permission only, where it looks for a token, and its open to Cross Site Requests. However, if I post something when I'm logged in, the request does not work, and I get a 403 error. If I log out, the request works perfectly again. What is the problem with this? Any ideas on how to solve this? Thanks. -
Django initialise data in forms.inlineformset_factory
I'm trying to use an inlineformset and there are certain fields which will be the same for this particular user in this instance. I want to initialise/default these fields but cannot work out how to do it. MODELS Basically, my models look something like ... class Organisation(models.Model): name = models.CharField( verbose_name = 'Organisation Name', max_length = 30 ) slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True, blank=True, null=True ) user = models.ForeignKey( User ) class Factor (models.Model): name = models.CharField( verbose_name = 'Factor', max_length = 30 ) class SupportingDocument(models.Model): f = models.FileField( upload_to ='supporting_document/' ) factor = models.ForeignKey( Factor, blank = True, null = True ) organisation = models.ForeignKey(Organisation) FORMS class OrganisationFactorForm(forms.ModelForm): class Meta: model = Organisation fields = ['user'] widgets = { 'user' : forms.HiddenInput(), } class SupportingDocumentInline(forms.ModelForm): class Meta: model = SupportingDocument exclude = ['id', ] widgets = { 'factor' : forms.HiddenInput(), 'organisation' : forms.HiddenInput(), 'f' : forms.FileInput(attrs={'class' : 'form-control'}) } SupportingDocumentInlineFormSet = forms.inlineformset_factory( Organisation, SupportingDocument, form=SupportingDocumentInline, extra=1, exclude = ['id'], can_delete=True, can_order=True) VIEWS I want to default the factor record so that when I display the form I can do something like if self.request.POST: form_count = int(self.request.POST['supportingdocument_set-TOTAL_FORMS']) ctx['supporting_documents'] = SupportingDocumentInlineFormSet(self.request.POST, self.request.FILES, instance=self.get_object()) for x … -
MySQL 5.7 warning when SELECT is filtered by binary field
I'm using Django 1.6, MySQL 5.7 and there is a binary field in the DB. And when I try to SELECT some data with filtering by that field, I get an error: Invalid utf8 character string: 'F5F111'. It's the same as in the ticket: https://code.djangoproject.com/ticket/26140 As I see, fix for the ticked is solved a case only for INSERT (not SELECT) queries and anyway my Django can't be updated right now. So is any way to fix this issue? Maybe I can somehow query this data more properly, or do any patch? Thank you! -
Google Cloud Routes HTTP and HTTPS differently
TL;DR Google Cloud Platform routing dispatch behaves differently for HTTP and HTTPS, and I can't figure out (or find a reference as to) why. The Setup I have a default service with this (absolutely standard) app.yaml: runtime: python env: flex entrypoint: gunicorn -b :$PORT <project>.wsgi beta_settings: cloud_sql_instances: <instance-connection-string> runtime_config: python_version: 3 It's a Django app serving the API and the Admin Interface. I have a frontend service with this (again, absolutely standard) app.yaml: service: frontend runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static/(.*) static_files: build/static/\1 upload: build/static/(.*) - url: /.* static_files: build/index.html upload: build/index.html It's a ReactJS application that consumes the API and acts as a frontend. Then, I have this dispatch.yaml: dispatch: - url: "*/api/*" service: default - url: "*/admin/*" service: default - url: "*/*" service: frontend Meaning "serve /api/... and /admin/... from the default service, and the rest from the frontend service". Alright. The Problem When I go to http://<project-id>.appspot.com (note the HTTP), everything works as expected. To wit: http://aksinin-191616.appspot.com/api/content/ is the API, http://aksinin-191616.appspot.com/admin/en/ is the Admin Interface, http://aksinin-191616.appspot.com/ is the frontend. But when I do the same with https://<project-id>.appspot.com (note the HTTPS), everything is always redirected to the frontend. To wit: https://aksinin-191616.appspot.com/api/content/ is the frontend, … -
Django: Login with E-Mail
I want to authenticate with e-mail and password, but somehow I can't find the setting where it is done? Here is my login.html: <form method="post"> {% csrf_token %} <label for="email">E-Mail</label> <input id="email" name="email" type="email" maxlength="50" autofocus="autofocus" required=True unique=True class="form-control"> <label style="margin-top: 1em;" for="password">Passwort</label> <input style="margin-bottom: 2em;" id="password" name="password" type="password" maxlength="25" required=True class="form-control"> <button class="btn btn-success btn-sm" type="submit" value="login">Login</button> And here is my views.py: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST, email=request.email) if form.is_valid(): form.save() email = form.cleaned_data.get('eemail') raw_password = form.cleaned_data.get('password1') user = authenticate(email=mail, password=raw_password) login(request, user) return redirect('accounts:view_profile') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) Am I looking completely wrong? Where can I find the setting? Thank you for your help!