Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compress an image to less than 1MB (one) and than allow users to download the image using Python in Django project
I'm working on a Django project. All I need is to take a image as an input from user than I have to compress it in less than 1MB or specific size without losing too much quality. Then allow users to download the image -
Run Tasks on Celery with Django Error: raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED')
I just run Redis on my VPS with no problem: -------------- celery@s1550.sureserver.com v5.2.3 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.19-sure2-x86_64-with-debian-10.11 2022-03-08 17:22:46 *** --- * --- ** ---------- [config] ** ---------- .> app: web_edtl:0x7c2374cc52e8 ** ---------- .> transport: redis+socket:///home/$USER/private/redis/redis.sock ** ---------- .> results: socket:///home/hamutuk/private/redis/redis.sock *** --- * --- .> concurrency: 2 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . imagekit.cachefiles.backends._generate_file [2022-03-08 17:22:46,248: INFO/MainProcess] Connected to redis+socket:///home/$USER/private/redis/redis.sock [2022-03-08 17:22:46,252: INFO/MainProcess] mingle: searching for neighbors [2022-03-08 17:22:47,267: INFO/MainProcess] mingle: all alone [2022-03-08 17:22:47,284: INFO/MainProcess] pidbox: Connected to redis+socket:///home/$USER/private/redis/redis.sock. [2022-03-08 17:22:47,292: WARNING/MainProcess] /home/$USER/private/project/project_env/lib/python3.7/site-packages/celery/fixups/django.py:204: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! leak, never use this setting in production environments!''') [2022-03-08 17:22:47,293: INFO/MainProcess] celery@s1550.sureserver.com ready. But web i run some task to Send Email i got a Error : raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') This is log off error: [2022-03-08 17:04:44,527: ERROR/MainProcess] Task appname.tasks.task_name[892f4462-2745-4bb7-9866-985cd3407c86] raised unexpected: ConnectionRefusedError(111, 'ECONNREFUSED') Any Ideia how to Fix it? Thank You -
Running a command from a command line tool from another app in django
I am building a Webapp using Django and want to generate some comments from a command-line tool present in the same directory as the web app. What are the different methods to call this tool from the web app and run commands in the terminal and extract output from it and display it in a web app? -
How I can show selectbox from models in my form?
How I can show selectbox from models in my form. Output for below code does not show options for selectbox. #models.py class Reg(models.Model): options = ( ('one', 'option1'), ('two', 'option2'), ) types = models.CharField(max_length=30, choices=options,null=True) company = models.CharField(max_length=50,null=True) #form.py from django import forms from .models import Reg class Regform(forms.ModelForm): class Meta: model = Reg fields = ['types','company'] types = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'} ), label="Type", ) -
Is there a way to require a signature or authorization when POSTing JSON data to a Django database with Python?
Say I have a Django database in an API storing a bunch of JSON data. I have a scraper webscraping a site and posting the info at specific endpoints. It runs swimmingly but, if I were to share my API, I worry that there may be a malicious actor or some troll that might want to POST fraudulent data to the database. So the question is, is there a key or or some functionality that authorizes the poster to upload to the database? How would I implement this? Thank you in advance! -
Error "string indices must be integers" when querying
I am just learning how to write programs and applications in python. I'm writing a serializer for a Recipe app. But I am getting an error. Please help me understand and write correctly. Here is the serializer: class AddRecipeIngredientsSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) amount = serializers.IntegerField() class Meta: model = RecipeIngredient fields = ('id', 'amount') class AddRecipeSerializer(serializers.ModelSerializer): image = Base64ImageField() author = CustomUserSerializer(read_only=True) ingredients = AddRecipeIngredientsSerializer(many=True) tags = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), many=True ) cooking_time = serializers.IntegerField() class Meta: model = Recipe fields = ('id', 'tags', 'author', 'ingredients', 'name', 'image', 'text', 'cooking_time') def validate_ingredients(self, data): ingredients = data[0] if not ingredients['id']: raise ValidationError('Не выбрано ни одного ингредиента!') ingredients_ids = [ingredient['id'] for ingredient in ingredients] if len(ingredients) != len(set(ingredients_ids)): raise serializers.ValidationError('Вы не можете добавить один ' 'ингредиент дважды') for ingredient in ingredients['amount']: print(ingredients) print(ingredient) if int(ingredient) <= 0: raise ValidationError('Количество должно быть положительным!') pk = int(ingredient['id']) if pk < 0: raise ValidationError('id элемента не может быть ' 'отрицательным') return data def validate_tags(self, data): if not data: raise ValidationError('Необходимо отметить хотя бы один тег') if len(data) != len(set(data)): raise ValidationError('Один тег указан дважды') return data def validate_cooking_time(self, data): if data <= 0: raise ValidationError('Время готовки должно быть положительным' 'числом, не менее 1 минуты!') return data … -
Dynamic carousel in django using bootstrap carousel
I am working on project where I need dynamic carousel in my html.problem is I making carousel which have maximum of 5 slide but what I am getting only 4 slides and i cannot even nav buuton to last slide using buttons and also prev button is not working when i at the second last slide. I used bootstrap carousel . Views.py class HomeView(View): def get(self,request): return render(request,'MainSite/home.html',{'carousel_item' : carousel_item}) home.html <div style = "padding : 10px 10px 10px 10px;margin-top : 20px;"> <div id="carouselExampleCaptions" class="carousel slide mx-3" data-bs-ride="carousel"> <div class="carousel-indicators"> {%for item in carousel_item %} {% if forloop.first %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> {% else %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> {% endif %} {% endfor %} </div> <div class="carousel-inner"> {%for item in carousel_item %} {% if forloop.first %} <div class="carousel-item active"> <img src="{{item.title_image}}" class="d-block w-100" height = "350px" > <div class="carousel-caption d-none d-md-block"> <h5>{{item.title}}</h5> <p>{{item.subtitle}}</p> </div> </div> {% else %} <div class="carousel-item"> <img src="{{item.title_image}}" class="d-block w-100" height = "350px" > <div class="carousel-caption d-none d-md-block"> <h5>{{item.title}}</h5> <p>{{item.subtitle}}.</p> </div> </div> {% endif %} {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> … -
how to deal with model property in django view
I am trying to do an ecommerce app ,where in i have to add coupon code in the checkout page. I had a model property to check for the coupon code validity.Here is my code model: class CoupenCode(models.Model): code=models.CharField(max_length=100) startdate=models.DateField() enddate=models.DateField() discount=models.IntegerField() disc_type=models.CharField(max_length=20,choices=( ('Amount','Amount'), ('Percentage','Percentage'))) usercount=models.PositiveIntegerField() min_amount=models.PositiveIntegerField() @property def is_expired(self): if datetime.now().date() > self.enddate or datetime.now().date() < self.startdate : return False return True class Meta: db_table = 'CoupenCode' ordering = ['-id'] def __str__(self): return self.code views: def fncoupon(request): if request.method=="POST": coupon=request.POST.get('promo') couponcode=CoupenCode.objects.filter(code=coupon) validity=couponcode.is_expired() if validity == True : if couponcode.disc_type == "Amount": discount=couponcode.discount + 'Rs' else: discount=couponcode.discount + '%' print(discount) return JsonResponse({'discount':discount}) else: message="This coupon code is not valid" print(message) return JsonResponse({'message':message}) the problem is i cant check for the coupon code validity using this property in views.it gives me an error 'QuerySet' object has no attribute 'is_expired' Can anyone please suggest me how i could solve this.. -
Django Rest Framework: How to generate sequence numbers
In my projects, there is a unique random number that is auto-generated through a function, but the scenario is I want a sequential number for each entry. def generate_unique_key(length): return ''.join(random.choice(string.digits) for _ in range(length)) def get_unique_key(): while User.objects.filter(learner_number=unique_id).exists(): unique_id = ("NO" + generate_unique_key(length=3)).upper() return unique_id how to change the above functions to generate sequential numbers for each entry? Like userA: NO001 userB: NO002 -
I am not able to make migrations to the following file?
My models.py code is this ` from django.db import models class Flight(models.Model): origin = models.CharField(max_length=64), destination = models.CharField(max_length=64), duration = models.IntegerField(), -
Cannot submit Django Wizard form when form is passed with arguments
I'm creating an app containing 3 multiple choice questions. The second multiple choice options are dependent on the response to the first question. To accomplish this, I added a "choices" argument to the second form and called that argument in the wizard's get_form function. While everything appears to work normally, the problem occurs when trying to submit the form on the last step. The done() function is never called and neither is the clean() function in forms.py. The page just gets refreshed without any errors appearing and the existing selected options get wiped. From testing, I've concluded that removing the custom init from forms.py and the get_form from views.py fixes the issue--but obviously defeats the purpose of this. I've been trying for a very long time to solve this issue but just can't seem to, any help is greatly apperciated! views.py class FormWizardView(SessionWizardView): form_list = [FormReflectionOne, FormReflectionTwo] template_name = 'reflection/form.html' def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] # Save form_data to Reflection Model return redirect('dashboard') def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current if step == '1': firststep_data = self.get_cleaned_data_for_step('0') choices_list = AdjectiveChoice.objects.filter(feeling=firststep_data['feeling']) choices = [(x.order, x.adjective) for x in choices_list] form … -
Recover data deleted by diskpart
After accidentally deleting all data on my disk using "clean" on diskpart, my HDD is now empty. I've searched and used some recovery data apps, one of them is EaseUS. After scanning hours, it shows up exactly all data I lost but requiring fee to recover. I want to know that how all the data is still remained and found by the app while the disk show in my computer is empty and is there any reliable and safe ways to recover all data that do not require money? p/s: Sorry for bad english, I hope you guys understand and help me with this problem. -
How To Create Live Location Tracker in Django? [closed]
I have Used folium To create map but two pointer mark draw that was straight line and so i am getting straight line but i am not able to get the road location. SO please help me in fixing that. -
Running into a booting worker issue with Django application when deploying to heroku
I'm deploying a website using Heroku, Django and gunicorn and can't seem to get it to deploy. 2022-03-08T04:04:56.739100+00:00 heroku[web.1]: State changed from crashed to starting 2022-03-08T04:05:02.664299+00:00 heroku[web.1]: Starting process with command `gunicorn commerce.wsgi` 2022-03-08T04:05:03.931009+00:00 heroku[web.1]: State changed from starting to up 2022-03-08T04:05:03.885712+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-08T04:05:03.886103+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Listening at: http://0.0.0.0:6623 (4) 2022-03-08T04:05:03.886136+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [4] [INFO] Using worker: sync 2022-03-08T04:05:03.889017+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-08T04:05:03.932911+00:00 app[web.1]: [2022-03-08 04:05:03 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-08T04:05:04.307248+00:00 app[web.1]: [2022-03-08 04:05:04 +0000] [10] [ERROR] Exception in worker process 2022-03-08T04:05:04.307278+00:00 app[web.1]: Traceback (most recent call last): 2022-03-08T04:05:04.307279+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute 2022-03-08T04:05:04.307280+00:00 app[web.1]: return self.cursor.execute(sql, params) 2022-03-08T04:05:04.307280+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "auctions_category" does not exist 2022-03-08T04:05:04.307280+00:00 app[web.1]: LINE 1: ...category"."name", "auctions_category"."name" FROM "auctions_... -
I have django application and nginx
I have django application and nginx, from browser, it access to the file /static. such as http://example.com/static/file.png However my application has files under /staticroot. http://example.com/staticroot/file.png it shows the image. So, I set on nginx. location /static { alias /staticroot; } However it doesn't appear My environment is Debug mode. My settings py is like this, STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(config("PROJ_PATH"), 'staticroot') How can I fix this? -
NotSupportedError : Calling QuerySet.exclude() after union() is not supported
I am getting the above error when I was trying to exclude some datasets from the result.. votes = VoteResponse.objects.filter(project=self) others = OtherResponse.objects.filter(project=self) vote_responses = votes.filter(date__year=self.date.year, date__quarter=self.date_quarter) return vote_responses.union(others) and I am trying to exclude the comments with null... projectSnapshot.comments = projectSnapshotResponses.exclude(comments='').order_by('-date')[:10].values_list('comments', flat=True) Could anyone please help me with this... Thanks -
IsAuthenticated Permission Error Cannot Input Token from Login
how to authenticate using tokens in django DRF? I'm trying to create a token authentication system using rest_framework.permissions.IsAuthenticated in views, but I can't input tokens, token status has not been entered, I create views like this, I read it here (https://www.django-rest-framework.org/api-guide/permissions/), and I adjusted it like the documentation but it still doesn't work, I tried using postman to check the response but it's still the same, can anyone help? -
Need to get the Foreign key value instead of ID in the database table using Django
model class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(Default_User,related_name='users',default=None) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def __str__(self): return self.project_name model class Job(models.Model): job_name=models.CharField(max_length=50) user= models.ForeignKey(Default_User,on_delete=CASCADE) project = ChainedForeignKey(Project,chained_field="user", chained_model_field="user",related_name='projects',show_all=False, auto_choose=True, sort=True) date = models.DateField(max_length=10,default=None) class Meta: db_table ='Job' def __str__(self): return '{}'.format(self.job_name) serializers class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project fields= '__all__' class Job_Serializers(serializers.ModelSerializer): job = serializers.StringRelatedField() class Meta: model= Job fields= ('id','job_name','user','project','date','job',) I need to get the foreign key value displayed in the database table of Job model but as per the above code it is displaying the Foreign key ID. For example I linked the project model in the Job model and in the db table it is showing the Project_id as(1,2,3) but i need to return the values of that id as(app, learning etc). Please help me to get the values of the foreign key value instead of ID in the database table. -
Can't connect to Postgres from Django using a connection service file (on Windows)
I have successfully set up Django and Postgres, and I can get them to work together when I put all of the Postgres parameters in the Django settings.py file. However, as shown in the Django documentation, I want to use a Postgres connection service file instead. I've created a service file (C:\Program Files\PostgreSQL\14\etc\pg_service.conf) that looks like this: [test_svc_1] host=localhost user=django_admin dbname=MyDbName port=5432 Launching Postgres from the command line with this file seems to work fine, as it prompts me for the password: > psql service=test_svc_1 Password for user django_admin: However, when I try to make migrations with Django, I get the following error: Traceback (most recent call last): File "C:\...\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\...\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\...\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\...\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\...\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\...\psycopg2\__init__.py",line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: definition of service "test_svc_1" not found There were other exceptions related to this one, such as: django.db.utils.OperationalError: definition of service "test_svc_1" not found but they all pointed back to not finding the service "test_svc_1". Here is an excerpt … -
ModuleNotFoundError virtual environment pythonanywhere in scheduled task
I am trying to schedule a task, but when running the script I get: ModuleNotFoundError: No module named 'clients' Even this is an installed app within my django project. I already added a hashbang/shebang as: #!/usr/bin/venv python3.9 #!/usr/bin/python3.9 Either option gets me the same error message. I think my code for the schedule task is good, but here it is anyways: cd /home/myusername/myproject/maintenance && workon venv && python3.9 mantenimientosemanal.py Any help will be really appreciated. Thanks. -
Writing a manuall (command line) triggered script to bulk change some DB values in Django?
I know that the best practice is to generally use these https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations, but I have been told that automatic migrations are risky and the powers that be want me to write a manual script that can be triggered manually on production instead. What would be the best way to go about doing this? Where would be the best place for it to live in the Django repo? How do I import everything I need? Anyone have an example? -
Django: calling a function and let it run in different thread with out waiting and affecting the main thread
I'm trying to work out how to run a process in a background thread in Django. Here is a api view which gets called by user and i need that (Crawler.crawl(request.user)) function to run independently and complete the work. User hitting this api view will not have to wait or the request time out will also not be an issue. class CrawlApiView(APIView): permission_classes = [IsAdminUser, ] def get(self, request, format=None): Crawler.crawl(request.user) response = { "Crawl has Started ", } return Response(response, status=status.HTTP_201_CREATED) -
How to get past 12 months total applicants number in months wise in django
I want to get last 12 months applicants data in months wise view. If this is March then i need to get data of [3,2,1,12,...,4] in this scenario. Here is my model: class Applicant(models.Model): full_name = models.CharField(max_length=200, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) ..... While i try query: Applicant.objects.values('created_at__month')annotate(total = Count('created_at__month')) it return values like [{'created_at__month': 2, 'total': 3}, {'created_at__month': 3, 'total': 13}]. If I have 2022's month March total applicant 22 and 2021's month March total applicant 20, this query return value 42 in created_at__month: 3, but I need only past 12 months data from this month. How can I write this query efficiently? -
How do I join together two Django querysets that are themselves results of joins (four tables involved)?
I have four related models in my Django app, and while I've got the basic and moderately advanced query syntax down I'm struggling with how to get this particular advanced query to work. My app is a scheduling app for a mountain biking team. For a given event (table 1), I want to combine together team member's (table 2) RSVPs (table 3) along with their relative rankings (table 4) for that event (back to table 1), which is information we use to group attending riders by their abilities. Since riders' skills change throughout the season and we want to track that, their rank is not a single number that we can just store as a single attribute on the TeamMember model (though that would definitely simplify this particular query). Here are the models (minus some irrelevant details for clarity): class TeamMember(AbstractUser): class Category(models.TextChoices): STUDENT = 'S', 'Student Athlete' PARENT = 'P', 'Parent' RIDE_LEADER = 'R', 'Ride Leader' COACH = 'C', 'Coach' category = models.CharField('Category', choices=Category.choices, max_length=1) # Also has first_name, last_name, etc from AbstractUser, # along with some other fields not relevant for this question class Event(models.Model): class EventType(models.TextChoices): PRACTICE = 'P', 'Practice' RACE = 'R', 'Race' type = models.CharField('Event … -
How do I show a form and 2 inputs to upload multiple images in the template and in the view?
I want to make an input that uploads multiple images. I have been reviewing some tutorials and my experience makes me not understand many things. I placed a view but in the template, where the input should appear, this appears: <QuerySet []> Obviously that should not be there, the input should appear that uploads the images when clicked. Can you see my code? can you give me a hint? html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="col-md-4"> <div class="mb-3"> <label class="form-label">Insurance company</label> {{ form.compañia_seguros }} <div class="invalid-feedback"> Please provide a website. </div> </div> </div> </div> <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> </div> <div class="tab-pane" id="pictures" role="tabpanel"> <div> {{ images }} <label for="file-input" class="btn btn-outline-success">Upload images</label> <p id="num-of-files">No files chosen</p> <div id="images"></div> </div> </div> <div class="tab-pane" id="warranty" role="tabpanel"> <div> {{ garantias }} <label for="file-inputz" class="btn btn-outline-success">Upload images</label> <p id="num-of-filez">No files chosen</p> <div id="imagez"></div> </div> <br> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </div> </form> views.py def create_carros(request): if request.method == "POST": form = CarroForm(request.POST) images = request.FILES.getlist('fotosCarro') garantias = request.FILES.getlist('garantia') for image in images: Carro.objects.create(fotosCarro=image) for garantia in garantias: Carro.objects.create(garantias=garantia) form = CarroForm(request.POST) images = FotosCarro.objects.all() garantias = Garantia.objects.all() return render(request, 'carros/carros-form-add.html', {'images': images,'garantias': …