Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make an Image qualifier project in django
first of all I must say that I am new to django and I am practicing. I explain, I am creating a project to rate images by showing the user several pairs of images and the user must select the one they like the most. And I'm stuck on how I can do to show the records of the images in pairs according to whether there was already a rating. It shows you a couple of images, you select the one you like the most and they must change the images for two others, that's the idea. Here is my models, the image model contain the image field atribute and the likes atribute who stores the likes of users. The UserLike model contain just the like of one user who will be add in the likes atribute (possibly i defines the class models incorrectly, 'couse i dont find the foreign key 'user_like' in users table) from django.db import models from django.core.validators import FileExtensionValidator from django.contrib.auth.models import User # Create your models here. class UserLike(models.Model): user_like = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Images(models.Model): image = models.ImageField(validators=[FileExtensionValidator]) likes = models.ManyToManyField(UserLike, blank=True) def __str__(self): return f'Image: {self.image}' Here is my views, i already made … -
Django display images on custom domain directly without showing Digital Ocean Endpoint on webaddres
I have an django app that hosts images on digitalocean spaces. The images are correctly uploaded to my digital ocean spaces. But when I click on the image it is shown with the digital ocean web address. With CDN and custom domain, I thought the web address for the image will be my custom domain (e.g. media.mydoamin.com) but it is directed to digital ocean's endpoint still. sfo3.digtialoceanspaces.com. I already included a custom domain url in the settings and added a CNAME record to my domain registry media.mydomain.com to an alias as domainname.sfo3.cdn.digitaloceanspaces.com I can see the cname record is already updated online. what am I missing? -
Read the image as Array from Django Model
The django model is a follows class Post(models.Model): title = models.CharField(max_length=100) file = models.FileField(null=True,blank=True,upload_to='Files') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I want to read the file. Let's say its an image. I want to read this image in an array format. I tried this but it doesnt work. img = Post.objects.all()[0].file print(img) OR print(np.array(img)) Output is : car-1.jpg Expected output : 2d Array -
Is there any solution for this Django register post method.?
!this is register syntax in views.py](https://i.stack.imgur.com/US67H.jpg) I've registration form attached as shown above I've created helloworld_Register table in But the data is fetching to user_auth but not to the helloworld_register However data is fetching in user_auth but while logging in with registered credentials it's not logging in !this is login syntax in views.py](https://i.stack.imgur.com/MvV4m.jpg) Can any one sort me this it'll be helpful :) "I've tried fetching data to the helloworld_register but couldn't It's fetching to user_auth However data exist in user_auth It's unable to login." -
How to implement AbstractBaseUser with two user types ("Individual" & "Business"), where user can be both types
I am working on a custom user using AbstractBaseUser, where there are multiple types of user ("individual" users and "business" users). I have defined a User model with these two types and created a separate app for their profiles which will be different depending on the user type. I have used two models to split this out, both with a OnetoOne relationship to the User model, then used proxy models & managers to filter each queryset. The part which I'm struggling with is in that I would like for a user to be able to sign up to both an Individual account, and a Business account using the same email authentication. I.e. one user, can be two types, and therefore access application components which relate to both user types. At the moment I believe they can only be one or the other. Has anyone come across this before or have any ideas of how I might implement this? The tutorials I have found haven't covered this as they have said it is "too complex", but I thought it might just be a case of making the type field a multiple choice field, but not sure if this is the case? -
get_serving_url silently fails with django-storages, app engine, python 3.x
I am trying to get the seving_url for a project that uses django-storages with google cloud storage for media files. I am trying to serve the files with get_serving_url, but I get a silent failure here with no text logged in the exception. The blobkey generates correctly from what I can see however the image = images.get_serving_url(blobkey, secure_url=True) raises an exception with no error text. This is what I have done: #storage_backends.py class GoogleCloudMediaStorage(GoogleCloudStorage): """GoogleCloudStorage suitable for Django's Media files.""" def __init__(self, *args, **kwargs): if not settings.MEDIA_URL: raise Exception('MEDIA_URL has not been configured') kwargs['bucket_name'] = setting('GS_MEDIA_BUCKET_NAME') super(GoogleCloudMediaStorage, self).__init__(*args, **kwargs) #this works fine def url(self, name): """.url that doesn't call Google.""" return urljoin(settings.MEDIA_URL, name) #https://programtalk.com/python-examples/google.appengine.api.images.get_serving_url/_ #This does not work yet def serving_url(self, name): logging.info('serving url called') if settings.DEBUG: return urljoin(settings.MEDIA_URL, name) else: # Your app's GCS bucket and any folder structure you have used. try: logging.info('trying to get serving_url') filename = settings.GS_MEDIA_BUCKET_NAME + '/' + name logging.info(filename) blobkey = blobstore.create_gs_key('/gs/' + filename) logging.info('This is a blobkey') logging.info(blobkey) image = images.get_serving_url(blobkey, secure_url=True) return image except Exception as e: logging.warn('didnt work') logging.warn(e) return urljoin(settings.MEDIA_URL, name) I have appengine-python-standard installed and I have wrapped my application #main.py from antiques_project.wsgi import application from google.appengine.api import … -
Wagtail 4 FieldPanel issue with ForeignKey
I have the following setup in wagtail 4.0.4: @register_snippet class Copyright(models.Model): class CopyrightType(models.TextChoices): PH1 = "PH1", _("Phase 1") PH2 = "PH2", _("Phase 2") type = models.CharField( max_length=3, choices=CopyrightType.choices, unique=True, ) class ReportPage(Page): copyright = models.ForeignKey( Copyright, to_field="type", default="PH2", on_delete=models.SET_DEFAULT, ) Now the set up works just fine. But if I add the FieldPanel: class ReportPage(Page): copyright = models.ForeignKey( Copyright, to_field="type", default="PH2", on_delete=models.SET_DEFAULT, ) promote_panels = Page.promote_panels + [ FieldPanel("copyright"), ] I get the following error: ValueError: Field 'id' expected a number but got 'PH2'. Is there any way to tell the FieldPanel to look at the field referenced in the "to_field" option? -
Django apache image loading slow
I have django deployed with apache2. I'm using static files collected using "./manage.py collectstatic"; noticed png images are loading very slow. Image size is only 130Kb and its taking 2500ms to load. Following is html and css. <img class='image1' src="{% static 'index_background.png' %}" style="width:100%;"> <div class="index_feature">test</div> <img class='image2' src="{% static 'index_banner.png' %}"> .indexbar1 { position: relative; top: 0; left: 0; } .imgage1 { position: relative; top: 0; left: 0; } .image2{ position: absolute; width: 600px; top: 35%; right: 5%; } .index_feature { position: absolute; top: 65%; left: 5%; font: 50px lato-regular, Arial, Helvetica, sans-serif; font-weight: 900; line-height: 150%; color: white; } apache2 is deployed on ubuntu 20.04 vm with 16vcpu and 32gb memory. I could see the same issue while using vscode to run django locally without apache2. I'm missing something in django and need some help. -
Static files are served on django admin site but not on the main website after migrating from Django 1.5 to 2.2.5
My trouble is the following. I did a migration from django 1.5 to 2.2.5. All fine on development environment, but when I deployed it to the internet, static files were being served on admin site but not on the main website. I debug this problem and realize that scheme of the request is passed from http to https and console panel shows the following messages: The scheme is https instead of http. But in django admin site the static files are served under http scheme. For this reason, the static files can be loaded on the site. Also, the login page is loaded correctly, but when I reach the next page, the same problem occurs. I am deploying the application on server without SSL certificates for testing. Initially the web server was apache but I changed it to nginx. I thought the problem was the web server but I was wrong. I want the application can serve the static files correctly under http protocol. -
Optimizing Django Aggregation Over Subsets
I'm currently trying to do some summary statistics calculations for date-based subsets of a large "competition" table (~3M rows) stored in SQLite. Specifically, I'm trying to calculate statistics for: this year last year the lifetime of the competitor Here's a model breakdown: class Competitor(models.Model): # ... ID is the only important part here class Venue(models.Model): # ... ID is the only important part here class Division(models.Model): venue = models.ForeignKey(Venue) # ... class Level(models.Model): division = models.ForeignKey(Division) # ... class Class(models.TextChoices): STANDARD = "Standard", _("Standard") JWW = "JWW", _("JWW") class Run(models.Model): competitor_id = models.ForeignKey(Competitor, related_name="runs", db_index=True) date = models.DateField(verbose_name="Date created", db_index=True) MACH = models.IntegerField(..., db_index=True) PACH = models.IntegerField(..., db_index=True) yps = models.FloatField(..., db_index=True) score = models.IntegerField(..., db_index=True) qualified = models.BooleanField(..., db_index=True) division = models.ForeignKey(Division, db_index=True) level = models.ForeignKey(Level, db_index=True) cls = models.CharField(max_length=..., choices=Class.choices) # ... Other fields that aren't relevant For each Competitor, I want to generate summary statistics that describe their performance this year, last year, and over all time, and store that in a Report model: class CurrPrevLifetime(models.Model): curr_yr = models.FloatField(default=0) prev_yr = models.FloatField(default=0) lifetime = models.FloatField(default=0) class Report(models.Model): ... = models.ForeignKey(CurrPrevLifetime, related_name=...) # repeat as needed for as many fields need this My current aggregation setup looks like … -
I am add url look like en but rosetta did not translate static html word
I am add url look like en but rosetta did not translate static html word How i can resolve this problem I a add all settings for rosetta but it did not work -
How to access the request object inside a custom logging formatter in Django?
I have setup a custom formatter to log my data into a text file in JSON format: class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) log_record['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['level'] = record.levelname log_record['location'] = record.name I would like to be able to automatically access my request object within this formatted since I have a "unique request identifier" that I would like to add to my logs. This way I know which log lines belong to which request. class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) log_record['timestamp'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['level'] = record.levelname log_record['location'] = record.name log_record['request_id'] = request.uuid <--- Something like this Is there a way to achieve this without having to manually pass the request object to every single log line? Many thanks in advance -
How to print data from two different methods next to each other?
I hava a django application and I have two methods that returns different text. And now the data from the two methods are printed under each other. But I want to have them next to each other. So this is the combined twom methods in one method: def combine_methods(self, file_name): self.extractingText.extract_text_from_image(file_name) return '\n'.join(self.filter_verdi_total_number_fruit(file_name)) + " " + '\n'.join( self.filter_verdi_fruit_name(file_name)) And this is the output: 16 360 6 75 9 688 22 80 160 320 160 61 Watermeloenen Watermeloenen Watermeloenen Watermeloenen Watermeloenen Appels Sinaasappels Sinaasappels Sinaasappels Sinaasappels Sinaasappels Sinaasappels But I want to have it like: 16 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen 360 watermeloenen -
Browser cant find file or directory in Django
I am trying to create a qr code and store it on disk. Running the program from my pc works fine, but when I run it on the server (deploy is done in docker), I get this error: [Errno 2] No such file or directory: '/app/static/QR /QR-1-9.png' and the browser also points me to this line of my code with open(UPLOADS_PATHS, 'wb') as f: The route is defined in the settings file like this: QR_ROOT = os.path.join(BASE_DIR, 'static/QR') And this is the view where the qr is stored on disk nombre_archivo = f'QR-{request.user.instituto.id}-{idRecibo}.png' UPLOADS_PATHS = os.path.join(settings.QR_ROOT, nombre_archivo) with open(UPLOADS_PATHS, 'wb') as f: f.write(response.content) I try this on settings.py: QR_ROOT = os.path.join(BASE_DIR, './static/QR') but it does not work -
How to access server data in a javascript file that is loaded by Django admin pages
I need to access server data in a javascript file that gets loaded with an admin page. In my case, I'll need a json variable that is set in the settings.py file (in the production version, this json-variable gets loaded from env-variable which means that the content of the variable is known at startup-time but is not hard coded). I use the javascript to validate and populate some fields in an admin-page - that is a better UX than doing it server side. Is it possible to add script-tag to the admin html-pages' head section, that contains server data, i.e. non-static data? -
Unable to find user django-user: no matching entries in passwd file
I was following a tutorial on docker and django. Not really hard but at one time, i get on this error and i don't understand where is the error on the dockerfile. I understand the error given by docker but dont understand what is wrong in the Dockerfile. Docker file : FROM python:3.9-alpine COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home django-user ENV PATH="/py/bin:$PATH" USER django-user And here is the error : Creating django-deploy-gap_app_run ... done Error response from daemon: unable to find user django-user: no matching entries in passwd file Any help is welcome Thank's ! -
what is the using of Signals in Django?
I'm new to Django and I'm watching a tutorial on youtube, and I have a problem, he using ready functions I don't understand what is the meaning of these functions. my question is .. can anyone explain the (Signals, Senders, and receivers) and their use? if you can recommend someone course for Django I will appreciate it -
Access private GitHub Django repositories on requirements.txt when using AWS Codebuild
I am trying to use AWS Codebuild and am having problems accessing private python Django github repositories from my requirements.txt file. Getting this error "Permission denied (publickey). fatal: Could not read from remote repository." Is there a solution to enable access? -
Possible Race Condition when limiting model creation by count
I have a django view function representing a redemption process of a prize. I'm trying to eliminate the possible race condition when setting a redemption limit based on the count of a linked model (Redemption). At a high level my view function looks like this: def redeem(request, prize_id): # Get a prize model that contains a limit attribute prize = Prize.objects.get(id=prize_id) # Check the count of a set of another model representing redemption objects if (prize.redemption_set.count() >= prize.redemption_limit): return error_page("Reached redemption limit") else: # Run some API calls that redeem the prize # Create a redemption object in the DB redemption = Redemption(prize=prize) redemption.save() So my main concern is when concurrent requests come in I can see the possibility of extra redemptions occurring if the count isn't updated by the time another request comes in. I was looking at select_for_update() and atomic requests but I don't want errors to occur if the model is locked. I mainly want to make sure the redeem calls enter a queue and are rejected appropriately when reaching the redemption limit. I'll have multiple web workers and my DB is mySQL. Thanks for any tips! -
Face error in install Django REST framework
When I write: pip install djangorestframework In CMD show me: Fatal error in launcher: Unable to create process using '"H:\Full Stack\Django\Django_All\project1\env\Scripts\python.exe" "H:\Full Stack\Django\Django_All\project1\studybud\env\Scripts\pip.exe" install djangorestframework': The system cannot find the file specified -
<slug> path converter not working, but literal <slug> in URL works
When I try to visit this URL: http://127.0.0.1:8000/slugtest/ I get 404 page. Here's the message that I get: Using the URLconf defined in scrap.urls, Django tried these URL patterns, in this order: admin/ api-auth/ getpage/ ^<slug>/$ [name='ArticleInfoViewSet-list'] ^<slug>/(?P<slug>[^/.]+)/$ [name='ArticleInfoViewSet-detail'] __debug__/ The current path, slugtest/, didn’t match any of these. However, if I use http://127.0.0.1:8000/<slug>/ the page loads perfectly, but that's not intended behavior. models.py class Article(models.Model): url = models.CharField(max_length=255,validators=[RegexValidator(regex=website_regex)]) slug = models.CharField(max_length=255, null=True) unique_id = models.CharField(max_length=255, unique=True, null=True) views.py class ArticleInfoViewSet(ModelViewSet): serializer_class = ArticleInfoSerializer lookup_url_kwarg = 'slug' lookup_field = 'slug' def get_queryset(self): queryset = Article.objects.prefetch_related('data') return queryset serializer.py class ArticleInfoSerializer(serializers.ModelSerializer): data = ArticleDataSerializer(many=True) class Meta: model = Article fields = ['url', 'data', 'slug'] lookup_field = ['slug'] read_only_fields = ['url', 'data', 'slug'] urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('getpage/', include('getpage.urls')), path('', include('getpage.urls2')), path('__debug__/', include('debug_toolbar.urls')), ] urls2.py from . import views from rest_framework_nested import routers router = routers.SimpleRouter() router.register('<slug>', views.ArticleInfoViewSet, basename='ArticleInfoViewSet') urlpatterns = router.urls What am I doing wrong here? -
Nginx Gunicorn powered server unable to access media in a separate postgresql server
Long story short, my BE dev left midway through setting up my apps' BE server and I'm trying to pick up the pieces to find out what is left to do. I'm by no means any form of a developer, so I apologize in advance for asking silly questions and if I am lacking any details needed to better understand my problem. Will do my best updating this question and be as concise as I can as I go along. Problem The Django admin panel runs in https, but is unable to access the files stored in the database. Current configuration Virtual machine 1 - Docker, Nginx, Gunicorn, Django (admin panel) Virtual machine 2 - postgresql (database) Here are the following file configurations docker-compose.yml version: "3" services: theapp: image: theapp-be/python-3.10-full container_name: theapp-be build: ./ command: bash -c "./deploy.sh" volumes: - ./:/usr/app/ - ./ssl/:/etc/ssl/theapp-BE/ expose: - "80" restart: always nginx: image: theapp-be/nginx container_name: theapp-be-nginx build: ./nginx volumes: - ./:/var/www/theapp-BE/ - ./ssl/:/etc/ssl/theapp-BE/ - ./nginx/config/:/etc/nginx/conf.d/ - ./nginx/log/:/var/log/nginx/ ports: - "80:80" - "443:443" depends_on: - theapp restart: always default.conf (nginx) # Upstreams upstream wsgiserver { ip_hash; server theapp-be:80; } # Redirect to HTTPS server { listen 80; listen [::]:80; server_name theapp; access_log /var/log/nginx/theapp-access.log; error_log … -
Question about sorting by date inside a database using Django
I have a database, in which it's possible to find products by their name. The DB has ID, category, name, amount and date defined, and I was trying to create a separate search field that would let me search those items by the date they were added. The models.py looks like this: class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' And views.py looks like this: class ExpenseListView(ListView): model = Expense paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), **kwargs) I've added the "date" field under the "name", following it's structure, but I kept getting the 'datetime.date' object has no attribute 'strip' error. Is there a different format for defining the date? When I've also added it to the search field in forms.py, it was seen there as a string. I've also found a similar post from How to make date range filter in Django?, but it didn't explained … -
In Django, restrict user view using class based views
I have this url pattern: path("user/<int:pk>", MyAccountView.as_view(), name='my_account'), And this view: class MyAccountView(DetailView): model = CustomUser When the user is logged Django redirect to that URL. The problem is that any user can access other users. For example, if the logged user has pk 25, he can access the view of user with pk 26 by writing in the browser url box: localhost:8000/user/26 I want that each user can access to his user page only, so if user with pk 25 try to access the url with pk 26, the access should be denied. Can you point me in some direction of how this is done? The Django documentation is very confusing in this respect. Thanks. -
How to combine two methods for uploading file?
I have a Django application And I have a upload functionality. And I have two methods that shows the extracted text: def filter_verdi_total_number_fruit(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word) for word in self.extractingText.list_fruit) + ')' return re.findall(regex, self.extractingText.text_factuur_verdi[0]) def filter_verdi_fruit_name(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(?:\d*(?:\.\d+)*)\s*\W+(" + '|'.join(re.escape(word) for word in self.extractingText.list_fruit) + ')' return re.findall(regex, self.extractingText.text_factuur_verdi[0]) But as you can see. There are some duplicate code. Like: file_name and: re.findall(regex, self.extractingText.text_factuur_verdi[0]) So I try to combine this two methods in one method: def combine_methods(self, file_name): self.filter_verdi_total_number_fruit(file_name) self.filter_verdi_fruit_name(file_name) and then I try to call the combined method in the views.py: if uploadfile.image.path.endswith('.pdf'): content ='\n'.join(filter_text.combine_methods(uploadfile.image.path)) But then I get this error: can only join an iterable Exception Location: C:\Users\engel\Documents\NVWA\software\blockchainfruit\main\views.py, line 50, in post Raised during: main.views.ReadingFile Question: how can I change this?