Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get checkbox values in django template and pass to view
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) where I want the leader to have the ability to remove Users who have joined the Group. On the frontend, I have the list of members rendered: {% if user.id == group.leader_id %} <form action="{% url 'remove_members' group.pk %}" method="POST"> {% csrf_token %} <ul id='leaderList'> {% for member in list %} <input type='checkbox'>{{ member }}</input> {% endfor %} </ul> <button type="submit">REMOVE</button> </form> {% endif %} However, before I even write the view I need to be able to access the values of these checkboxes and pass the values over to my remove_members view. The view will be function based and will look something like this: def remove_members(request, pk): group = Group.objects.get(id=request.POST.get('group_id')) # I need a line here to access the checkbox values from the template so that I can run a for loop for member in checkbox_values: group.joined.remove(member) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) If I can retrieve the values of the checkboxes and pass them to this view on submit I think this should work to remove the members. Is there some simple thing I'm missing to passing the values? -
Save Excel file to specific path with Django and then zip it
I have the following view which enables me to create an Excel report and then to zip it. def download_report(request, slug): report = get_object_or_404(Report, slug=request.session['slug']) transporter_list = get_transporters_list_with_files(report=report.pk) folder = create_report_folder() if request.method == 'GET': files = [] for transporter in transporter_list: reports_detail = get_object_or_404(ReportResults, report=report, transporter=get_object_or_404(Transporter, name=transporter)) general_result_data = reports_detail.result weights_data = reports_detail.result_comparison_weights file = create_excel_report(report=report, name=transporter, folder_name=folder) files.append(file) zip_files = create_zip_files(list_files=files) response = serve_report_zip_file(zip_files) return response Since multiple reports are to be generated, I'm aiming at generating all the reports and then zip them. I created the following functions: def create_report_folder(): """ Create a folder for the files """ # Creating the folder random_string = get_random_string(length=10) folder_name = "temp" + "/" + random_string if not os.path.exists(folder_name): os.mkdir(folder_name) return folder_name def create_excel_report(report, name, folder_name): """ Create a downloadable report """ # Getting transporters transporter_list = get_transporters_list_with_files(report=report.pk) for transporter in transporter_list: reports_detail = get_object_or_404(ReportResults, report=report, transporter=get_object_or_404(Transporter, name=transporter)) general_result_data = reports_detail.result weights_data = reports_detail.result_comparison_weights general_result_data = json.loads(general_result_data) df_general_result = pd.DataFrame(general_result_data) weight_data = json.loads(weights_data) df_weights = pd.DataFrame(weight_data) # Create a Pandas Excel writer using XlsxWriter as the engine. folder = folder_name filename = "Report - " + name + ".xlsx" with BytesIO() as b: writer = pd.ExcelWriter(b, engine='xlsxwriter') wb = writer.book # … -
Django - Apache - AWS --- 403 Forbidden : You don't have permission to access this resource. error
I have been trying to launch my Django application through apache but I am getting 403 error after configuring apache and giving the permissions. My settings are as follows: Apache conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following … -
Why There Is Error showing "File Not Found" on my Django about webpage even after putting txt file in codebase?
Here Is My about File code from django.http import HttpResponse def readfile(request): openit = open("hell.txt", 'r') hhhhh = openit.read() return HttpResponse(hhhhh) Here Is my urls.py from django.contrib import admin from django.urls import path from . import views from . import about urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('about/', about.readfile, name="readfile"), ] Here Is My hell.txt file in same directory vdsseebelouvbuobewoubouerbrobgerubrobogougbeoebergbrobeobwebewbvdsseebelouvbuobewoubouer -
Django admin model add page save button not working
I am trying to add a model from the admin page and when I press save the model doesn't add and nothing happens, the button darkens and that's as far as it goes. Here's my models.py from distutils.command.upload import upload from django.db import models from tinymce.models import HTMLField # Create your models here. class Actualite(models.Model): titre = models.CharField(max_length=200) auteur = models.CharField(max_length=500) miniature = models.ImageField(upload_to='uploads/thumbnails') contenu = HTMLField() date_creee = models.DateTimeField(verbose_name="Date créée", auto_now_add=True, auto_now=False) date_modifiee = models.DateTimeField(verbose_name="Date Modifiée", auto_now=True) def __str__(self): return f"{self.titre} | {self.auteur} | {self.date_creee}" class Meta: ordering = ['date_modifiee'] verbose_name = "Actualité" class Message(models.Model): nom = models.CharField(max_length=200) email = models.EmailField(max_length=200) contenu = models.TextField() date_recu = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.nom} | {self.date_recu}" and settings.py """ Django settings for jac project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+1j_(+ad1&!9_0+r+u1d&6pieo5q$zv%c-*$vykrx8lnk8c244' # SECURITY WARNING: don't run with … -
To prevent session data between two users Django
Im using django sessions to store user's one of the multiple accounts so that user can proceed with that selected account Flow. When i tried login with another user same account of the previous customer is fetching from session. My scenario is only logged in user should have post/fetch data in session and once logged out all data should be erased. I'm using django JWT. Please help on this. Thanks in advance. -
Django Rest Framework testing destroy view fails
I got fallowing test case: def test_delete_address(self) -> None: """test disable address""" # res = create_object_helper(self.client, self.url, self.data, self.headers) res = self.client.post(self.url, json.dumps(self.data), **self.headers) self.assertEqual(res.status_code, 204) address = AddressBook.objects.all().first() url = reverse( "marketplace_api:add-order-address-detail", kwargs={"pk": address.id} ) res = self.client.delete(url, **self.headers) self.assertEqual(res.status_code, 204) address.refresh_from_db() breakpoint() self.assertTrue(address.disabled) And fallowing view: def destroy(self, request, *args, **kwargs): try: instance = AddressBook.objects.get(id=kwargs.get('pk'), user=request.user) except ObjectDoesNotExist: return Response( {"error": "Address was not found"}, status.HTTP_404_NOT_FOUND ) breakpoint() if instance.disabled: return Response( {"error": "Address was not found"}, status.HTTP_404_NOT_FOUND ) instance.disabled = True instance.save() add = AddressBookSerializer(instance=instance) return Response(add.data, status.HTTP_204_NO_CONTENT) What I'm trying to achieve, is to test my overridden method, where I'm not destroying the instance, but just changing the flag. The problem I am encountering is that, my test case getting different DB data than in view. To test it out, I printed some results in pdb: The response data is (res.data) -> returned from view: {'id': 1, 'invoice': False, 'user': 81, 'first_name': 'Test name', 'last_name': 'Test name', 'street': 'Unknown', 'building': 'Unknown', 'place': 'Unknown', 'city': 'Unknown', 'zip_code': 'Unknown', 'phone_number': 'Unknown', 'email': 'test@test.pl', 'company_name': None, 'nip': None, 'remarks': None, 'disabled': True, 'created': '2022-08-02 15:17:50'} Object address data is (address.__dict__): {'_state': <django.db.models.base.ModelState object at 0x0000026308ED92B0>, 'id': 1, 'user_id': 81, … -
How can I read response content (that is JSON) from Django middleware so I can convert it to HTML?
From my django view I am returning a serialized JSON as below: def features(request): features = db_service.fetch_all_features() data = serializers.serialize('json', features) return HttpResponse(data, content_type='application/json') I have registered a middleware, where I want to fetch this JSON and convert it into HTML class ReturnResponseAsHTML: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after #return HttpResponse(data, content_type='application/json') return response Once I have access to the response object, how may I fetch the JSON from it so I may convert it to HTML -
Get Highest Likes User with Django
class Profile(models.Model): .. goldcoin = models.IntegerField(default=0) likes = models.ManyToManyField(User, blank=True, related_name='user_like') dislikes = models.ManyToManyField(User, blank=True, related_name='user_dislike') def __str__(self): return self.user.username def get_avatar(self): .. from likes = models.ManyToManyField(User, blank=True, related_name='user_like') How to get Highest Likes User? Example i have user like this User Likes Jhon 30 Aish 25 Josh 5 Adam 50 Output User Likes Adam 50 Jhon 30 Aish 25 Josh 5 Django 4.0.6 Python 3.10.2 -
Django,Profile matching query does not exist error at profile/1
I'm learning django,whenever I click on the profiles(links) on the profile_list page,I get the profile doesn't exist error it always goes to profiles that do not longer exist in the database. This is the models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) follows=models.ManyToManyField( "self", related_name="followed_by", symmetrical=False, blank=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile=Profile(user=instance) user_profile.save() user_profile.follows.add(instance.profile) user_profile.save() th This is the admin.py from django.contrib import admin from django.contrib.auth.models import Group,User from .models import Profile class ProfileInline(admin.StackedInline): model=Profile class UserAdmin(admin.ModelAdmin): model=User fields=["username"] inlines=[ProfileInline] # Register your models here. admin.site.unregister(Group) admin.site.unregister(User) admin.site.register(User,UserAdmin) This is the views.py from django.urls import reverse from django.shortcuts import render from requests import request from users.models import Profile from django.http import HttpResponseRedirect # Create your views here. def dashboard(request): return render(request,"inbox/layout.html") def feed(request): return render(request,"inbox/feed.html") def outbox(request): return render(request,"inbox/outbox.html") def profile_list(request): profiles=Profile.objects.exclude(user=request.user) return render(request,"inbox/profile_list.html",{"profiles":profiles}) def profile(request, pk): if not hasattr(request.user, 'profile'): missing_profile = Profile(user=request.user) missing_profile.save() profile = Profile.objects.get(pk=pk) if request.method == "POST": current_user_profile = request.user.profile data = request.POST action = data.get("follow") if action == "follow": current_user_profile.follows.add(profile) elif action == "unfollow": current_user_profile.follows.remove(profile) current_user_profile.save() return render(request, "inbox/profile.html", … -
Django ORM prioritise a column with (almost) duplicate data
Basic DB table is: class ModelA(models.Model): type_of_input = models.CharField(max_length=10) # say "USER" or "SOURCE" date = models.DateField() volume = models.IntegerField() object_referenced = Foreign_key... Problem We sometimes have two duplicate entries in ModelA - which means the two values for the date and the object_referenced are the same, but the values for the type_of_input are different. This means we need to prioritise one value ("SOURCE") for type_of_input over the other ("USER"), in order to make sure the volume value is correct (as "USER" can sometimes be incorrect). We always get the data from the (sometimes unreliable) "USER" type_of_input, but only occasionally get the (always correct) "SOURCE" type_of_input. So when the "SOURCE" type of input value is present we need to return only the "SOURCE" row and not the "USER" row Question How could we do this with the Django ORM to only retrieve one row per date (prioritising the "SOURCE" value for type_of_input? -
Django and Postgre: psycopg2.errors.UniqueViolation: could not create unique index "main_customuser_pkey" DETAIL: Key (token)=(Key) is duplicated
this error show up when i migrate to db using python manage.py migrate, model: class CustomUser(AbstractUser): username = models.CharField(max_length=322,unique=True) email = models.EmailField(max_length=320,unique=True) token = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False) USERNAME_FIELD ='email' REQUIRED_FIELDS = ['username'] -
Wagtail - customise FieldPanel to show results for current Locale
I have a site which is i18n enabled and using wagtail-localize. When editing (or creating) the original language of a page, all the snippets show values for every language, if you use the standard FieldPanel. Using the SnipperChooserPanel is not an option because there are a lot of ParentalManytoManyFields in the model, it would be too cluttered for the editors. This is how the model and snippet is constructed. @register_snippet class Level(TranslatableMixin): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: verbose_name = "Educational Level" unique_together = ('translation_key', 'locale') class Activity(Page): ... level = ParentalManyToManyField(Level, verbose_name='Education level', blank=True) MultiFieldPanel([ .... FieldPanel('level', widget=forms.CheckboxSelectMultiple), ]) I'm trying to work out how to subclass FieldPanel so it uses the page's locale to filter the snippet queryset. I have hacky/temporary solution to this using the limit_choices_to kwarg for ParentalManyToManyField but I can only filter by the user language not the page language. def limit_lang_choice(): limit = models.Q(locale__language_code=get_language()) return limit -
Synthax error on my code - what is wrong in my logic?
It looks like there is a syntax error in my code at the last line. Django doesnt like it. It considers the "return" is outside the function. It was making sense to me. Any clues? class ProfileView(request): user = request.user up = user.userprofile form = FORM(instance = up) if request.is_ajax(): form = FORM(data = request.POST, instance = up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result= "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result':result,'message':message} return JsonResponse(data) -
Detail: Unsupported media type "application/json" in request in django and Vue JS
I am trying to upload a file in my website . However, i got an error Unsupported media type "application/json" in request in python django backend. Not too sure if it is frontend problem or backend problem. But in the django backend , it shows that the API has unsupported media type. Can anyone help me this ? frontend <v-file-input type="file" label="Attachment" multiple prepend-icon="" prepend-inner-icon="mdi-file" v-model="inputs[i].value" :outlined="outlined" > </v-file-input> models.py class ClinicVisit(models.Model): upload_attachment = models.FileField(null=True , blank=True, upload_to='uploads/') views.py class ClinicVisitList(generics.ListCreateAPIView): serializer_class = ClinicVisitSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = ClinicVisitFilter permission_classes = [permissions.IsAuthenticated,] pagination_class = LargeResultsSetPagination ordering = ['-created_at'] parser_classes = [MultiPartParser, FormParser] queryset = get_user_model().objects.all() def get_queryset(self): return ClinicVisit.objects.based_on_access_level(self.request.user) def post(self, request, format=None, *args, **kwargs): file_serializer = ClinicVisitSerializer(data=request.data,instance=request.user) if file_serializer.is_valid(): file = request.FILES['file'] file_serializer.save() print('hello') return response.Response(file_serializer.data, status=status.HTTP_200_OK) else: print('error') return response.Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
Heroku Postgis - django releases fail with: relation "spatial_ref_sys" does not exist
Since Heroku changed their extension schema management (https://devcenter.heroku.com/changelog-items/2446) deployments to our existing django 4.0 application fail with the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedTable: relation "spatial_ref_sys" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 106, in handle connection.prepare_database() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 26, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "/app/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/__init__.py", line 544, in execute return real_execute(self, sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "spatial_ref_sys" does not exist Has anyone experienced the same issue? Is there … -
add manual parameters using drf-yasg, modelviewset
how do I add a manual parameters using drf-yasg? I need two parameters for product id and quantity this is what it looks like right now Swagger api, this is what i want to achieve RestFrameWorkBrowsableAPI. I've tried to add manual parameters with swagger_auto_schema decorators, but nothing changes. this is my views class OrderItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete','head', 'options'] def get_serializer_class(self): if self.request.method == 'PATCH': return UpdateOrderItemSerializer elif self.request.method == 'POST': return AddOrderItemSerializer return OrderItemSerializer def get_queryset(self): return OrderItem.objects.filter(order_id=self.kwargs['order_pk']).select_related('product') def get_serializer_context(self): return {'order_id': self.kwargs['order_pk']} this is my serializers class AddOrderItemSerializer(serializers.ModelSerializer): #product_id = serializers.IntegerField() product_id = openapi.Parameter('product', in_=openapi.IN_QUERY, type=openapi.TYPE_NUMBER) @swagger_auto_schema(manual_parameters=[product_id]) def save(self, **kwargs): order_id = self.context['order_id'] product_id = self.validated_data['product_id'] quantity = self.validated_data['quantity'] try: order_item = OrderItem.objects.get( order_id=order_id, product_id=product_id) order_item.quantity += quantity order_item.save() self.instance = order_item except OrderItem.DoesNotExist: self.instance = OrderItem.objects.create( order_id=order_id, **self.validated_data) return self.instance class Meta: model = OrderItem fields = ['id', 'product_id', 'quantity'] -
Use different delete behavior in admin-django and models.CASCADE
I have two Django models, one referencing the other with a ForeignKey. Something like this: class Data(models.Model): [some fields] class Backup(models.Model): data_source = models.ForeignKey(Data, on_delete=models.CASCADE) storage_destination = models.ForeginKey(S3Bucket, on_delete=models.CASCADE) The behavior I want is that After the deletion of a "Data" instance, Its backups get deleted from the S3 bucket (I can handle this by invoking a Temporal workflow like DeleteFromS3Workflow, no Django hack is needed), and after the completion of DeleteFromS3Workflow, the "Backup" model gets deleted from the database. Beyond this, I want to be able to delete a "Backup" object from Django admin without invoking the Temporal workflow and directly deleting the object from the database (the thing uncustomized delete() method of the model does). Overwriting the delete() method on the "Backup" model doesn't satisfy this as long as it deletes the model before the completion of workflow and this behavior is mutual in both cases. -
how to use prefetch_related or select_related with multitable inheritance
hey guys i have these models class Product(models.Model): ....... class Course(Product): ......... class Book(Product): ......... class Cart(models.Model): product = models.ForeignKey(Product) what I want is to prefetch the products with the Cart objects i know we can do this Cart.objects.select_related('product') but how do we also get the product to children too without making an impact on the performance and if i get it's children how can get it's child when accessing the product like: cart_instance.product.its_child -
how to Update the value of another model in Django Models
i want Contract_bills_amount field in class contract update from bills_mount field in class bills ? #Contract class Contract(models.Model): Contract_code = models.CharField(max_length=200) Contract_rec = models.DateTimeField('contract date ') Contract_total_amount = models.FloatField('total amount') Contract_deposit= models.FloatField('deposit') Contract_remainder_amount=models.FloatField('Contract remainder amount',null=True,blank=True) Contract_bills_amount=models.FloatField('bills_amount',null=True,blank=True) Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE) Contract_car = models.ForeignKey(Car, on_delete=models.CASCADE) def save(self, *args,**kwargs): a=self.Contract_total_amount b=self.Contract_deposit self.Contract_remainder_amount=a-b super(Contract,self).save(*args,**kwargs) def __str__(self): return self.Contract_code #Bills class bills(models.Model): bills_Contract = models.ForeignKey(Contract, on_delete=models.CASCADE) Contract_owner = models.ForeignKey(Client, on_delete=models.CASCADE) bills_code = models.CharField(max_length=200) Contract_rec = models.DateTimeField('date') bills_mount= models.FloatField('amount') def __str__(self): return self.bills_code strong text -
django CBV doesnt pagginate with editing context
View down below should show the tasks for the logged user but when I paginate the tasks I got Cannot filter a query once a slice has been taken. how should I filter the context to avoid the error for pagination? class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' template_name = 'TaskList.html' paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) return context -
django inspectdb-generated gitlab models throws errors when making migrations
i have generated inspectdb models for my django project. They are models generated from gitlab postgres database extracted by pg_dump. So now i have models.py file having something like 8k lines, and when trying to make migrations i get multiple errors. Some of the examples are: (They are mostly the same just with different variables) trackApp.Appearances.favicon: (fields.E121) 'max_length' must be a positive integer. or trackApp.AnalyticsDevopsAdoptionSegments.namespace: (fields.E304) Reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.namespace' clashes with reverse accessor for 'trackApp.AnalyticsDevopsAdoptionSegments.display_namespace'. I would be able to fix this by hand, but having a 8k lines long file makes this impossible. Is there any trick i could use to "mass-fix" these errors? -
unknow `runcrons` when running `python3 manage.py runcrons
When I run python3 manage.py runcrons, this message appears: "Unknown command: 'runcrons'". I run python3 manage.py help and couldn't find runcrons in the list of commands. How can I add runcrons to manage.py enter image description here -
Failed to push to heroku - Requested runtime (ÿþpython-3.8.0) is not available for this stack
When I try and push my django app to heroku I get the following error: Requested runtime (ÿþpython-3.8.0) is not available for this stack (heroku-20). This looks like an error with runtime.txt - I've tried changing the formatting from UTF-16 to UTF-8 which was suggested elsewhere. "ÿþ" was not included in my runtime.txt so this I why I think it's an encoding issue Does anyone know why this is occuring? Cheers! -
Problem with install GeoDjango Could not find the GDAL library
I followed with instruction: https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/ for Windows 10 I downloaded Postgres and added installed Postgis. Then OSGeo4W in the folder C:\OSGeo4W and maked point Modify Windows environment I create new project and one application. In settings.py added: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'geo', }, } After run py manage.py runserver I get a error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIB RARY_PATH in your settings. I add (Python Root)\Lib\site-packages\django\contrib\gis\gdal\libgdal.py "gdal305", becauuse this file i have in C:\OSGeo4W\bin. I get a error: FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal305.dll' (or one of its dependencies). Try using the full path with constructor syntax. (this path is good ) In settings.py I add: GDAL_LIBRARY_PATH = r'C:\OSGeo4W\bin\gdal505', but I'm showing the same error as before. So I try in settings.py: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] And I still get …