Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having issues converting api json stream into an array in Flutter
The django api I am working with has the following actions user api (url = website/user/): action: CREATE_USER necessary params: action, email_address, password note: action = 0 action: LOGIN necessary params: action, email_address, password note: action = 1 action: CHANGE_PASSWORD necessary params: action, email_address, password, new_password note: action = 2 action: DELETE_USER necessary params: action, email_address, password note: action = 3 entry api (url = website/entry/): action: MAIN_PAGE necessary params: action note: action = 0 action: SEARCH_KEYWORD necessary params: action, keyword note: action = 1 action: FILTER_YEAR necessary params: action, first_year, second_year note: action = 0 note: if filter is for 1 year, first_year and second_year should be equal archive api (url = website/archive/): action: CREATE_ARCHIVE necessary params: action, email_address, password, keyword, frequency note: action = 0 note: frequency has to be 'daily', 'week', 'biweek', or 'month' action: DISPLAY_USER_ARCHIVES necessary params: action, email_address, password note: action = 1 note: to return entries pulled from archive, use action SEARCH_KEYWORD using the keyword saved in the archive action: DELETE_ARCHIVE necessary params: action, email_address, password, keyword note: action = 2 action: UPDATE_FREQUENCY necessary params: action, email_address, password, keyword, new_frequency note: action = 3 note: frequency has to be 'daily', 'week', 'biweek', or 'month' … -
Reduce stock in the database with django
I created a stock for the coffee beans in the database, and want to decrease the stock whenever CoffePods are created indicating the decrease of the beans stock. How to reduce the CoffeBeans stock in the database each time I create CoffePods which is received as a query parameter from the URL and what is the best practice in this case? views.py class PodsViewSet(viewsets.ModelViewSet): queryset = CoffePods.objects.all().order_by('id') serializer_class = CoffePodsSerializer serializer_class = CoffeBeansSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = '__all__' def create(self, request, *args, **kwargs): print("Coffe Pod Created!") try: pods_pack_size = int(self.request.query_params.get('pack_size')) coffe_beans = CoffeBeans.objects.all()[0] if coffe_beans.capacity > 2.0 and coffe_beans.quantity > 4: if pods_pack_size == 1: coffe_beans.capacity -= 0.5 coffe_beans.quantity -= 1 coffe_beans.save() elif pods_pack_size == 2: coffe_beans.capacity -= 1.0 coffe_beans.quantity -= 2 coffe_beans.save() elif pods_pack_size == 3: coffe_beans.capacity -= 1.5 coffe_beans.quantity -= 3 coffe_beans.save() elif pods_pack_size == 4: coffe_beans.capacity -= 2.0 coffe_beans.quantity -= 4 coffe_beans.save() except Exception as e: raise e return Response(coffe_beans) models.py class CoffeBeans(models.Model): capacity = models.FloatField(validators=[MinValueValidator(0.0)], default=100) quantity = models.PositiveIntegerField(default=200) class Meta: verbose_name_plural = 'Coffe Beans' def __str__(self): return f"{self.capacity} KG - {self.quantity} Pack" -
DRF - How to concatanate serialized model with custom field
i need to concatanate serialized models with custom field = list[] i have a user_profile model and i want to know if particular user is "mine(active user's)" friend, in the users list (list_boolean = ["True", "False", "True"]) views.py class User_profile_view(APIView): def get(self, request): #this is example list which i need to link list_boolean = ["True", "False", "True"] query = User_profile.objects.all() User_profile.objects.filter(pk=1).delete() serializer_class = User_profile_serializer(query, many=True) return Response(serializer_class.data) models.py class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) age = models.CharField(max_length=100) city = models.CharField(max_length=100) serializer.py class User_profile_serializer(serializers.ModelSerializer): class Meta: model = User_profile exclude = ["id"] is here any way to link particular list, to objects? it might be inside of the object (which is better) or outside -
Why I can't log in with this django login code, the message says: "Authentication credentials were not provided"
This is my views.py LoginView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, request): if request.method == 'POST': email = request.data.get('email', None) print(email) password = request.data.get('password',None) print(password) user = authenticate(request, email= "email", password= "pasword") print(user) if user : login(request, user) print("punto1") return Response(status=status.HTTP_200_OK) return Response( status=status.HTTP_404_NOT_FOUND) The output is: 403 Forbiden { "detail": "Authentication credentials were not provided." } -
Getting a database error when using Djongo to connect Django with MongoDB
Here is the entire error I am getting. I have tried looking everywhere for an answer and I am just lost. I have been trying to deploy, but I have been stuck with this error for months now. Internal Server Error: /profile/1/ Traceback (most recent call last): File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 152, in parse self.where = WhereConverter(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 119, in parse self.op = WhereOp( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 475, in __init__ self._statement2ops() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 413, in _token2op raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT "post_app_screammodel"."id", "post_app_screammodel"."content", "post_app_screammodel"."posted_by_id", "post_app_screammodel"."creation_time" FROM "post_app_screammodel" WHERE "post_app_screammodel"."posted_by_id" = %(0)s OFFSET 3',) Params: ((1,),) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Heroku set-cookie header was blocked because its domain attribute was invalid with regards to the current host url
I have a django app using htmx for a form and it's hosted on Heroku with Gunicorn as application server. I am getting 403 forbidden when I try to submit the form and tried a few different settings from reading the Django 4 docs. The form works on my local but not on Heroku. What else should I try so I can submit my htmx form with https on Heroku? my template <form hx-post="{{ request.path }}" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="modal-content"> ... <script>document.body.addEventListener('htmx:configRequest', (event) => {event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';)</script> my settings.py CSRF_COOKIE_DOMAIN = '.herokuapp.com' CSRF_TRUSTED_ORIGINS = ['https://django-example.herokuapp.com','http://django-example.herokuapp.com'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Response headers csrftoken=GjeYwnfTwUGLzF7DSJWOoaJk1GHiSC3MffaLaornrd4ENDgKlokkHsyoIERTReB4; Domain=.herokuapp.com; expires=Mon, 06 Mar 2023 18:01:01 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure ! This attempt to set a cookie via a set-cookie header was blocked because its domain attribute was invalid with regards to the current host url Heroku logs 022-03-07T18:59:13.184551+00:00 app[web.1]: Starting server 2022-03-07T18:59:16.297718+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Starting gunicorn 20.1.0 2022-03-07T18:59:16.298014+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Listening at: http://0.0.0.0:28553 (10) 2022-03-07T18:59:16.298062+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Using worker: sync 2022-03-07T18:59:16.301273+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [12] [INFO] Booting worker with pid: 12 2022-03-07T18:59:16.704678+00:00 … -
Python + Django + Gunicorn on AWS: 2 workers, worker terminated due to signal 15 -> Failed to boot
I'm pretty new using django + gunicorn + aws. Im struggling to find the problem on "signal 15 from gunicorn". Below are the log file from gunicorn. https://github.com/benoitc/gunicorn/issues/2755 -
Django - Cancel one delivery but when cancelling one it cancels all the deliveries
I'm trying to cancel one "posted" delivery when the user clicks on the button "cancel", but it cancels all the posted deliveries below is the views.py views html models Here is the list of deliveries I want to cancel one delivery and it automatically moves to the "Done/Cancelled Deliveries" page. -
How to upload multiple images to a form divided into 3 tabs?
I have a form divided into 3 tabs, in tab 2 and in tab 3 you have to upload multiple images respectively. The information that I have found about it, for the most part I do not understand and the one that I have seen easily, throws me many errors, can you help me tell me what I am doing wrong? Thanks models.py class Carro(models.Model): placas=models.CharField(max_length=255) marca=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, upload_to="images/") garantia=models.ImageField(null=True, upload_to="images/") fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.marca}{self.cliente}{self.fotosCarro}{self.garantia}' \ f'{self.fecha_registros}' forms.py class CarroForm(forms.ModelForm): class Meta: model=Carro fields = ['placas','marca','cliente','fotosCarro','garantia'] exclude = ['fecha_registros'] widgets = { 'placas': forms.TextInput( attrs={ 'class': 'form-control', } ), 'marca': forms.TextInput( attrs={ 'class': 'form-control' } ), 'cliente': forms.Select( attrs={ 'class': 'form-select' } ), 'fotosCarro':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-input', 'onchange':'preview()', } ), 'garantia':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-inputz', 'onchange': 'previewz()', # 'id':'pro-images', # 'click': "$('#pro-images').click()", } ), 'fecha_registros': forms.DateInput( attrs={ 'class': 'form-control', } ), } views.py def create_carros(request): form = CarroForm(request.POST or request.FILES) if request.method == 'POST': form = CarroForm(request.POST or request.FILES) fotosCarro = request.FILES.getlist('fotosCarro') garantia = request.FILES.getlist('garantia') for img in fotosCarro: Carro.objects.create(fotosCarro=fotosCarro) Carro.objects.create(garantia=garantia) images=Carro.objects.all() if form.is_valid(): form.save() return redirect('carros/index.html') return render(request, "carros/carros-form-add.html", {'form': form}) -
Json transferred in javascript
jsonData = { "a":{ "b":{ "c":"d" ,"e":"f" } ,"g":{ "h":"i" ,"j":"k" ,"m":"n" } ,"l":{ "o":"p" ,"q":"r" } } } } How do you create an array starting with a with JavaScript and transfer it to the jsondata function? -
Django CASCADE deletion not working and throws IntegrityError
I'm running into this bug with cascade deletion which is frustrating as I couldn't figure out what the root cause is. I use PostgresQL and I have the following database models: class Subdomains(models.Model): subdomainid = models.AutoField(db_column='subdomainid', primary_key=True) subdomainname = models.TextField(db_column='subdomainname', unique=True, ) class Meta: managed = True db_table = 'subdomains' class Dnsdata(models.Model): dnsid = models.AutoField(db_column='dnsid', primary_key=True) dnsa = models.TextField(db_column='dnsa', blank=True, null=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, db_column='subdomainid') class Meta: managed = True db_table = 'dnsdata' class Issues(models.Model): issueid = models.AutoField(db_column='issueid', primary_key=True) class Meta: managed = True db_table = 'issues' class Alerts(models.Model): alertid = models.AutoField(db_column='alertid', primary_key=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, blank=True, null=True, db_column='subdomainid') dnsid = models.ForeignKey(Dnsdata,on_delete=models.CASCADE, blank=True, null=True, db_column='dnsid') issueid = models.ForeignKey(Issues,on_delete=models.CASCADE, blank=True, null=True, db_column='issueid') # FK can be null class Meta: managed = True db_table = 'alerts' Whenever I try to remove an object from Subdomains table as follows: Subdomains.objects.filter(subdomainid=1).delete() it throws the following error: django.db.utils.IntegrityError: update or delete on table "subdomains" violates foreign key constraint "alerts_subdomainid_be56ec78_fk_subdomains_subdomainid" on table "alerts" DETAIL: Key (subdomainid)=(1) is still referenced from table "alerts". Please note that I've used on_delete=models.CASCADE and Foreign Keys in Alerts table can be null as well. -
crontab is not working with docker django
I'm setting up the cron job in my Django project, when I go to add the corn using this command python manage.py crontab add in my docker container so I got the following error. error: /bin/sh: 1: /usr/bin/crontab: not found settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('0 0 * * *', 'projects.views.notifications_cron') ] and I want to run my corn job after every 24 hours at 12am midnight. -
Getting an "Integrity Error Exception Value: NOT NULL constraint failed" in my Django application
I keep getting an integrity error for a particular table on my database - the review table, whenever a user tries to review a selected movie. I have gone through my codes line by line but can't seem to find the error. Please help! I always get an "IntegrityError Exception Value:NOT NULL constraint failed: movieworld_review.review_number" whenever the user tries to review a movie. I even tried setting the review_number to null=True, yet a new integrity constraint pops up, this time it is that "NOT NULL CONSTRAINT FAILED: MOVIEWORLD_REVIEW.MOVIE.ID". BELOW ARE MY CODES FOR THE VIEW AND MODEL: MODELS: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') picture = models.ImageField(upload_to = 'profile_images', blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) SIZE = 250, 250 if self.picture: pic = Image.open(self.picture.path) pic.thumbnail(SIZE, Image.LANCZOS) pic.save(self.picture.path) def __str__(self): return self.user.username class Genre(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(null=False, unique=True) def get_absolute_url(self): return reverse('genres', args=[self.slug]) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.title.replace(" ", "") self.slug = slugify(self.title) return super().save(*args, **kwargs) class Movie(models.Model): imdbID = models.CharField(max_length=20, blank=True) Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank = True) Genre = models.ManyToManyField(Genre, blank=True) Language = models.CharField(max_length=250, blank=True) Poster = models.ImageField(upload_to='movies', blank = True) Poster_url = models.URLField(blank=True) TotalSeasons … -
python3 manage.py migrate gives error about field even when it is deleted from the model class
Every time I run python3 manage.py migrate I get the same error about one of the fields in the model class. Even after deleting the field, the same error occurs. This is what the model class looks like: class Events(models.Model): name = models.CharField(max_length=200, null=True) date = models.DateTimeField(editable=True, null=True) sport = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) num_seats = models.IntegerField(null=True, blank=True) creator = models.CharField(max_length=200, null=False) And this is what the error looks like: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'IntegerField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 22, in <module> main() File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 253, in handle post_migrate_state = executor.migrate( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 126, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 156, in _migrate_all_forwards state … -
Django Query many to many field count miscalculation
I am creating a Django Blog Website and I am stuck at one point finding the no of likes on a specific post. I have created a webpage where all the posts are displayed. Now the problem I am facing is the no of likes are getting calculated wrong. Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") def __str__(self): return self.title Query in Views.py file to fetch all the posts -> posts = Post.objects.select_related().prefetch_related('images_set').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now when I see the post.Likes__count in template it shows wrong count of 6 for one specific post but when I use post.likes.count() it shows count of 3. for other posts they both show same result. I am unable to find out why it is happening. This is the result for that specific post -> {'post_id': 22, 'user_id': 1, 'title': 'wkjdfh', 'description': 'kjwdfn', 'Tags': '.,smdf,m', 'category': <Category: Shoes>, 'userName': 'admin', 'images': <QuerySet [<Images: Images object (10)>, <Images: Images object (11)>, <Images: Images object (12)>, <Images: Images object (13)>]>, 'comments_count': 6, 'likesCount': 6, 'actualLikeCount': 3} This is very … -
How to safely execute user-written code in the backend?
I'm trying to build a Django web application that allows users to write Python code and runs that in the backend, kinda like how an IDE would work. I'm just wondering, what security risks does this come with? I'm sure there are plenty, the user could literally do anything with that code, so what would be a good solution to safely do this? Would running it inside a Docker container be a good solution? -
Django Authentication Application
I've just started to the django and got a little lost in between various doumentations and outdated tutorials. What I want to achieve is to create a simple dashboard application that also contains some backend scripts to integrate various apis most of them are open API's like weather API's , calendar API's etc just for learning. But I need to create a login page for the application and current tutorials for the authentication mosule of django is a little bit cunfusing as it never gives me how to implemelent a login form to the auth backend. I need a little bir more simple documentation for that. Is there anyone able to help me on that. I know the question is not code related but still any help will be appriceated. Most of findings from my previous searches are outdated and implementing those methods are often causes errors like non-existent templates etc... Meanwhile I'll be also checking the offical documentation. Thank you. -
Hashicorp Vault - Django query from docker container
Good afternoon, I have a two docker containers, one running a django app and the other running Hashicorp Vault as I am starting to play with Vault in a dev environment. I am using HVAC from a django view to write a secret to the vault that is entered by a user to set up an integration to a REST API for a data pull. When I run the following from my host machine, it writes just fine. client_write = hvac.Client(url='http://127.0.0.1:8200', token='MY_TOKEN') client_write.is_authenticated() When I run the same from the Django container, it fails with: requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8200): Max retries exceeded with url: /v1/auth/token/lookup-self (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2a21990610>: Failed to establish a new connection: [Errno 111] Connection refused')) Django docker container is running on localhost:8000 & the vault is localhost:8200. I also have a front end written in VueJS running on localhost:8080 that has no trouble communicating back and forth with the django rest API (django-rest-framework). Is there something in vault that I need to list where the queries can come from? Thank you, I am very new to Vault and am struggling through it a bit. BCBB -
Why is django's forloop.counter0 confused by an adjacent loop?
I have a template that looks like this: <table> <tbody> {% for row in rows %} <tr> {% for column in row %} <td>{{ column }}</td> {% endfor %} <td><input type=checkbox name="checkbox_{{ forloop.counter0 }}"></td> </tr> {% endfor %} </tbody> </table> The checkboxe names in the table that get generated start with checkbox_1 instead of checkbox_0. If I remove the inner for loop however: <table> <tbody> {% for row in rows %} <tr> <td>Column 1</td> <td>Column 2</td> <td><input type=checkbox name="checkbox_{{ forloop.counter0 }}"></td> </tr> {% endfor %} </tbody> </table> They start with checkbox_0 as they should. The inner loop appears to be messing up the counter for the outer loop. I even tried to use the with tag, but that didn't seem to help: <table> <tbody> {% for row in rows %} {% with forloop.counter0 as outer_counter %} <tr> {% for column in row %} <td>{{ column }}</td> {% endfor %} <td><input type=checkbox name="checkbox_{{ outer_counter }}"></td> </tr> {% endwith %} {% endfor %} </tbody> </table> Any idea what might be going wrong? -
Save and Update Record date wise in via Django Rest framework
I am new to django , I am using AIPView method of restframework to create and update leaderboard model. The requirement is to save Email, Name and Total Score along with a date field which automaticall updates the date each time the record is saved. Each time a users score his highest score , its pushed to database on server. A user can achieve higest score many times within a single day or within of a few days The issue is that my client wants to save highest score record date wise. I am able to update total Points everytime I receive from the client for the current dateand I am unable to keep the previous days hights score/TotlaPoints, Please advice a solution. This is my Models.py file class leaderboard(models.Model): name = models.CharField(_("playername"), max_length=255) email = models.CharField(_("email"), max_length=255, default='myemail@gmail.com') TotalPoints = models.IntegerField(_("TotalPoints")) updated_at = models.DateTimeField(auto_now=True)code here This is my Views.py file: I tried ofllowing code but it only saves the highest score to Total_points field and updates the date field (updated_at), I want to keep on updating Total Points until the dat changes, when the next day comes a new entry for the same record should be done but with … -
Image file can't covert to pdf when using python-pdfkit
Here is my code options = { "enable-local-file-access": True, ... } pdfkit.from_string(html_file, pdf_file, options=options, ...) since Im using Django template, here is my code to reference that <img src="{{ static_root }}{% static '../../target.svg' %}" alt=""> I use a local image file in html, It just shows a blank box in pdf output file I also tried using "base64" to resolve my issue base on this link pdfkit not converting image to pdf It doesn't really work to me. -
Image not Updating using DOM manipulation
I am trying to toggle between 2 images based on a condition. I am thinking to change the src of img tag. I am able to change the src but on the webpage the image is not getting updated. can someone point out where or what should be used or updated. Here is my JS code -> success: function(data){ if(data.status == 200){ if(data.message == "Liked"){ document.getElementById("like_image_state_change").src="{% static 'FrontEnd1/Static_Images/CovrPage_Like_R.png' %}"; } else if(data.message == 'Like Removed'){ document.getElementById("like_image_state_change").src="{% static 'FrontEnd1/Static_Images/CovrPage_Like_W.png' %}"; console.log(document.getElementById("like_image_state_change")); } } else{ console.log('wrong'); } } }); Here when I console the document.getElementById in 'like Removed' I could see the updated src for the Image but the Image is still the same on the webpage. PS -> The backend I am using is DJango. (if it matters) -
Django Python contact form saves file but doesn't send the email
I'm trying to set up a simple contact form with an optional file upload; I don't want the file to be attached to the email message, I simply want to save the file to /media. I'm using required=False in the form to not require a file. But still, some of my form validation or form processing logic is wrong; the code below works when I submit the contact form without a file and I get an email. But if I attach a file, the file is saved to media, but I don't get an email even though the contact form correctly renders thanks.html after form submission. No errors in the logs. Ubuntu 20.04; Django 4.0.3; Python 3.8.10; Apache 2.4 contact/contactform/forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'maxlength': '100'} )) email_address = forms.EmailField(required=True, widget=forms.EmailInput( attrs={'class': 'form-control', 'maxlength': '100'} )) document = forms.FileField(required=False) message = forms.CharField(required=True, widget=forms.Textarea( attrs={'class': 'form-control', 'maxlength': '1000', 'rows': 8} )) contact/contactform/views.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.shortcuts import render, get_object_or_404, redirect from django.core.files.storage import FileSystemStorage from contactform.forms import ContactForm from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST def thanks(request): return render(request, 'thanks.html', {}) def contact(request): if request.method … -
Save django CreateView in Python Shell
I'm trying to write a test for my CreateView view in django. As part fo the test, I want to create a new object through a CreateView class, though I'm unsure how to save the object through tests.py. models.py class MyClass(models.Model): name = models.CharField( max_length = 50, ) tests.py from myapp.views import MyCreateView m = myCreateView() m.name = 'John Doe' # save object here Neither m.save() nor m.submit() will work. Any suggestions? -
Create a custom superuser django
I'm trying to create a custom user model but when I create a superuser with "python manage.py createsuperuser" and try to login from the django admin, I get this message: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. username and password are correct. and this is my models: class MyUserManager(BaseUserManager): def create_user(self, username, password, **extra_fields): user = self.model(username=username) user.set_password(password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(username, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10,unique=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] publisher = models.BooleanField(default=False) admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = MyUserManager() def __str__(self): return self.username