Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django run scheduled jobs hourly
In my project I have to load data in database hourly .I tried celery and cron but found all the stuff very complicated and always createes some issue.I use pycharm in windows. I am new to django and just need a simple solution to run the following command hourly. This loads data in dabase. "python manage.py fetchfiles" management/commands/fetchfiles from django.core.management.base import BaseCommand, CommandError from dashboard.models import airdata as tdata import requests import json class Command(BaseCommand): help = 'Fetches api data' """def add_arguments(self, parser): none""" def handle(self, *args, **options): #for a in range(0,1578,10): a = True offno = 0 lst2=[] dict1={} while a == True: api_key = "579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b" url = "https://api.data.gov.in/resource/3b01bcb8-0b14-4abf-b6f2-c1bfd384ba69?api-key={}&format=json&offset={}&limit=10".format(api_key,offno) response = requests.get(url) data = response.text a1=json.loads(data) for ele in a1['records']: if ele['pollutant_min'] == 'NA': dict1['pol_min'] = 0 else: dict1['pol_min'] = int(ele['pollutant_min']) if ele['pollutant_max'] == 'NA': dict1['pol_max'] = 0 else: dict1['pol_max'] = int(ele['pollutant_max']) if ele['pollutant_avg'] == 'NA': dict1['pol_avg'] = 0 else: dict1['pol_avg'] = int(ele['pollutant_avg']) dict1['state'] = ele['state'] dict1['city'] = ele['city'] dict1['station'] = ele['station'] dict1['time_vector'] = ele['last_update'] lst2.append(dict1.copy()) if a1["count"] < 10: a= False offno += 10 airx = json.dumps(lst2, indent=1) tdata.objects.bulk_create([tdata(**vals) for vals in lst2]) return airx -
How to set the variables from .env file when using Django and Gitlab CI/CD?
I'm trying to run the tests of my Django app in Gitlab CI/CD. The process fails every time with an error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.. I assume this is because I have not my .env file available in the repository and that file contains for example the SECRET_KEY -variable which is then used in the settings.py like this: SECRET_KEY = os.getenv('SECRET_KEY'). So what would be the proper way to set these variables so my tests would pass? -
What to add in permission_classes for allowing to view the api by only specific group - django
To make only admin access the API, used - permission_classes = (IsAdminUser, ) But to access the specific group is there anything needed to add to permission_classes, or such a thing is completely not possible with permission_classes. If so how can I proceed? -
XML http request error on a login request from flutter -
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:bloc_login/model/api_model.dart'; final _base = "http://localhost:8000/"; final _tokenEndpoint = "rest/v1/pwa/token/login/"; final _tokenURL = _base + _tokenEndpoint; Future<Token> getToken(UserLogin userLogin) async { print(_tokenURL); print(userLogin.toDatabaseJson()); final http.Response response = await http.post( _tokenURL, headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale", "Access-Control-Allow-Methods": "POST, GET, OPTIONS" }, body: jsonEncode(userLogin.toDatabaseJson()), ); if (response.statusCode == 200) { return Token.fromJson(json.decode(response.body)); } else { print(json.decode(response.body).toString()); throw Exception(json.decode(response.body)); } } Seeing XML http request error on a Login request, where as http://localhost:8000/rest/v1/pwa/token/login/ {username: customer1, password: randompass} are obtained but request hit as [18/Jun/2021 12:27:22] "OPTIONS /rest/v1/pwa/token/login/ HTTP/1.1" 200 412 on backend The same API tested from POSTMAN hits as a POST request -
Azure DataLake Query Expression | Error Processing Query
I got some data in blob storage under data lake in CSV, data format is mail,usertype,license Data is huge, so I'm implementing pagination in Django to render it, I don't want my compute unit to fetch all half a mil rows every time which makes the website slow. To improve pagination. Right now when I am querying data based on rows with limit then I'm getting an error Syntax error! RequestId:59f9d9e5-601e-0015-4f0f-64fd1d000000 Time:2021-06-18T06:56:56.9344470Z ErrorCode:ErrorProcessingQueryExpression Error:None Here's my query to pick data of the 5th to 10th row for a test. query_expression = "SELECT * from DataLakeStorage limit 5,10" -
google maps api key for django
hi every one i hope you be okay, so i'm need to display and use google map and places api in my django project and i'm using the django-google-maps package and now i need to get an googld API key i'm got one from https://console.cloud.google.com/ but there is this noise water mark text for developers purposes only after setting the django-google-maps options and google API key on my admin panel. and each time i enter a place namd i'll get the requiest denied error can any one explain to me how to get a correct google API key and or even a better way to display google maps in django project? i'll be so thankful for your help🙇♂️🌷 -
How to make custom decorator with multiple arguments?
Here I am making a custom decorator with some kwargs parameter but the decorator is not working. Error: TypeError: my_decorator() takes 1 positional argument but 2 were given Code def my_decorator(title, **data): def _method_wrapper(view_method): def _arguments_wrapper(request, *args, **kwargs) : obj = Model.objects.get(title=title) if obj.relatedmodel_set.filter(**data).exists(): return view_method(request, *args, **kwargs) raise PermissionDenied return _arguments_wrapper return _method_wrapper #view @my_decorator('title', {'is_manager':True}) def my_view(request, id): -
How to use pre_create_historical_record signal in django-simple-history?
I am using django-simple-history to save history of data. I want to save an extra field value to each history model before it is saved. I found the reference code in documentation mentioned above but cant use it. Please help. from django.dispatch import receiver from simple_history.signals import ( pre_create_historical_record, post_create_historical_record ) @receiver(pre_create_historical_record) def pre_create_historical_record_callback(sender, **kwargs): print("Sent before saving historical record") @receiver(post_create_historical_record) def post_create_historical_record_callback(sender, **kwargs): print("Sent after saving historical record") -
Wagtail RoutablePageMixin fail to route page when DEBUG=True
I am using Wagtail/CodeRedCMS to set the website. RoutablePageMixin is inherited in my model (named WriteLandingPage). And "route" is used to redirect request to certain custom view. my code is below. model.py class WriteLandingPage(RoutablePageMixin, CoderedArticlePage): class Meta: verbose_name = 'Write Landing Page' template = 'coderedcms/pages/write_landing_page.html' @route('') def submit(self, request): article_index = ArticleIndexPage.objects.all()[0] from .views import submit_topic return submit_topic(request, article_index) views.py def submit_topic(request, article_index): print(request.user.is_authenticated) form = EditForm(data=request.POST or None, label_suffix='') if request.method == 'POST' and form.is_valid(): submit_page = form.save(commit=False) submit_page.slug = slugify(submit_page.title) topic = article_index.add_child(instance=submit_page) if topic: topic.unpublish() topic.save_revision(submitted_for_moderation=True) return render(request, 'coderedcms/pages/submit_topic_success.html', {"user": request.user}) context = { 'form': form, 'edit_index': article_index, } return render(request, 'coderedcms/pages/submit_topic.html', context) forms.py class EditForm(ModelForm): class Meta: model = ArticlePage fields = ['draft', 'title'] Everything works just prefect when DEBUG=True. But It fails to read page when I turns DEBUG to False. The following messages shows on backend console. [18/Jun/2021 01:41:04] "GET /write-landing-page/ HTTP/1.1" 500 940 Am I missing any setting? -
docker cmd: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
I have a Django project and I want to create a docker image for it. FROM python:3 # copy source and install dependencies ENV PYTHONUNBUFFERED=1 WORKDIR DockerHome COPY requirements.txt /DockerHome/ RUN pip install -r requirements.txt RUN pip install psycopg2 COPY . /DockerHome/ RUN python manage.py makemigrations RUN python manage.py makemigrations bill RUN python manage.py migrate CMD python manage.py grpcrunserver 0.0.0.0:5051 The RUN commands use psycopg2 successfully. for example python manage.py makemigrations bill uses psycopg2 too, but when I run a container from this image, I get this error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' what is the problem with the CMD function that cannot import psycopg2? -
Uncaught RangeError: Maximum call stack size exceeded at Dt on posting
I am using Django and trying to post a form through ajax. $(document).on('submit', '#create-assignment', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/teacher/exam/create/', data:{ title: $('#assignment-form-title-input').val(), time: $('#assignment-form-time-input'), description: $('#assignment-form-description-input'), date: today, file: files[0], csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() } }); $('#create-assignment').trigger("reset"); }); On trying to post it I get an error - Uncaught RangeError: Maximum call stack size exceeded at Dt I tried to search for it but couldn't understand anything. For the array files, $('#assignment-form-file').change(function(event) { files = event.target.files; reader = new FileReader(); reader.onload = function(){ reader.readAsDataURL(files[0]); }; }); and var today = new Date().toISOString().slice(0, 10) And the html is like this - : <form id="create-assignment"> {% csrf_token %} <div class="title-time-wrapper"> <input type="text" placeholder="Enter Title" class="assignment-form-input" id="assignment-form-title-input" name="assignment-title"> <input type="text" placeholder="Enter Time in minutes" class="assignment-form-input" id="assignment-form-time-input" name="assignment-time"> </div> <textarea placeholder="Enter Description" class="assignment-form-input" id="assignment-form-description-input" name="assignment-description" rows="5"></textarea> <div class="input-file-wrapper"> <input type="file" name="assignment-file" id="assignment-form-file"> </div> <input type="submit" value="Save" id="assignment-form-submit"> </form> If anyone can tell the mistake and explain a bit about the same it will be really helpful. -
About (sender, instance, created, **kwargs) parametert. How it's assigned
from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) I'm new to python in general and while I was going thru a tutorial it teaches about signals. I've been trying to figured how this function works, as in how (sender, instance, created, **kwargs) is assigned to? I can't seem to wrap my head around it. So if a post is saved it triggers this vvv receiver(post_save, sender=User) in this case User gets assigned to sender. since sender=User . easy. Now, as for the second parameter, instance , it shows in the very last line of the function. user= instance. from my understanding of function, and parameter, should it all be assigned WHEN the function is CALLED? in this case when the receiver signal is triggered and create_profile is called, instance and created has no value yet.... correct? As for 'created', why does it have to be a parameter? since it's checking if CREATED. Does (instance, created) have an in built....functionality in it? since from what i get those three are placeholders and it needds to be assigned a value in order to do … -
Disable field in Django forms do not fetch the original value
I am trying to disable the field input for update from my view def get_update_form(self, obj): form = super().get_update_form(obj) form.fields["is_active"].disabled = True return form But when I update, it doesn't retain the original value of the active status of the object to be updated. I also tried form.fields["is_active"].widget.attrs['disabled'] = 'disabled' but it still doesn't retain the value. Is there any way I can disable it but upon update, it will retain the original value of this specific field? Thanks! -
Declare Model Value in Django [duplicate]
I am pretty new to Django. I would like to know how to declare the value of a models field. For example, if was making a model for pictures frames, I could choose from the selection of small, medium, or large. Then, it would automatically populate the values for length and width to be 5 and 7 for small, 8 and 10 for medium and so on. I’m assuming you still have to make the field length and width be integer fields. But I don’t know how to set the value after that. -
How can I undeploy a heroku app with Django?
I'm having issues with parts of my website (made with Django) that I create after deploying disappearing because Heroku is very unhelpful with storage. Is there a way to undeploy and redeploy a site on Heroku? I think this would fix my issue. -
pytest django load database data from yaml file
I have dumped data from my development environment using dumpdata django command into a yaml file. I am using pytest framework and need to achieve the following scenario: During start of a pytest session -> that is when I run pytest from command line, the data from yaml file should be loaded into my test database Is there any plugin or hook which I can use to achieve the above ? I am using python 3.8, pytest 6.2.4, pytest-django 4.40, Django 3.0.5 -
Django url dynamic link
im using vuejs in django and i have this code <form method="POST" :action="edit ? '{% url 'productoEdit' pk=request.path|slice:'19:21' %}' : '{% url 'productoCrud' %}'" enctype="multipart/form-data"> if the variabble edit is true action will be {% url 'productoEdit' pk=request.path|slice:'19:21' %} if is false {% url 'productoCrud' %} the problem is that django gives me an error: Reverse for 'productoEdit' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['user/productoEdit$', 'user/productoEdit/(?P<pk>[^/]+)$'] this is my urls.py path('productoEdit/<str:pk>', views.productoEdit, name="productoEdit"), path('productoEdit', views.productoEdit, name="productoEdit") as you can see the path productoEdit has 2 views, one with parameters and other without parameters. this is my productoEdit in views.py def productoEdit(request, pk=''): producto = Producto.objects.get(id=pk) form = CreateProductForm(instance=producto) if request.method == 'POST': form = CreateProductForm(request.POST, instance=producto) if form.is_valid(): form.save() redirect('productoCrud') return render(request, 'productoCrud.html', {'form': form}) the problem ocurred when request.path is an empty string pk=''. i tried using a ternay operator like this: pk=request.path|slice:'19:21' ? request.path|slice:'19:21' : None or pk=request.path|slice:'19:21'|yesno:'request.path|slice:'19:21',None' Django doesnt like my solutions xD, how can i resolve this problem?? thx so much for your help -
Confusion about migration files on Official Django document
On Migration Files part of Django Official Document, it reads: Paragraph 1: The operations are the key; they are a set of declarative instructions which tell Django what schema changes need to be made. Django scans them and builds an in-memory representation of all of the schema changes to all apps, and uses this to generate the SQL which makes the schema changes. Paragraph 2: That in-memory structure is also used to work out what the differences are between your models and the current state of your migrations; Django runs through all the changes, in order, on an in-memory set of models to come up with the state of your models last time you ran makemigrations. It then uses these models to compare against the ones in your models.py files to work out what you have changed Q1: In differences are between your models and the current state of your migrations, what exactly your models and current states of your migrations refer to? which one refers to the Database Version before this new migration file is applied and which one refers to the Database Version after new migration file is applied? Q2: That in-memory structure is also used to work … -
Django - Databases
I have two projects in django, proj1 and proj2, Aim - I want to use common database(postgresql) between proj1 and proj2. Problem - proj1 has all the models, How do I import models in proj2? Is there any way to do that? -
Opening CSV file in Django using javascript
I'm starting to learn Django and one of the projects I have chosen for myself is one that has has a html front page, which the user inputs some search text and then that calls to a api using python and pytrends, then its saves that information as a csv file. I'm having a hard time with the next part which is importing that csv file into another html page, where I would like to use chart.js to turn it into a graph. I can't figure out how to open up the file and run it inside of javascript. I have tried a static load but its not opening up the file, just the path to the file. Please let me know if you need to see any other files or know anything else. async function getData() { const data = '{% static "interest.csv" %}'; console.log(data.text()); const table = data.split("\n").slice(1); table.forEach((row) => { const columns = row.split(","); const year = columns[0]; const interest = columns[1]; xlabel.push(year); console.log(year, interest); }); -
ModuleNotFoundError: no module named <projectname> Django Heroku
Help PLEASE!!! Newbie trying to put Django on Heroku... ~8-( Am I supposed to list my app somewhere else???? I just know it some foolish oversight.... I am trying to set up a Django site on Heroku free tier. It works locally (using Sqlite3) and I got it working on Azure - but after following many howtos for this I cannot get it to work and have found no answers (that worked). I am not great with Git and am pretty new to Django - but I think I have followed all the tutorials guidance. Heroku was set up with the same name as used in Git and is correct in wsgi.py. I have the requirements.txt(below), .gitignore, Procfile (web: gunicorn animalproject.wsgi --log-file -), .env ('DATABASE_URL=sqlite:///db.sqlite3' - just for local and this is in .gitignore) , runtime.txt (python-3.7.10), django-heroku, and settings.py correct I thought... I did install Postgresql per various tutorials and it shows as correct in Heroku. I am trying to use dj-database-url.And I do have a .env file with DATABASE_URL= postgres://@ec2-54-87-34-201.compute-1.amazonaws.com:5432/ Settings.py is: import environ import django_heroku import dj_database_url ... env = environ.Env() # allows use of env("x") environ.Env.read_env() ... WSGI_APPLICATION = 'animalproject.wsgi.application' DATABASES = { 'default': { 'ENGINE': … -
Django server receives broken string data from Android Device that uses QR scanner(Keyboard input)
I am an Android App Developer. And the app read QR code using QR Scanner device and get Token(a string) from it. I send: B8EurXd5xq9OsvcpGW Server Log receives something like this: B8 Eur Xd5xq9 Osvcp G W Is there a way to show \n, \r or something like that? I replaced them with replace("\r", ""), replace("\n", "") but didn't work. -
Django get specific users profile
I have a implemented a feature in my blog app that allows you to click on a user and view their profile / posts. I want to display information from the users profile such as the bio and profile picture. I was able to successfully display the username but nothing else. To solve this issue I need to get the specific users profile but I am unsure of the proper way to do this Been playing around with a few methods but haven't had anything work and all of the solutions I have found online are about getting the current user views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) userBio = User.objects.get('bio') #not working return Post.objects.filter(author=user).order_by('-date_posted') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=200, null=True) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) -
Edit permissions for Django Details View for api calls
I am very new to django and currently trying to generate api calls to localhost:8000/stateapi/id where id is an id for a single "State" object in a json (like 1, 2, etc). It is using token authentication by passing a username and password to the "get-token" endpoint and then using that token for calls to the stateapi endpoint. I mostly followed this tutorial https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-2 and keep getting a "detail": "You do not have permission to perform this action." Here are the views where CreateView handles the "localhost:8000/stateapi" endpoint and DetailsView handles the localhost:8000/stateapi/id endpoint. class CreateView(generics.ListCreateAPIView): queryset = State.objects.all() serializer_class = StateSerializer permission_classes = (permissions.IsAuthenticated,IsOwner) def perform_create(self, serializer): """Save the post data when creating a new State.""" serializer.save(owner=self.request.user) class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" queryset = State.objects.all() serializer_class = StateSerializer permission_classes = (permissions.IsAuthenticated,IsOwner) I can't seem to figure out why the authenticated user has permission to access information from CreateView but not DetailsView. Here is the permissions code: class IsOwner(BasePermission): """Custom permission class to allow only bucketlist owners to edit them.""" def has_object_permission(self, request, view, obj): # Our problem is that we do not have a owner property for the object """Return True if … -
Django: Display Count of Ratings in ListView
I just started learing django and I'm trying to display a Product with the Amount of Ratings it has in a ListView. But I fail to generate the expected output. models.py class Product(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=255, default=None) author = models.ForeignKey(User, on_delete=models.CASCADE) class ProductRating(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_rating') user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.SmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) views.py class ProductListView(LoginRequiredMixin, ListView): model = Product def get_queryset(self): return Product.objects.annotate(avg_rating=Avg('product_rating__stars')).order_by('-avg_rating') def get_context_data(self, **kwargs): data = super(ProductListView, self).get_context_data(**kwargs) data['product_rating_count'] = Product.objects.annotate(Count('product_rating')) return data template {{ product.name }} {{ product.avg_rating }} {{ product_rating_count }} This displays the name and average-rating as expected but puts a Queryset containing all Products next to each single product like this: <QuerySet [<Product: testp1>, <Product: testp2>, <Product: testp3>, <Product: testp4>]>