Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update balance after withdrawal and deposit with python django app
I'm still new to django and i'm learning by trying to build a web bank account like app. I have created a users app and the bank app within my project. in my users app, i have models such as the user profile, user account details and user account. the user account model is designed to store the current account balance of the user. in the bank app, i have models such as deposit and withdrawals, these models have details of the deposit or withdrawal amount, date and time of withdrawal. Here is my user account model from django.db import models from django.contrib.auth.models import User class UserAccount(models.Model): class Meta: verbose_name = 'UserAccount' verbose_name_plural = 'UserAccounts' MAX_BALANCE = 10000000.00 MIN_BALANCE = 0.00 MAX_DEPOSIT = 2000000 MIN_DEPOSIT = 10000 MAX_WITHDRAW = 1000000 MIN_WITHDRAW = 10000 MAX_PORTFOLIO = 2000000 MIN_PORTFOLIO = 10000 user = models.OneToOneField(User, on_delete=models.CASCADE) created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) account_balance = models.PositiveIntegerField(verbose_name ='Current balance', default=0) def __str__(self): return f'{self.user.username} Account' then this is the deposit model i created in the bank app from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class MakeDeposit(models.Model): MAX_DEPOSIT = 2000000 MIN_DEPOSIT = 10000 DEPOSIT_STATUS_PENDING = … -
HTML select form with option to enter value does not store the entered value as object field in django
I have a Django form in which I have several drop-down menus that have an option to enter a custom value. In order to enter a custom value, I am using the following implementation to toggle a textbox whenever the custom value is selected from this implementation http://jsfiddle.net/6nq7w/4/ Whenever I select an option from the dropdown list and save the form, the model's object value (In this case it is EmployeeInformation.dept) retains the value selected, but it is not the case if I enter a custom value. In the below example, I use a chained dropdown implementation to load the Department based on the Department ID. For example - Let's say while filling the form I select the value Sales then the value of EmployeeInformation.dept = Sales, whereas when I select the option as Enter Manually and enter a new value say DeptXYZ the Django model object does not take this manually entered value as the data for the field Dept. models.py class EmployeeInformation(models.Model): name = models.Charfield(max_length=30,null=False, blank=False) dept_id = models.ForeignKey(DepartmentInformation, on_delete=models.SET_NULL, null=True) dept = models.ForeignKey(SubDeptInformation, on_delete=models.SET_NULL, null=True) salary = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10) form.html <!DOCTYPE html> <html> <script> function toggleField(hideObj,showObj){ hideObj.disabled=true; hideObj.style.display='none'; showObj.disabled=false; showObj.style.display='inline'; showObj.focus(); } </script> <body> <form … -
How to put an image from ImageField on an html email template in django
I have in views.py: def buy(request): if request.method=='POST': form=forms.Purchase(request.POST) if form.is_valid(): form.save() user = Person.objects.filter(first_name=form.cleaned_data.get('first_name')).filter(last_name=form.cleaned_data.get('last_name')).first() name=form.cleaned_data.get('first_name') + form.cleaned_data.get('last_name') subject, from_email, to = 'Subject test1234', 'tasselsas@gmail.com', form.cleaned_data.get('email') html_content = render_to_string('tickets/mail_template.html', {'first_name':user.first_name, 'imagelink':user.qr_image}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return redirect('thankyou') else: form=forms.Purchase() return render(request, 'tickets/buy.html', {'form': form}) Inside of the ImagField is contained jpg image file, and I want it to show on the html email being sent. mail_template.html: {% extends "event/base.html" %} {% block content %} <p>{{ first_name }}</p> <img src= {{ imagelink }}> {% endblock content%} The first_name works, but the image does not. -
Forbidden You don't have permission to access this resource. django apache ubuntu
i tried to deploy my django application this is the conf file Alias /static /home/username/main_folder/app name/static <Directory /home/username/main_folder/app name/static> Require all granted </Directory> Alias /media /home/username/main_folder/app name/media <Directory /home/username/main_folder/app name/media> Require all granted </Directory> <Directory /home/username/main_folder/app name/app name> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/username/main_folder/app name/app name/wsgi.py WSGIDaemonProcess django_app python- path=/home/username/main_folder/app name python- home=/home/username/main_folder/venv WSGIProcessGroup django_app sudo ufw allow http/tcp but when i enable port 8000 0.0.0.0:8000 it will work fine is there something i missed ? -
Django error: 'QuerySet' object has no attribute 'destinations'
Doing little Django ecommerce project for a hobby. Can't seem to add an item to the cart. Get this error 'QuerySet' object has no attribute 'destinations'. Tried to clean the database, however did not work. my views.py def add_to_cart(request, slug): cart = Cart.objects.all() try: destination = Destination.objects.get(slug=slug) except Destination.DoesNotExist: print('does not exist') except: pass if not destination in cart.destinations.all(): cart.destinations.add(destination) else: cart.destinations.remove(destination) return redirect(reverse('cart')) models.py class Cart(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) destinations = models.ManyToManyField(Destination, blank=True, null=True) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) urls.py path('cart/<slug>', cart_views.add_to_cart, name='add_to_cart'), index.html <a href="{% url 'add_to_cart' destination.slug %}">Add</a> cart.html {% for destination in cart.destinations.all %} {{ destination }} {{ destination.price }} {% endfor %} Get this error 'QuerySet' object has no attribute 'destinations'. Much appreciate Your help! -
Failed to load resource: status of 500 (Internal Server Error) Django
I made an Admin user who uploads destinations. Data save in DB and get in a smooth way except for images. and Shows this Error in Console "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" HTML {% for dest in dests %} <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{dest.img.url}}" alt=""> {% if dest.offer %} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="destinations.html">{{dest.name}}</a></div> <div class="destination_subtitle"><p>{{dest.description}}</p></div> <div class="destination_price">From ${{dest.price}}</div> </div> </div> {% endfor %} Views.py def index(request): dests = Destination.objects.all() return render (request, 'index.html',{'dests':dests}) In Chrome's Console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) -
How to configure Django media root in Apache
This is my first time deploying to a production env and I am having a tough time getting my media folder settings to point to the correct directory. I would like to note that my static files are working correctly. My projects folder structure looks like: /sc /sc /sc /media /memos /payroll /users /static db.sqlite3 manage.py requirements.txt My projects settings.py MEDIA settings: STATIC_URL = '/users/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My /etc/apache2/sites-available/sc.conf media and static settings: Alias /users/static /home/davida/sc/sc/static <Directory /home/davida/sc/sc/static> Require all granted </Directory> Alias /media /home/davida/sc/sc/media <Directory /home/davida/sc/sc/media> Require all granted </Directory> <Directory /home/davida/sc/sc/sc> <Files wsgi.py> Require all granted </Files> </Directory> When I run a process on my site, which usually works in development, it gives back this error: [Errno 2] No such file or directory: 'media/DavidAlford/Tips_By_Employee_Report.xls' This file is uploaded by the user previous to this process and exists in at that directory. Also, I have a script which should be deleting all the old files in this directory before user uploads new files but that is not working either so I assume this means that my Apache settings are wrong. -
How can I redirect to another Twilio task using Twilio and Django?
I'm creating a chatbot and I can't redirect to a task created at the Twilio Autopilot Console. What it does: user sends a message to the bot, the view gets called, does some stuff which I removed for clarity then redirects (or should) to an Autopilot task. @twilio_view def bot(request): account_sid = config('account_sid') auth_token = config('auth_token') client= Client(account_sid, auth_token) msgresponse = MessagingResponse() msgresponse.redirect(url="task://parametrizacao") return HttpResponse(status=200) If I redirect to another view, django-style, it works, but I want it to redirect to a Twilio Autopilot Task... -
Installing Geospatial libraries in Docker
django's official documentation lists 3 dependencies needed to start developing PostGIS application. They list a table depending on the database. I use docker for my local development and I am confused on which of those packages should be installed in the Django container and which in the PostgreSQL container. I am guessing some of them should be on both. Would appreciate your help on this. -
Redirect to download Django
I want to track how many times file has been downloaded. I see it this way: 1) Instead of <a href="{{ file.url }}" download>...</a>, I should redirect user for download view; <a href="download/{{ file.id }}/{{ file.name }}">...</a> file.id and file.name needed for proper work of function bellow. 2) In my download view I need to registrate download of specific file, let's say I have registrate_dl function that does its job. Also, I need to take that {{ file.url }} value like in first link from first paragraph. 3) Finally, I registered download for specific file and got {{ file.url }} as file_url variable. But, if, at the end of view function I place return redirect(file_url), it just redirects me to file, without starting download. So, how should i return this file_url, and trigger download? -
Computing the SHA256 hash of a FileResponse objects content
I have a file for which I have computed its SHA256Sum and have verified it is correct. hash1 = computeSHA256(filepath) I need to compute the hash again, but this time using the values inside response.streaming_content where response is a Django FileResponse object, which I have done as follows: response = FileResponse(request, open(filepath, 'rb'), content_type='application/json') content = b''.join(response.streaming_content) h = hashlib.sha256() h.update(str(content).encode('utf-8')) hash2 = h.hexdigest() This issue here is that hash1 != hash2. For example: hash1 = 7836496a8e17dac5aad5dea15409b06558d0feaf6c39198eae620afebb1fa097 hash2 = 70a3e07b20e722652740e93702b70322d042b9710b3087228e70551ad8301086 Can anyone see where I have gone wrong to cause the two hash values to not be equal? Note: the file is a Google Protobuf (.pbf) file, so is binary. -
How to put the username of the logged-in user in the databse each time a form is submitted
I have an application where a user can submit a form which goes into the database (POSTGRES). I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end). what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission. I hope I am clear, thanls guys. Here is my code models.py from django.db import models as db_models from django.contrib.auth.models import User from django.contrib.gis.db import models class Fertidb(models.Model): user = db_models.ManytoManyField(User, on_delete=models.CASCADE) area = models.IntegerField() plot = models.FileField(upload_to='KML_FILES', blank=True) def __str__(self): return f' Parcelles de {self.user.username}' forms.py from django import forms from django.contrib.auth.models import User from .models import Fertidb class FertidbForm(forms.ModelForm): class Meta: model = Fertidb labels = { "plot": "Importez votre fichier KML" } fields = ['culture', 'area', 'plot'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import FertidbForm from django.contrib.auth.models … -
Request object has no user during process_request in django middleware
I have a custom middleware that I'm writing which I have added to my list of middlewares in settings. The middleware needs to access some attributes on the user attached to the request, and this works fine for requests made directly to the backend server. However, for CORS requests that come from the frontend, I'm seeing that the user is an AnonymousUser during process_request, and they only show up as authenticated in process_response. I have 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware' above my custom middleware in settings.py, so I would have expected this to work. Any advice on different things I should try to be able to access the authenticated user in my custom middleware's process_request method with CORS requests? -
Coordinates intersecting with bounding box after forcing right hand rule
I am trying to query for locations within a bounding box. The bounding box of the country Russia renders east-to-west, covering basically all of Canada and none of Russia (which is obviously incorrect) and returns cities in Canada, Poland, and Slovakia. I used ForceRHR (Django 1.11) and ForcePolygonCW (Django 2.2) to force the right-hand-rule, and it appears to order the bounding box coordinates properly, but I get the same query results for the regular bounding box and the RHR bounding box. Here are the relevant fields in the Location model... from django.contrib.gis.db import models as gis_models point = gis_models.PointField(blank=True, null=True, geography=True) bounding_box = gis_models.PolygonField(blank=True, null=True) And here's what I've tried... from locations.models import Location from django.contrib.gis.db.models.functions import ForceRHR, ForcePolygonCW russia = Location.objects.annotate(rhr=ForcePolygonCW('bounding_box')).get(pk=1646) print(russia.bounding_box) in_russia = Location.objects.filter(point__intersects=russia.bounding_box) print(in_russia) print(russia.rhr) in_russia2 = Location.objects.filter(point__intersects=russia.rhr) print(in_russia2) Here are the results of the code above: SRID=4326;POLYGON ((19.638861 41.185902, 19.638861 81.856903, -168.997849 81.856903, -168.997849 41.185902, 19.638861 41.185902)) <QuerySet [<Topic: 00-001 Warsaw, Poland>, <Topic: 048 01 Rožňava, Slovakia>, <Topic: 053 51 Richnava, Slovakia>, <Topic: 50.2112, -170.2624>, <Topic: 50.9566, -170.7638>, <Topic: 51.5734, -170.2439>, <Topic: 51.7759, -169.4604>, <Topic: 51.8281, -170.4743>, <Topic: 51.9097, -170.0422>, <Topic: 51.9108, -169.5701>, <Topic: 51.9771, -169.6288>, <Topic: 51.9782, -169.3368>, <Topic: 52.0036, -170.8657>, <Topic: 52.0231, -170.4362>, <Topic: … -
Differences between get_by_id() vs objects.get() vs objects.filter()
I'm just looking to see what the differences are between: obj = ClassModel.get_by_id(object_id) obj = ClassModel.objects.get(object_id) obj = ClassModel.objects.filter(pk=object_id) Obviously the first one is more concise, but I didn't find a good resource about it, and I'm not sure if I should use it throughout my code. In addition, what are the consequences of using the first option over the second option? Is it safe to use it or is it going to add code debt to my code? I'm in Django 1.11, but looking to migrate to Django 2 within the next months. -
date_facet in Django Haystack not faceting by date
I'm using Haystack 2.8.1 with Django 2.1 and Solr 6.6.6. I have no problems using facets, however date faceting is not working. My index: class ConflitoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) data_inicio = indexes.DateField(model_attr="data_inicio", faceted=True, null=True) def get_model(self): return Conflito def index_queryset(self, using=None): return self.get_model().objects.all() The following script on shell: from haystack.query import SearchQuerySet import datetime sqs = SearchQuerySet().date_facet("data_inicio", start_date=datetime.date(1980, 1, 1), end_date=datetime.date(2019, 1, 1), gap_by="year") results in: In [1]: sqs.facet_counts() Out[1]: {'fields': {}, 'dates': {}, 'queries': {}} However, the following script results in: In [1]: from haystack.query import SearchQuerySet In [2]: import datetime In [3]: sqs = SearchQuerySet().facet('data_inicio') In [4]: sqs.facet_counts() Out[4]: {'fields': {'data_inicio': [('1500-01-01T00:00:00Z', 212), ('1986-12-29T00:00:00Z', 148), ('2010-01-01T00:00:00Z', 141), ('1979-12-29T00:00:00Z', 130), ('2018-01-01T00:00:00Z', 104), ('1984-12-29T00:00:00Z', 100), ... ('2013-10-16T00:00:00Z', 17), ('1982-12-02T00:00:00Z', 16), ('1988-02-28T00:00:00Z', 16), ('1996-05-29T00:00:00Z', 16), ('1998-03-29T00:00:00Z', 16), ('2000-01-31T00:00:00Z', 16)]}, 'dates': {}, 'queries': {}} Thus, faceting is not working for dates. What can be wrong in my code? Unfortunately there are very few examples for date faceting in Haystack documentation. best, alan -
REST API serializer doesn't return Primary Key (PK)
I am setting up React-native app that talks to Django REST API using Axios. My problem is that I can't get primary key from the database via API in to the React-native app. I want to build a list that users can tap on and do something with it in next step, so I would like to have the PK of the chosen object. I have following Viewset: class PermitViewSet(viewsets.ModelViewSet): serializer_class = PermissionSerializer queryset = Permit.objects.all() def get_queryset(self): return Permit.objects.filter(user=self.request.user).values('permit_id','work_place_name','valid_to_date')[:2] and when I print the result in the console, I see the primary key: <QuerySet [{'permit_id': 100, 'work_place_name': 'mjest', 'valid_to_date': datetime.datetime(2019, 9, 29, 23, 0, tzinfo=<UTC>) When I try to get this response using Postman or in my React-native app using axios, there is no PK: permit_id -
Filter by Django EncryptedCharField
I'm using the cryptographic_fields.fields library to encrypt some of my fields, more specifically the customer's routing number. Here is how my model.py looks like: class Account(models.Model): account_number = EncryptedCharField(max_length=20, null=True, blank=True) I'm looking to see if it's possible to filter by this field. Account.objects.filter(account_number='123') Of course, this is going to return an empty queryset because there is definitely not an account number with the values 123 because it has already been encrypted (encoded). Is there a way of doing this. I was looking at the source code, and tried encoding the string and searching with the new encode value. from cryptographic_fields.fields import get_crypter CRYPTER = get_crypter() account_number = CRYPTER.encrypt('123'.encode('utf-8')) Account.objects.filter(account_number=account_number) But this doesn't work as it seems the CRYPTER products a new different encrypted value every time I use it. My ultimate goal is to be able to check if an account_number has been used in other accounts already. -
Django , how to use annonation for minus two model
How to find the total sum of the two Field using minus. class Car(models.Model): name = models.CharField(max_length=255) class Supplier(models.Model): name = models.CharField(max_length=255) class Buyer(models.Model): name = models.CharField(max_length=255) class Car(models.Model): name = models.CharField(max_length=255) class Buy(models.Model): car= models.ForeignKey(Car, on_delete=models.CASCADE) Supplier= models.ForeignKey(Supplier, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Sell(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def order(request): cars = Car.objects.filter() buy = Car.objects.filter().annotate(totals=(Sum('buy__quantity'))) sell = Car.objects.filter().annotate(total=(Sum('sell__quantity'))) total = Car.objects.annotate(tota=Sum(F('buy__quantity')-F('sell__quantity'))) #does work when i add the same car to another buyer when I multiply work fine. total = Car.objects.annotate(tota=Sum(F('buy__quantity')*F('sell__quantity'))) Total sum of the two Field using minus. when I add a to (Model Buy: car = quantity 4) and in the - (Model Sell : car = quantity 2) work fine (value = 2), but when I go to add the same car for another Buyer on the (model Sell: car = quantity 2) give the wrong (value = 4) not 0 -
Django: Could not parse the remainder: '{{' from '{{
when i execute my HTML Code, it gives me the following error: Could not parse the remainder: '{{' from '{{ I tried to nest the conditions too, but I am an absolute beginner in HTML so I wanted to get this version at least correct, but it is not working... {% block content %} <p align="justify"> So far you donated {{ donated_trees }} Tree(s). </p> {% if treatmentgroup == 'two' or treatmentgroup == 'three' %} Your current position is {{ player.end_position }} of {{ anzahlspieler }} for the most donated trees. {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} == 0 %} <P> No other player has the same.</P> {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} == 1 %} <P> One other player has the same.</P> {% endif %} {% if treatmentgroup == 'two' or treatmentgroup == 'three' and {{ player.rival }} > 1 %} <P> {{ player.rival }} other players have the same.</P> {% endif %} The error occurs from line 8 on -
Anonymous user encountered while accessing rest-api with simplejwt
I am able to obtain access and refresh token using SimpleJWT. I have a custom decorator which tries to identify type of user from user profile. Code fails here because it can not find authenticated user. I have repeatedly tried to get user via debug mode in VS Code but not successful. Here is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', # Add this line 'rest_auth', # Add this line 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # we will not be using this but not keeping this entry results in error while deleting user. A known issue https://github.com/Tivix/django-rest-auth/issues/412 'crispy_forms', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTH_USER_MODEL = 'users.User' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } REST_USE_JWT = True ''' #https://www.techiediaries.com/django-rest-framework-jwt-tutorial/ JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_RESPONSE_PAYLOAD_HANDLER': 'custom_jwt.jwt_response_payload_handler', # 'JWT_PAYLOAD_HANDLER': 'custom_jwt.jwt_payload_handler', # 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300) } ''' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 Here is … -
Instance of 'ImageField' has no 'save' member - working with PIL and Django
I am attempting to put a qrcode into the image field of my model. I saw this answer: Save a generated PIL image into an ImageField in django and tried to recreate it, but I encountered the following error: Instance of 'ImageField' has no 'save' member pylint(no-member) Any ideas as to why? class Customer(models.Model): user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() number_of_guests = models.PositiveIntegerField() url_link = models.CharField(max_length=200) qr_image = models.ImageField(upload_to='qrcodes', default='default.jpg', blank=True, null=True) def __str__(self): return (self.first_name + " " + self.last_name + " " + str(self.user_id)) def save(self, *args, **kwargs): self.url_link = "http://127.0.0.1:8000/" + str(self.user_id) qrcode_img = qrcode.make('some data') canvas = Image.new('RGB', (500, 500), 'black') canvas.paste(qrcode_img) blob=BytesIO() canvas.save(blob, 'JPEG') self.qr_image.save('qrcode-filename.jpg', File(blob), save=False) super().save(*args, **kwargs) -
Issue setting up celery/redis in docker/django
Here is my current setup: requirements.txt celery[redis] Dockerfile RUN curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash ENV PATH "/home/appuser/.pyenv/bin:$PATH" RUN echo "export PATH=/home/appuser/.pyenv/bin:$PATH" >> /home/appuser/.bashrc RUN echo 'eval "$(pyenv init -)"' >> /home/appuser/.bashrc RUN echo 'eval "$(pyenv virtualenv-init -)"' >> /home/appuser/.bashrc RUN pyenv install 3.7.0 RUN pyenv global 3.7.0 ENV PATH "/home/appuser/.pyenv/versions/3.7.0/bin:$PATH" WORKDIR /code COPY ./back-python/project/requirements.txt /code/ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt project/settings CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' projects/init.py from .celery import app as celery_app __all__ = ['celery_app'] projects/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) docker-compose.yml version: '3' services: ui: build: ./front-vue/. volumes: - ./front-vue/:/code ports: - "8888:8888" links: - django command: "npm run dev" redis: restart: always image: "redis:alpine" sysctls: - net.core.somaxconn=511 django: build: . volumes: - ./back-python/project/:/code - ./front-vue/dist/pwa/:/code/public expose: - "8000" command: "python manage.py runserver [::]:8000" depends_on: - redis celery: build: . command: celery -A project worker -l info volumes: - ./back-python/project/:/code depends_on: - redis When I run docker-compose up, I keep getting this error celery_1 | Traceback (most recent call last): celery_1 | File "/home/appuser/.pyenv/versions/3.7.0/bin/celery", line 11, in <module> celery_1 … -
request.session isn't saved or is somehow modified
It seems that my request.session isn't saved or is somehow modified in other ways, despite using request.session.modified = True after changing the value. Here is the debug output: This should run first. This should run second. I have set main category to 2 (Shoes) Main category is 1 (Books) The code below should display a different ModelForm based on selected category, however when I select, for instance, Books, ShoesModelForm is displayed and vice-versa. This currently works as follows: whenever a value in a combobox is changed, two AJAX requests are fired. First one calls a view (load_categories) that renders another if a category has children, otherwise returns an HttpResponse which stops attaching the listener. Second one calls a view (load_modelform) that renders a specific ModelForm if selected category is root node (main category). mappings = { '1': BookProductForm, '2': ShoesProductForm } def load_categories(request): print("This should run first.") category_id = request.GET.get('category') request.session['category'] = category_id request.session.modified = True if Category.objects.get(id=category_id).is_root_node(): request.session['main_category'] = category_id request.session.modified = True print(f"I have set main category to {request.session['main_category']} ({Category.objects.get(id=category_id).name})") subcategories = Category.objects.get(id=category_id).get_children() if subcategories: return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) return HttpResponse('leaf_node') def load_modelform(request): print("This should run second.") main_category = request.session['main_category'] print(f"Main category is {main_category} ({Category.objects.get(id=main_category).name})") form = … -
Configure Python to Complex Django Project
I need to configure pytest in my django application. But the structure of the directories is different of what I'm used to. . ├── apps │ ├── __pycache__ │ ├── admcore │ ├── ... │ ├── cauth │ ├── webservice │ └── webshell ├── doc │ └── ... ├── lib │ └── ... ├── ... └── project ├── __init__.py ├── globalsettings.py ├── local │ ├── __init__.py │ ├── app.uwsgi │ ├── manage.py │ ├── settings.py │ └── wsgi.py ├── mailconf.py └── urls.py I created pytest.ini [pytest] DJANGO_SETTINGS_MODULE=sgp.local.test_settings addopts = --nomigrations --cov=. --cov-report=html and test_settings.py files #!/usr/bin/env python import os import sys from project import globalsettings SECRET_KEY = "12341234AFDQFDQSDFAZR123D" ROOT_PATH = '/usr/local/sgp' BASEURL_ROOT = '' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } And I put the two files in project directory. . ├── apps │ ├── __pycache__ │ ├── admcore │ ├── ... │ ├── cauth │ ├── webservice │ └── webshell ├── doc │ └── ... ├── lib │ └── ... ├── ... └── project ├── __init__.py ├── globalsettings.py ├── local │ ├── __init__.py │ ├── app.uwsgi │ ├── manage.py │ ├── pytest.ini │ ├── settings.py │ ├── test_settings.py │ └── wsgi.py ├── mailconf.py └── urls.py …