Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using @fontface with DigitalOcean Spaces
I've started learning to use django and have starting working on hosting one on Digital Ocean's App platform. I'm hosting my static files on Digital Ocean's Spaces. My CSS file loads just fine. My fonts, however, do not. My file structure is as folows: Project --Static ---CSS -CSS files ---Fonts - font files I set up my @font-face in the CSS file like this: @font-face { font-family: 'poppins'; src: url('../static/fonts/Poppins-Light.woff2') format('woff2'); } and apply the font as follows: .div-name{ height: 100px; font-family: 'poppins'; font-size: 40px; } Like I said, my CSS loads just fine, the fonts are just not showing up. What am i missing? Thanks for the help. -
want to sum the Price i get in dictionary in django rest. I want to do it using Model serializers
Hii there I want to add the price field of the 2 dictionary data using model serializers. Hoever i am able to access the data but not able to sum it .Also i want to show whole data as well as the sum of price but if i use this function it only shows me wether price or data one at a time class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" def to_representation(self, instance, a=0): a+=instance.Price return a class GenericViews(generics.ListCreateAPIView, generics.CreateAPIView, generics.DestroyAPIView,generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'Product_name' def filter_queryset(self, queryset): get_data = self.request.GET if get_data.get('Product_name'): return queryset.filter(Product_name=get_data['Product_name']) return queryset I get this if i add this to_representation function in Serializers i want to get the sum of these values i want to show whole data as well as the sum of price but if i use this function it only shows me wether price or data one at a time -
Why is my debug Django server takes so long to load on my localhost? I'm using Django, django-compressor, django-libsass and bootstrap
I have a problem with developing a Django website. I started out with using CDN Boostrap and JS as recommended in Boostrap 5 docs but then I wanted to customize the CSS, so I changed the setup to compile Bootstrap's source scss files with django-libsass. I followed the installation guides for django-libsass and django-compressor. What I discovered is that while everything works, it works very slow on my local machine (5-6s per opening a new page). I'm not very experienced in web development so I'm not sure what could be causing this. If it's relevant, I don't use a frontend yet and I'm sticking to Django's templates. I tried to download a sample django libsass project and put bootstrap there and the outcome was the same. I expected the time for loading the pages to increase slightly due to the fact that now it has to compile scss files but not so much. Googling turned up no results:( Is this an expected behavior when debugging from a local machine or am I missing something? Huge thanks! -
Is there a way to implement select all/select none option in django-select2?
I found a few (older) answers where someone attempted to implement a select all/select none option in a jQuery dropdown list: https://github.com/select2/select2/issues/195 Select2 select all dropdown option I was wondering, is there a way to implement such a thing also in django-select2? My JavaScript coding capabilities are unfortunately very limited. Simply replacing select2 with djangoSelect2 or django-select2 in the proposed JavaScript didn't do the trick. It starts with the fact that $.fn.djangoSelect2.amd is undefined. -
Call to Stripe API leads to unexpected user logout from Django session
I have a simple Django view where I issue a call to Stripe API (PaymentMethod.detach), and then I am redirecting to a new page: from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import redirect import stripe stripe.api_key = "secret" @login_required def view(request, method_id): if request.method == 'POST': stripe.PaymentMethod.detach(method_id) return redirect('new-page') else: template = " ... " context = { ... } return HttpResponse(template.render(context, request)) DEV settings.py: DEBUG = True SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = not DEBUG CSRF_COOKIE_SECURE = not DEBUG The problem is that I recently found out that my user is getting logged out from Django when redirected to the new-page. This happens 100% of the time. I believe this is related to the Stripe call because there is nothing else in that view and also when I comment out the Stripe call, then no logout occurs. I have tried a bunch of different SESSION settings but nothing worked so far. I am currently trying to understand what is triggering the logout in the SESSIONS middleware. Any tips on what the issue might be will be greatly appreciated! python == 3.10.6 django == 4.1.6 stripe == 5.1.1 -
Permission denied (publickey,password) Apache in Ubuntu 20.04LTS
I obtain the above mentioned error "Permission denied (publickey,password)" when trying to connect with ssh using my apache server. The framework I have used is Django and when deploying it locally (with python) the ssh communication works perfectly. However, when I deploy it with apache on every ssh, scp communication I obtain the error. I have changed apache User to other than www-data and I got the same result. Obviously, ssh keys for both users are stored in both machines and they work perfectly without using apache. I dont know if it would be possible for apache to look for ssh keys at any specific folder or how to change the default directoy. Any help is much appreciated! -
Find the nearest longitude and latitude
I have a table with latitude and longitude columns with 1000 rows I want when I give latitude and longitude It should return a matching lat-long result and if lat and long are not found in the database can give the nearest lat long from the database table table ------------------------------------------------| id | name | lat | long| | ---|------|-----------------|-------------------| 1 | test |27.988865824076 | 77.8523526316 | I am passing in the request body { "latitude": 27.98681188240762, "longitude": 77.86585050166316 } and expecting ht nearest matching result -
Django Python MQTT Subscribe onMessage got executed two times
I've my Mosquitto MQTT broker and I've created a simple Django APP that subscribes to the topic $SYS/broker/uptime like below from django.apps import AppConfig from threading import Thread import paho.mqtt.client as mqtt class MqttClient(Thread): def __init__(self, broker, port, timeout, topics): super(MqttClient, self).__init__() self.client = mqtt.Client() self.broker = broker self.port = port self.timeout = timeout self.topics = topics self.total_messages = 0 # run method override from Thread class def run(self): self.connect_to_broker() def connect_to_broker(self): self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.connect(self.broker, self.port, self.timeout) self.client.loop_forever() # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): self.total_messages = self.total_messages + 1 print(str(msg.payload) + "Total: {}".format(self.total_messages)) # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): # Subscribe to a list of topics using a lock to guarantee that a topic is only subscribed once for topic in self.topics: client.subscribe(topic) class AppMqtteConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app_mqtt' def ready(self): MqttClient("localhost", 1883, 60, ["$SYS/broker/uptime"]).start() For some reason, the print statement on the on_message callback got executed two times, at least from what I'm seeing from the console. See screenshot. I can't understand why -
How to create right relations between models in Django project
I am developing Django progect with following models: class Aircraft_fleet(models.Model): Aircraft_type = models.CharField(max_length=16) Aircraft_Serial_Number = models.CharField(max_length=16) Engine_1_Ser_Num = models.ForeignKey('Engine', related_name='Engine_1', on_delete=models.PROTECT) Engine_2_Ser_Num = models.ForeignKey('Engine', related_name='Engine_2', on_delete=models.PROTECT) class Engine(models.Model): Ser_Num = models.PositiveIntegerField() Flight_Num = models.CharField(max_length=80) Flight_Date = models.DateField() Oil_Quantity_Departure = models.DecimalField(max_digits=5, decimal_places=2) Oil_Quantity_Arrival = models.DecimalField(max_digits=5, decimal_places=2) Oil_Temperature_Departure = models.DecimalField(max_digits=5, decimal_places=2) Oil_Temperature_Arrival = models.DecimalField(max_digits=5, decimal_places=2) One Aircraft (Aircraft_fleet model) have two Engine Ser_Num (different of course). Particular Engine Ser_Num (Engine model) is fitted only on one partucular Aircraft. The thing is that in database, "Engine" table has multiple records for each Engine "Ser_Num". See picture below: Engine Model in database look like: I can't determine how to create the proper relations between these two models. Currently, relation is one to many, but it doesn't work. Following error apears: django.db.utils.IntegrityError: The row in table 'oilcons_aircraft_fleet' with primary key '1' has an invalid foreign key: oilcons_aircraft_fleet.Engine _2_Ser_Num_id contains a value '193262' that does not have a corresponding value in oilcons_engine.id. -
Converting List to QuerySet Django
models.py class Part(models.Model): series = models.CharField(max_length=100) number = models.CharField(max_length=100) brand = models.CharField(max_length=100) class Request(models.Model): part_number = models.ForeignKey(Part, on_delete=models.CASCADE) brand = models.CharField(max_length=100) quantity = models.PositiveIntegerField() date = models.DateField() class Quota(models.Model): part_number = models.ForeignKey(Part, on_delete=models.CASCADE) brand = models.CharField(max_length=100) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) supplier = models.CharField(max_length=100) date = models.DateField() views.py def requests_and_quotas(request): requests = Request.objects.all() quotas = Quota.objects.all() result = [] for req in requests: match = False for quo in quotas: if (req.part_number.series == quo.part_number.series) and (abs((req.date - quo.date).days) <= 2): result.append({'request': req, 'quota': quo}) if not match: result.append({'request': req, 'quota': None}) return render(request, 'requests_and_quotas.html', {'result': result,}) I wanted to connect django_filters, but ran into a problem AttributeError: 'list' object has no attribute '_meta'. How can I change the logic of my code to retrieve a QuerySet object? result_qs = QuerySet(result) it didn't help -
how to get task status in celery
I have a celery task and I want the status of the task using task ID. I have read the previous answers but couldn't make it work. I used the command celery -A proj inspect query_task e9f6c8f0-fec9-4ae8-a8c6-cf8c8451d4f8pe command result celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) stream = os.popen( "ffmpeg.ffprobe -loglevel error -select_streams a … -
Error ! Please! Make sure all fields are entered and valid
Have been trying to use Django forms for contact tab - but getting the - Error ! Please! Make sure all fields are entered and valid. **forms.py ** from django import forms from content.models import Contact class ContactForm(forms.ModelForm): fullname = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100) subject = forms.CharField(required=True,max_length=300) phone_number = forms.CharField(required=True,max_length=100) message = forms.CharField(required=True,widget=forms.Textarea) class Meta: model = Contact fields = [ 'fullname', 'email', 'subject', 'message', 'phone_number', ] def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['fullname'].widget.attrs['placeholder'] = 'Your FullName' self.fields['fullname'].widget.attrs['class'] = 'form-control form-control-lg' self.fields['email'].widget.attrs['placeholder'] = 'Your Email' self.fields['email'].widget.attrs['class'] = 'form-control form-control-sm' self.fields['subject'].widget.attrs['placeholder'] = 'Subject' self.fields['subject'].widget.attrs['class'] = 'form-control form-control-sm' self.fields['phone_number'].widget.attrs['placeholder'] = 'Your Phone Number' self.fields['phone_number'].widget.attrs['class'] = 'form-control' self.fields['message'].widget.attrs['placeholder'] = 'Your Message' self.fields['message'].widget.attrs['cols'] = '30' self.fields['message'].widget.attrs['rows'] = '10' views.py from email.message import EmailMessage from django.shortcuts import render from content.forms import ContactForm from content.models import About, Profile,Primaryskill,Secondaryskill,Services,Portfolio,Blog,Testimonial,Contact from django.contrib import messages #for sending emails and contact from django.http import HttpResponseRedirect from django.core.mail import send_mail from django.conf import settings from django.template.loader import render_to_string from django.template import loader # Create your views here. def Homepage(request): #django orm concept profile = Profile.objects.first() #this will fetch all the data from Profile table first row and store it in profile about = About.objects.first() primaryskill = Primaryskill.objects.all() secondaryskill = Secondaryskill.objects.all() … -
Django : pre-filled forms by database
I created travels (pretty much like products) for my site and I want an admin to chnage some informations about those. So I created a form to change the informations. But I want the form to be pre-filled with the actual informations so the admin just have to change what he wants to change. I've been trying different ways to do it but it never worked. Here is my form : `class ModifAvantTravel(forms.ModelForm): class Meta : model = Travel fields = ['prix', 'description', 'quantite', 'date_depart', 'date_retour', 'lieu', 'affichage'] widgets = { 'prix': forms.NumberInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'quantite': forms.NumberInput(attrs={'class': 'form-control'}), 'date_depart': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), 'date_retour': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), 'lieu': forms.TextInput(attrs={'class': 'form-control'}), 'affichage': forms.CheckboxInput(attrs={'class': 'form-check-input'}), }` Here is my view : `def update_travel(request,id): travel = Travel.objects.get(pk=id) if request.method == 'POST': fm = ModifAvantTravel(request.POST, instance=travel) if fm.is_valid(): fm.save() return redirect("/accueil/gestion/") else: fm = ModifAvantTravel(instance=travel) context = { 'form': fm, } return render(request, 'accueil/update_product.html', context)` I've tried the view : `def update_travel(request,id): travel = Travel.objects.get(pk=id) if request.method == 'POST': fm = ModifAvantTravel(request.POST, instance=travel) if fm.is_valid(): fm.save() return redirect("/accueil/gestion/") else: fm = ModifAvantTravel(instance=travel, initial={'prix': travel.prix, 'description': travel.description, 'lieu': travel.lieu, 'date_depart': travel.date_depart, 'date_retour': travel.date_retour, 'quantite': travel.quantite, 'affichage': travel.affichage}) context = { 'form': fm, … -
How to fix 2005 (HY000): Unknown MySQL server host 'db' (8)
I want to run the database with mysql.connector to create a dataframe, but I caught the problem 2005 (HY000): Unknown MySQL server host 'db' (8) after running with python manage.py runserver. associationrule.py import os import pandas as pd import mysql.connector con = mysql.connector.connect(user='user', password='mariadb', host='db', database='mariadb', port='9051') dfParcel = pd.read_sql("SELECT * FROM LoanParcel", con) dfDurable = pd.read_sql("SELECT * FROM LoanDurable", con) docker-compose.py version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 9051:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:9051/mariadb ports: - "9052:8000" depends_on: - db volumes: mysqldata: -
How to display a query on DetailView in Django?
I want my "CustomDetailView" to display a query(a single "flashcard"). I was able to it by using ListView CustomListView(ListView): model = Flashcard template_name = 'flashcards.html queryset = Flashcard.objects.all()[:1] But for DetaiView I'm getting this error Generic detail view CustomDetainView must be called with either an object pk or a slug in the URLconf. class FlashTemplateView(DetailView): model = Flashcard template_name = "flashcards.html" queryset = Flashcard.objects.all().first() How to fix this? -
How to set userkey_id with @setter and token in django?
I have created a client frontend and have tested the url using cUrl and it works, sending the auth token via axios headers allows me in to call the api. The problem is that I get a NOT NULL constraint failed: post_post.userkey_id error and have narrowed it down that the @user.setter is not getting the CustomUser from the Auth Token. How can I correctly use the @user.setter to set the user that has the corresponding auth token/created the post from the client frontend. Views.py class CreatePost(generics.CreateAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self,serializer): serializer.save(user = self.request.user) Post model.py from django.db import models from accounts.models import CustomUser class Post(models.Model): #foriegn keys userkey = models.ForeignKey(CustomUser, on_delete=models.CASCADE) #properties title = models.CharField(max_length=100,blank=True) image= models.FileField(upload_to='files/', null=True, verbose_name="",blank=True) #image field price = models.IntegerField(default=0,blank=True) description = models.TextField(blank=True) likes = models.IntegerField(default=0) tags = models.CharField(max_length=30,blank=True,default="tag1,tag2,...") #sqlite doesnt support arrays date_modified = models.DateTimeField(auto_now=True,blank=True) created = models.DateTimeField(auto_now_add=True,blank=True) sold = models.BooleanField(default=False,blank=True) @property def user(self): return self.userkey.username @user.setter def user(self,value): return models.ForeignKey(CustomUser,on_delete=models.CASCADE) @property def datejoined(self): return self.userkey.date_joined def __str__(self): return self.title The userkey is to get data from the user thus I have a @property def user function to collect data from another object. The userkey and @property def user work fine … -
Celery will continue to execute historical tasks after the worker terminates abnormally and restarts
I added the celery crontab task. When an exception occurs in the worker, I hope that the worker will no longer execute unfinished historical tasks. I used the following task base class and wanted to preprocess the task by judging the status of the worker, but it didn't achieve the result I expected. When I stop the worker, after the time exceeds the task execution time, I restart the worker, it still executes the expired task. class MyTask(Task): def before_start(self, task_id, args, kwargs): inspect = app.control.inspect() active_workers = inspect.active() if not active_workers: print('worker not runing') return False print('worker runing') return super().before_start(task_id, args, kwargs) @app.task(base=MyTask) def test(): return 'test' I hope there is any method or parameter setting that can make the worker no longer execute expired tasks -
Using django crispy-forms wrap to wrap multiple properties
I have a form with lots of repetition and I want to use the wrap function of django crispy forms to reduce this. This is the form as it stands: class MyForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Row(Field(PrependedText('field1', 'Field1title', wrapper_class='col-12 stretchprepend')), title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip', data_bs_placement='bottom', data_html="true"), #fields 2-29 Row(Field(PrependedText('field30', 'Field30title', wrapper_class='col-12 stretchprepend')), title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip', data_bs_placement='bottom', data_html="true") ) CHOICES = [tuple([x,x]) for x in range(1,8)] help_text = {'field1': ''''help text for field 1''' #etc for other fields) field1 = IntegerField( label='Field1title', widget=Select(choices=CHOICES), help_text=help_text['field1']) # Repeat up to field 30 class Meta: model = mymodel fields = ['field1',...,'field30'] I can get wrap to generate some aspects of the form like so: self.helper.layout('field1'...'field30') self.helper[:].wrap(Field, wrapper_class='col-12 stretchprepend') I cant' seem to get it to work to include all the other aspects e.g. PrependedText, title, data_bs_toggle etc Please could anyone advise? -
The code is not taking json payload as post request in terminal but its working in postman
from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from myapp.models import Car import json def get_car(request, car_name): if request.method == 'GET': try: car = Car.objects.get(name=car_name) response_data = {'Car': car.name, 'Top Speed': car.top_speed} return JsonResponse(response_data) except Car.DoesNotExist: return JsonResponse({'Error': f'No car with name "{car_name}" found!'}) @csrf_exempt def add_car(request): if request.method == 'POST': try: payload = json.loads(request.body.decode('utf-8')) car_name = payload['car_name'] top_speed = payload['top_speed'] car = Car(name=car_name, top_speed=top_speed) car.save() response_data = {'Success': 'Car added successfully!'} except: response_data = {'Error': 'Car could not be added!'} print(response_data) return JsonResponse(response_data) -
Issue using nested serializer with django-rest-framework
I'm trying to create a nested serializer, UserLoginSerializer , composed of a UserSerializer and a NotificationSerializer, but I'm getting this error when it tries to serialize: AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserSerializer instance. Original exception text was: 'UserSerializer' object has no attribute 'email'. Here is my models.py: class Notification(models.Model): kind = models.IntegerField(default=0) message = models.CharField(max_length=256) class User(AbstractUser): username = models.CharField(max_length=150, blank=True, null=True) email = models.EmailField(unique=True) customer_id = models.UUIDField(default=uuid.uuid4, editable=False) And my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "first_name", "last_name", "email", "customer_id" ] class NotificationSerializer(serializers.ModelSerializer): class Meta: model = Notification fields = [ "id", "kind", "message", ] class UserLoginSerializer(serializers.Serializer): user_info = UserSerializer(read_only=True) notifications = NotificationSerializer(many=True, read_only=True) The error occurs at the last line in this endpoint: def get_login_info(self, request): notifications = Notification.objects.filter(recipient=request.user) serializer = UserLoginSerializer( { "user_info": UserSerializer(request.user), "notifications": NotificationSerializer(notifications, many=True), } ) return Response(serializer.data) What am I doing wrong? -
Assiging the lastest terms and condtions to users upon sign in
I have the following model for the terms and conditions: class TermsAndConditions(models.Model): text = models.TextField() date_modified = models.DateTimeField(auto_now=True) def __str__(self): return f'Terms and conditions, last modified on {self.date_modified}' class UserAgreement(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) agreed = models.BooleanField(default=False) agreed_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) terms_and_conditions = models.ForeignKey(TermsAndConditions, on_delete=models.PROTECT) def __str__(self): return f'Agreement for user {self.user.username}' I have the following views: @login_required def show_terms_and_conditions(request): try: user_agreement = UserAgreement.objects.get(user=request.user) except UserAgreement.DoesNotExist: user_agreement = UserAgreement.objects.create(user=request.user) terms_and_conditions = user_agreement.terms_and_conditions return render(request, 'tac/termsandconditions.html', {'terms_and_conditions': terms_and_conditions}) @login_required def agree(request): if request.method == "POST": user_agreement = UserAgreement.objects.get(user=request.user) user_agreement.agreed = True user_agreement.save() return redirect(reverse('........')) else: return redirect(reverse('.......')) My objective to to assign the latest terms and conditions to every user who signs in and if it is not agreed then to show here is what I tried # @login_required # def show_terms_and_conditions(request): # latest_tac = TermsAndConditions.objects.latest('date_modified') # user_agreement, created = UserAgreement.objects.get_or_create(user=request.user, terms_and_conditions=latest_tac) # if created: # # If the user agreement was created in this request, set `agreed` to False and update the `agreed_at` field # user_agreement.agreed = False # user_agreement.agreed_at = timezone.now() # user_agreement.save() # terms_and_conditions = user_agreement.terms_and_conditions # # return render(request, 'tac/termsandconditions.html', {'terms_and_conditions': terms_and_conditions, 'user_agreement': user_agreement}) The reason I am doing this is because I keep … -
Django migrations deployment strategy with AWS ECS Fargate?
What is the recommended deployment strategy for running database migrations with ECS Fargate? I could update the container command to run migrations before starting the gunicorn server. But this can result in concurrent migrations executing at the same time if more than one instance is provisioned. I also have to consider the fact that images are already running. If I figure out how to run migrations before the new images are up and running, I have to consider the fact that the old images are still running on old code and may potentially break or cause strange data-corruption side effects. I was thinking of creating a new ECS::TaskDefinition. Have that run a one-off migration script that runs the migrations. Then the container closes. And I update all of the other TaskDefinitions to have a DependsOn for it, so that they wont start until it finishes. -
Property destructuring pattern expected.javascript
How to fix this ',' expected.javascript Property destructuring pattern expected.javascript var map_{{ forloop.counter }} = new google.maps.Map(document.getElementById('map_{{ forloop.counter }}'), { zoom: 8, center: {lat: {{ image.lat }}, lng: {{ image.lon }}} }); var marker_{{ forloop.counter }} = new google.maps.Marker({ position: {lat: {{ image.lat }}, lng: {{ image.lon }}}, map: map_{{ forloop.counter }} }); -
Django on Ubuntu giving libpq version 10 error
I am trying to setup a Django website on linux ubuntu with postgresql, gunicorn and nginx. However every time I try to start the development server I get this following error: Traceback (most recent call last): File "/home/ubuntu/personalserver/manage.py", line 22, in <module> main() File "/home/ubuntu/personalserver/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor return self._cursor() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor self.ensure_connection() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection with self.wrap_database_errors: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, … -
Can´t find a way to change the initial value of the primary key id, and make start from it on my models
I really apreciate somebody's help.... I am working on django, so I created my table on my models.py.... by default when I start registering data, the id, set as primary key, begins with the initial value #1 and counting on each time I do a new register. But, I have loaded some data in my table, so the final id right now is 185. I runserver and try to add a new register, but I get an error about id duplicity..... django is trying to save in id # 1 the actual register.... but I want it to continue saving the register from id #186 and counting on... I have tried doing this on my models: class MyModel(models.Model): id = models.AutoField(primary_key=True, initial=123) but it does not recognizes the kwarg 'initial' So I am stuck right now....