Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am working on a django project and for payment integration we need SSLCOMMERZ python . While installing this problem arises
I am working on a Django project and attempting to install the sslcommerz-python\ package for payment integration. However, I encountered an error during the installation process. Here's the error message: pip install sslcommerz-python Collecting sslcommerz-python ... Building wheels for collected packages: typed-ast Building wheel for typed-ast (setup.py) ... error ... Failed to build typed-ast ERROR: Could not build wheels for typed-ast, which is required to install pyproject.toml-based projects This is the error I get while installing sslcommerz python Thanks in advance for your help. -
Django TextField (CharField) in OuterRef to list with filter _in
I tried filter queryset in Subquery, but can not use filter _in with OuterRef. UserAccount.objects.filter(groups__name__contains=group).annotate( spend=Cast(Subquery(FacebookStatistic.objects.filter( ad_account__id_ad__in=[el.strip() for el in str(OuterRef('facebook_ad_accounts')).split(',')], ).annotate(spd=Coalesce(Func('spend', function='Sum'), 0, output_field=FloatField()) ).values('spd') ), output_field=FloatField()), ) This filter don't work. Text Field not converting to string str(OuterRef('facebook_ad_accounts')) Plese tell me, how can I do it? -
Trouble access django models with celery for background tasks
I'm utilizing Celery within my Django project to execute tasks in the background. However, I've encountered an issue when try to access models using apps "from django.apps import apps". The problem arises when I use this method to access a model, as it raises an "object does not exist" error. Even when I try to resolve it by using relative imports, I still got the same problem. I would greatly appreciate any insights or solutions . If anyone has encountered a similar issue or has knowledge about integrating Celery with Django . ps: Im use Supervisor in order to run celery execution process. here is the celery task from celery import shared_task from django.apps import apps from campaigns.api import send_campaign from campaigns.constants import CampaignStatus from django.core.mail import mail_managers @shared_task def send_campaign_task(campaign_id): Campaign = apps.get_model('campaigns', 'Campaign') try: campaign = Campaign.objects.get(pk=campaign_id) if campaign.campaign_status == CampaignStatus.QUEUED: send_campaign(campaign) mail_managers( f'Mailing campaign has been sent', 'Your campaign "{campaign.email.subject}" is on its way to your subscribers!' ) else: logger.warning( 'Campaign "%s" was placed in a queue with status "%s".' % (campaign_id, campaign.get_campaign_status_display()) ) except Campaign.DoesNotExist: logger.exception( 'Campaign "%s" was placed in a queue but it does not exist.' % campaign_id) and this is the log of … -
Overriding LOGIN_REDIRECT_URL = "page-name" for a specific function in Django
I have a base.py file that states a default redirection page when the user registers and gets logged in. base.py LOGIN_REDIRECT_URL = "index" I want to create to possibility for a user that connects from a specific page page_1 to signup/login directly from this page. When they sign up/login they will be redirected to the same page1 which will show a different content based on whether the user is authenticated or not. (if authenticated they get content, if not they get the signup/login prompt) The problem I am running into (I think) is that when a user register from page_1, this user is redirected to index page as defined in my base.py. Is there a way to override the base.py for a specific function? I left my latest attempt request.session['LOGIN_REDIRECT_URL'] = url. Which didnt work. def show_venue(request, page_id): #REGISTER USER FROM VENUE url = request.META.get('HTTP_REFERER') print(f'url ={url}') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active=True user.save() user = authenticate(username = form.cleaned_data['username'], password = form.cleaned_data['password1'],) login(request,user) request.session['LOGIN_REDIRECT_URL'] = url else: for error in list(form.errors.values()): messages.error(request, error) else: form = RegisterForm() -
login with django in a microservices architecture
I'm trying to login and authenticate my user in a microservices architecture def form_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') api_url = 'http://127.0.0.1:8000/login/' data = { 'username': username, 'password': password, } try: response = requests.post(api_url, data) if response.status_code == 200: print("Usuário autenticado com sucesso.") return redirect('home') elif response.status_code == 400: messages.error(request, 'Credenciais inválidas', extra_tags='login_error') except requests.exceptions.RequestException: messages.error(request, 'Credenciais inválidas', extra_tags='login_error') return render(request, 'login.html') This view takes the username and password from the form and sends it to my API endpoint in the microservice and if the authentication is successful and returns status 200 it redirects to the main page if it returns status 400, it gives an error message class UserLogin(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) print(user) if user is not None: login(request, user) return Response({'detail': 'Autenticação bem sucedida'}, status=status.HTTP_200_OK) else: return Response({'detail': 'Credenciais inválidas'}, status=status.HTTP_400_BAD_REQUEST) This view takes the username and password from the other view, authenticates using django's 'authenticate' if the user exists, logs in with django's 'login' and returns status 200 and if it does not exist, returns status 400 My problem is that: the view sends the username and password, the API gets … -
Django AJAX Form submission is always invalid
I have a Django Project with a view that contains two forms that I want to be submitted with two separate ajax requests. The first ajax request is actually supposed to fill in one value of the second form which this does successfully. Also, the second form has a few initial values that I later plan on making hidden so the user only sees the necessary fields to fill in after submitting the first form. I am passing in an "ajax_type" keyword after checking for "request.is_ajax()" and "request.method == 'POST' within my view to determine if the ajax type is the first ajax request or the second one. My second ajax request makes use of a model form that is supposed to create a new instance of my model upon validation. My View: def canadaTaxEntries(request): newest_record = LAWCHG.objects.aggregate(Max('control_number')) newest_control_number = newest_record["control_number__max"] print(newest_control_number) today = date.today().strftime("1%y%m%d") current_time = time.strftime("%H%M%S") #print(today) #print(current_time) initial_data = { 'control_number': (newest_control_number + 1), 'item_number': None, 'vendor_tax_code': None, 'expiration_flag': 1, 'charge_category': None, 'charge_desc_code': None, 'country': 'US', 'state': None, 'city': None, 'county': None, 'charge_amount': None, 'charge_uom': 'CA', 'charge_percentage': 0.0, 'apply_flag': 1, 'beg_del_date': None, 'end_del_date': None, 'rev_date': today, 'rev_time': current_time, 'est_date': today, 'est_time': current_time, 'program_id': 'BI008', 'operator_id': 'FKRUGER', } … -
Session is not working and showng keyError at task
Hello i was trying to fix my session but it did not work. it shows KeyError at /task/ 'tasK'. I tried many things . I changed the setting but it didnt work too: SESSION_COOKIE_SECURE = True SESSION_COOKIE_SECURE != DEBUG my code is: from django.shortcuts import render from django import forms class TaskForm(forms.Form): input = forms.CharField(label="New Task", max_length=255) # Verwende CharField für Texteingabe def show_task(request): if "tasK" != request.session: request.session["tasK"] = [] return render(request, "hi/j.html", {"tasK": request.session["tasK"]}) def show(request): if request.method == "POST": form = TaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["input"] request.session["tasK"].append(task) # Verwende .append() statt += request.session.modified = True # Speichere die Änderungen in der Session request.session.save() else: return render(request, "hi/j.html", {"form": form}) return render(request, "hi/k.html", {"forms": TaskForm()}) -
Serving image uploads with apache and django
I am programming a ticket system, where users can upload their favorite thing: screenshots with red circles! Each ticket gets an ID and has an upload field. I use one django project with one app that uses this upload function. What I've done I followed the official steps on How to use Django with Apache and mod_wsgi and that works. My website is available under http://localhost. Where I am stuck I am stuck at the next step of the documentation How to authenticate against Django’s user database from Apache When I come to the part where they suggest to add the following code, the whole website gets an 500 Internal Server Error Code to be added to wsgi.py: import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from django.contrib.auth.handlers.modwsgi import check_password from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() I didn't touch nor change the wsgi.py code. I replaced it with the code above from the documentation. And then the 500 Error shows up. Previous code, that I didn't change in wsgi.py that works: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() Below is my project.conf file <VirtualHost *:80> ServerName localhost DocumentRoot /var/www/project/mysite ServerAdmin webmaster@localhost Alias /favicon.ico /var/www/project/mysite/static/tickets/img/ibe.ico Alias /media/ /var/www/mysite/media/ Alias … -
Custom Authentication in Django with Email
i have to do this task For the current project, create the ability to log in with email or username, under these conditions, you should expand the input elements of the registration form and add the ability to log in by email, and then during the review if one of the two matches. The user name or email status should be checked and the user will be allowed to enter and i search a lot about this but i cant find them useful #viws.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.decorators import login_required def login_view(request): if not request.user.is_authenticated: if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') form = AuthenticationForm() context = {'form': form} return render(request, 'accounts/login.html', context) else: return redirect('/') @login_required def logout_view(request): logout(request) return redirect('/') def register_view(request): if not request.user.is_authenticated: if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/') form = UserCreationForm() return render(request, 'accounts/register.html', {"form":form}) else: return redirect('/') i dont hace a forms.py and i dont much code in models -
Tailwind/Flowbite modal hidden behind backdrop
I'm going through the same issue as this 'https://stackoverflow.com/questions/72080009/tailwindflowbite-pop-up-showing-black-screen/77008795?noredirect=1#comment135756693_77008795' developing in django: even with aria-hidden set to true it doesn't work. I'm also really confused because i'm using the same exact modal for the signup and it works perfectly with two cta buttons, the structure is the same, basically copied changing only the ids. Inspecting on the browser the backdrop that appears after i click on it is the same for both modals, i don't understand why the backdrop with z-40 is making it impossible to interact with the login that has z-50. <div id="login_modal" data-modal-backdrop="static" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full"> <div class="relative w-full max-w-md max-h-full"> <!-- Modal content --> <div class="relative bg-darkred rounded-lg shadow"> <button id="close-login_modal" type="button" class="absolute top-3 right-2.5 text-palettewhite hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ml-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-hide="login_modal"> <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/> </svg> <span class="sr-only">Close modal</span> </button> <div class="px-6 py-6 lg:px-8"> <h3 class="mb-4 text-xl font-medium text-palettewhite">Login to our platform</h3> <form class="space-y-6" action="{% url 'home' %}" method="POST"> {% csrf_token %} <div> <label for="username" … -
Setting up a Django form in 2 times
I can't achieve to make a form in 2 times. The values between the 2 forms does not seems to be saved. Whenever the second form is submitted, it brings me back to the first one saying "This field is required." I am trying to set up a Django form that works in 2 times : The first one is asking the user to upload a file in a form. Then, when submitted, there is a function that analyze the file (CSV) and get every values from a row. It then ask the user, in a new form, to select every value he would like. Then, when submitted, it executes a new function. Here is what I've got so far : views.py if choice == '2': site_choices = list(donneesLieux.keys()) # Get the site choices from donneesLieux if request.method == 'POST': if 'csv_choice_data' in request.session: csv_choice_data = request.session['csv_choice_data'] form_site_selection = SiteSelectionForm(request.POST, site_choices=site_choices, initial=csv_choice_data) if form_site_selection.is_valid(): selected_sites = form_site_selection.cleaned_data['selected_sites'] # Merge data for selected sites merged_data = [] for site in selected_sites: merged_data.extend(donneesLieux[site]) output_filename = 'example.xlsx' file_bilan = doExtract(merged_data, output_filename, 1) with open(file_bilan, 'rb') as f: response = HttpResponse(f.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename="{output_filename}"' return response else: form_site_selection = SiteSelectionForm(request.POST, site_choices=site_choices) else: … -
Plotly: make width of boxplots fill gaps between categories
I have the following Plotly plot right now. But as you can see, the boxplots are squished width-wise and after a lot of googling it seems that it is an intended behaviour from Plotly which "reserves" space for every category the total amount of boxplots in the plot (i hope that was clear). But this is pretty illegible. Ideally I'd want the boxplots to take the whole space for every category. I'm using Django 4.1 with Plotly 2.26 in Javascript, so that the plotting can be faster rather than doing everything in the backend. Here is a snippet of the data: sample_1 ... sample_2 2023-08-16|run1 NaN ... NaN 2023-08-16|run2 NaN ... NaN 2023-08-18|run3 NaN ... NaN 2023-08-18|run4 NaN ... NaN 2023-08-18|run5 8530990.0 ... NaN 2023-08-21|run6 NaN ... 10346463.0 Here is the code that i use for that plot: plot_data = plot_data.sort_index() for index in plot_data.index: report_date, project_name = index.split("|") cleaned_data = plot_data.loc[[index]].transpose().dropna().values.flatten().tolist() trace = { "x0": report_date, "y": sorted(cleaned_data), "name": project_name, "type": "box", "marker": { "line": { "outlierwidth": 2 } }, "boxpoints": 'suspectedoutliers', } traces.append(trace) return json.dumps(traces) What is returned is then passed to the template under the plot variable name. <div id="plot-div"></div> <script> var plot_data = JSON.parse("{{plot|escapejs}}"); var layout … -
Celerybeat container dying frequently on container with "corrupted size vs. prev_size"
I have django app working on pod on Openshift. I also have a celerybeat working on the same namespace. My celerybeat is dying many times a day with such issues: corrupted size vs. prev_size free(): invalid pointer malloc(): unaligned tcache chunk detected I don't have any C code there and celerybeat doesn't do anything besides creating new tasks on redis. Do you have any ideas what may be wrong or where to look for the help? So far I've updated python to newer version, insalled top linux tool to check the memory usage. I have no idea what's wrong as the only thing it shows is this C related issue. No python traceback at all. Architecture details: Container: RHEL 8.5 on Openshift 3 Backend: Python3.9 + Django 3.2 Celery: 5.3.1 django-celery-beat: 2.5.0 -
getting data in consume class from service class in python
so i want to get data from socket class with is class BinanceWebSocket: def __init__(self, symbol, interval): self.symbol = symbol self.interval = interval self.latest_price_info = None self.closes = Queue() self.is_force_stopped = False def on_message(self, ws, message): data = json.loads(message) if "k" in data and data["k"]["x"] == True: kline = data["k"] time = data["k"]["T"] / 1000 print(datetime.fromtimestamp(time)) # print(kline) close = kline["c"] self.latest_price_info = close print( "From WEBSOCKET - Latest current price updated: ", self.latest_price_info, ) data_to_send = self.get_data_to_send() self.ws.send(json.dumps(data_to_send)) async def get_data_to_send(self): data = { "symbol": self.symbol, "interval": self.interval, "latest_price": self.latest_price_info, } in my consumer class im trying to do class BinanceConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() self.binance_ws = BinanceWebSocket(symbol, interval, ma_length) asyncio.ensure_future(self.update_data()) async def disconnect(self, close_code): pass async def update_data(self): try: while True: data_to_send = await self.binance_ws.get_data_to_send() print("Data received from BinanceWebSocket:", data_to_send) await self.send(text_data=json.dumps({"data": data_to_send})) await asyncio.sleep(1) except asyncio.CancelledError: pass But im getting default value that initializing in constructor so im cant reach values from on_message method in my consumer, any one can help me with it? -
Selenium within Anaconda
For some time I have been trying to figure out how to handle reading a few different programming books and having other projects. I learned that it would be best through a python virtual environment to manage the package dependencies. However I then needed/wanted to use the same python version. Which I found a version of pyenv for windows, now when I am within the local environments I am still having issues. I have decided to start using the open source program Anaconda to handle my separate projects and there environments. However, I am reading Test Driven Development with Python, Obey the testing GOAT! Which uses Selenium and Django, I have them installed however I am still greeted with another Error message: (django-selenium) C:\Users\Steven Walker\Documents\Projects\Python\tdd-book>python functional_tests.py Traceback (most recent call last): File "C:\Users\Steven Walker\Documents\Projects\Python\tdd-book\functional_tests.py", line 2, in <module> browser = webdriver.Firefox() File "C:\Users\Steven Walker\.conda\envs\django-selenium\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 170, in __init__ RemoteWebDriver.__init__( File "C:\Users\Steven Walker\.conda\envs\django-selenium\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in __init__ ...... I'm sure that I have the geckodriver for Firefox installed, as I am able to use geckodriver --version. I have added the firefox browsers directory to the PATH in environment variables but still no luck. I was wondering if anyone would be able … -
file empty after upload in django admin
I want to save a beforehand created pdf file to my django model in model's save method: class MyModel(BaseModel): pdf_file = models.FileField(upload_to='pdfs',blank=True, null=True) And my mdoel save: def save(self, *args, **kwargs): #create the file at pdf_path with fpdf self.pdf_file.save("myfile.pdf" , open(pdf_path, "r", encoding='ISO8859-1'), save=False) super().save(*args, **kwargs) There is no errors, the file is created at pdf_path and is a 5 page file with content. There is also a file uploaded into the django database but it is an empty 5 page pdf file. -
Django Multi OR Operations
I am trying to do an OR operation for a specific group without knowing the number for each so that it is more than an OR LIKE SELECT * FROM movies WHERE genres LIKE '%Action%' or genres LIKE '%Comedy%' If we assume that I have genres added to it, how can I control the genre so that more than one OR can be chosen for genres without knowing how many genres will be entered? Like Example User input Genres: [Action, Comedy, Horror] as we can see user add new Genres Horror so, my query Muse be SELECT * FROM movies WHERE genres LIKE '%Action%' or genres LIKE '%Comedy%' or genres LIKE '%Horror%' My Simple Script series = series_db.objects.filter(Q(genres__icontains=genres), status=1 ).values('id','title') -
Django Page not found (404) No order item matching the query was found
I'm new to Django and doing my first serious project Why Django returns the error: "Page not found (404) No order item matching the query"? enter image description here application view orders The DataMixin class is used to generate the contents of the main menu. It is used in almost all other views of my application, so it seems to me that the problem is clearly not in it view queryset returns the expected set, despite the fact that Django writes in error <QuerySet [<OrderItem: 31>, <OrderItem: 32>, <OrderItem: 33>, <OrderItem: 34>]> def get_queryset(self): queryset = OrderItem.objects.filter(order_id=self.kwargs['order_id']) print(queryset) return queryset class OrderDetail(DataMixin, DetailView): model = Order template_name = 'orders/order_detail.html' context_object_name = 'order' pk_url_kwarg = 'order_id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context() return context | c_def | {'title': 'Заказ'} def get_queryset(self): queryset = OrderItem.objects.filter(order_id=self.kwargs['order_id']) return queryset main_urls I suspect Django doesn't see my url for some reason. urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls', namespace='home')), path('cart/', include('cart.urls', namespace='cart')), path('orders/', include('orders.urls', namespace='orders')), path('users/', include('users.urls', namespace='users')), ] urls app_name = 'orders' urlpatterns = [ path('order/<int:order_id>/', OrderDetail.as_view(), name='order_detail'), path('create/', OrderCreateView.as_view(), name='order_create'), ] models class Order(models.Model): username = models.CharField(max_length=100, verbose_name='Логин') first_name = models.CharField(max_length=50, verbose_name='Имя') last_name = models.CharField(max_length=50, verbose_name='Фамилия') email = models.EmailField() address … -
Celery beat doesn't pick up tasks
I have a task that is supposed to run every minute and a celery worker. I have placed the celery.py into my main project folder, where wsgi.py is located and it looks like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestTask.settings') app = Celery('TestTask') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60.0, print_hw(), name="print_hw") @app.task def print_hw(): print('hello_world') app.conf.beat_schedule = { 'print_hello_world': { 'task': 'tasks.print_hw', 'schedule': 10.0, } } app.conf.timezone = "UTC" But when I run the command celery -A TestTask beat I only see the following in the console: celery beat v5.3.1 (emerald-rush) is starting. __ - ... __ - _ LocalTime -> 2023-08-30 14:20:04 Configuration -> . broker -> redis://127.0.0.1:6379/0 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s) And nothing happens afterwards, i.e. tasks aren't being identified/executed by the worker. Any idea what I did wrong here or what can be the problem? -
how to integrate django and scrapy and celery?
I have a django project and in its root directory i have a scrapy project that has a spider that should be run every 24 hours and it scrapes provided urls and saves data to a mysql database using django model. i want to shcedule this task using celery beat but i don't know how to integrate django and scrapy project. this is how my project tree looks like: news-website | ├──django_app | └──models.py | ├──news-website | └──settings.py (and other django auto made files are in this directory) | ├──manage.py ├──tasks.py | └──scrapy_project ├──scrapy_project | ├──settings.py | ├──piplines.py | ├──items.py | └──spiders | └──spider.py └──scrapy.cfg i tried to create a file in root directory named as tasks.py and i tried to run my spider in it but when i run tasks.py i get this error. from scrapy_project.items import NewsItem ModuleNotFoundError: No module named 'scrapy_project.items' actually i have this line in my spider.py file: from scrapy_prject.items import NewsItem but since i am running my spider from a script it seems that items file is not accessible for it. how should i fix this problem and how should i use celery with this project for scheduling my scraper? -
Django Rest Framework Role and Permissions having hierarchical relationship
We have two user types: service provide customer each user has following roles- admin service and support operator -reporter but each role has follwoing subrole region admin, region operator, region service and support and with same way to other roles site admin, site operaotor , site service and support in above case service provider and cusotmer has hierarchical relationship. service provider in top of customer. then how to manges role and permission with hierarchical in efficent way ? how to get data in hierarchial way ? then how to manges role and permission with hierarchical in efficent way ? how to get data in hierarchial way ? -
How to serve django static files via kong and nginx
I have Django app, nginx and Kongo. I configured the service and routes. I have a simple web page with a form. In order to display it correctly, you need to load static files such as js, css, png. I don't understand how to tell Kongo routes to static files. django nginx kong deployed in docker. Didn't find any information on how to do it. -
How to integrate OTP sending with Celery into a project?
Here is my viewset and serialsers. I want to integrate OTP sending during user authorization. To pass successful authorization, you need to enter a 6-digit OTP code. How can I do it better? I also want to connect Celery to send OTP codes. from djoser.views import UserViewSet class AccountViewSet(UserViewSet): queryset = User.objects.all() search_fields = ('^username', '^email', '^first_name', '^last_name') from djoser.serializers import UserCreateSerializer as UserCreate from djoser.serializers import UserSerializer class CustomUserCreateSerializer(UserCreate): password = serializers.CharField( max_length=MAX_LENGTH_PASSWORD, required=True, write_only=True, validators=[ MinLengthValidator( limit_value=MIN_LENGTH_PASSWORD, message='Password must be longer than 6 characters' ), MaxLengthValidator( limit_value=MAX_LENGTH_PASSWORD, message='Password must be shorter than 30 characters' ), validate_password ], help_text=( 'Enter password.' 'It must include lowercase and uppercase letters ' 'of the Latin alphabet and numbers.' ), ) email = serializers.EmailField( validators=[ UniqueValidator( message='This email is already taken', queryset=User.objects.all() ), MaxLengthValidator( limit_value=MAX_LENGTH_EMAIL, message=( 'Email must be shorter than' f'{MAX_LENGTH_EMAIL} characters' ) ) ], required=True ) username = serializers.CharField( validators=[ UniqueValidator( message='This username is already taken', queryset=User.objects.all() ), validate_username ], required=True ) first_name = serializers.CharField( max_length=MAX_LENGTH_USERNAME, help_text='Enter your first name', validators=[validate_first_name], required=True ) last_name = serializers.CharField( max_length=MAX_LENGTH_USERNAME, help_text='Enter your last name', validators=[validate_last_name], required=True ) class Meta(UserCreate.Meta): model = User fields = ( 'id', 'email', 'first_name', 'last_name', 'username', 'password' ) class CustomUserSerializer(UserSerializer): … -
Django Image upload missing exif data on Android Chrome devices
I'm having some issues with a project I'm working on at the moment. In testing on my local machine there were no issues, on production there are no issues via a desktop PC but I am experiencing issues on Android Chrome which will be the main use for the application. Essentially I have a simple form in django that takes a few values and has an Image Upload field. I then have the following piece of code at the start of the submission: if request.method == "POST": form = ImageUploadForm(request.POST, request.FILES) image = request.FILES.get('image') print(image) try: x = float(getgpsloc(image)[0]) y = float(getgpsloc(image)[1]) The process will upload the file, take the GPS and some other exif data and if valid submit some of this information to the database and at the same time strip the exif data from the image and rename the file so there is no user identifiable information. As noted, on PC this works fine, the getgpsloc function reads all of the exif fields as expected. On Android Chrome however it appears as though only a couple of the exif data fields are present in the image file that is then causing a divde by zero error as … -
Why is running django app in cmd giving me a module error?
each time I try to run my django app it is giving me this error( ModuleNotFoundError: No module named 'django.contrib.genresdjango') The genres is the page iam trying to create I tried removing the line from the django settings.py it is running perfectly but when i add the line for my app it is not